@vite-hub/cli 0.0.4 → 0.3.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/README.md +82 -12
- package/dist/commands-DPg3kL8m.js +3104 -0
- package/dist/console-auth-xl7kLQNt.js +315 -0
- package/dist/console-env-C5YeAm2-.js +198 -0
- package/dist/env-DzoVtVJO.js +5820 -0
- package/dist/envelope-Cf56AJLa.js +88 -0
- package/dist/index.d.ts +38 -10
- package/dist/index.js +1462 -218
- package/dist/provision-C9p1wSzq.d.ts +170 -0
- package/dist/provision-D8OvBBzi.js +2262 -0
- package/dist/setup/index.d.ts +919 -0
- package/dist/setup/index.js +231 -0
- package/package.json +46 -16
package/dist/index.js
CHANGED
|
@@ -1,210 +1,1252 @@
|
|
|
1
|
-
|
|
1
|
+
import { A as operationInputJsonSchema, B as isRecord, D as operationCliPath, E as operationCall, F as collectViteHubCliContribution, I as createCliDiscoveryNitroCloser, L as findViteHubDevServerUrl, M as setupCommandNames, N as resolveViteHubProjectRoot, O as operationsOf, R as getStableStdoutWrite, S as callOperation, T as createOperationRegistry, b as loadAllEnv, h as PROVISION_STATE_FILE, j as reservedOperationNamespaces, k as parseOperationInput, m as cliErrorDiagnostics, t as createProvisionNamespace, v as readProvisionStateSync, w as collectOperationContributions, x as withViteStageEnvironment, z as withStdoutOnStderr } from "./provision-D8OvBBzi.js";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { existsSync, readFileSync,
|
|
4
|
-
import process from "node:process";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
//#region ../internal/dist/
|
|
9
|
-
async function
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
async function collectViteHubCliNamespaces(plugins) {
|
|
13
|
-
const namespaces = /* @__PURE__ */ new Map();
|
|
3
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
4
|
+
import process$1 from "node:process";
|
|
5
|
+
import { basename, dirname, relative, resolve } from "pathe";
|
|
6
|
+
import { createInterface } from "node:readline/promises";
|
|
7
|
+
import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
8
|
+
//#region ../internal/dist/inspect.js
|
|
9
|
+
async function collectContributors(plugins) {
|
|
10
|
+
const contributors = [];
|
|
14
11
|
for (const plugin of plugins) {
|
|
15
|
-
if (!plugin || typeof plugin !== "object") continue;
|
|
12
|
+
if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
16
13
|
const metadata = plugin.vitehub;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (!existing) {
|
|
22
|
-
namespaces.set(namespace.name, {
|
|
23
|
-
...namespace,
|
|
24
|
-
features: [...namespace.features]
|
|
25
|
-
});
|
|
26
|
-
continue;
|
|
27
|
-
}
|
|
28
|
-
const features = new Map(existing.features.map((feature) => [feature.name, feature]));
|
|
29
|
-
for (const feature of namespace.features) features.set(feature.name, feature);
|
|
30
|
-
existing.features = [...features.values()];
|
|
31
|
-
}
|
|
14
|
+
if (!metadata || typeof metadata !== "object" || !Object.hasOwn(metadata, "inspect")) continue;
|
|
15
|
+
const value = metadata.inspect;
|
|
16
|
+
const contributor = typeof value === "function" ? await value() : value;
|
|
17
|
+
if (contributor) contributors.push(contributor);
|
|
32
18
|
}
|
|
33
|
-
return
|
|
19
|
+
return contributors;
|
|
34
20
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
21
|
+
/** Collects Definition inspectors from active plugins. A later plugin replaces an earlier inspector of the same kind. */
|
|
22
|
+
async function collectViteHubDefinitionInspectors(plugins) {
|
|
23
|
+
const inspectors = /* @__PURE__ */ new Map();
|
|
24
|
+
for (const contributor of await collectContributors(plugins)) for (const inspector of contributor.definitions ?? []) inspectors.set(inspector.kind, inspector);
|
|
25
|
+
return [...inspectors.values()];
|
|
26
|
+
}
|
|
27
|
+
/** Collects Provider Output entries from active plugins, keyed by path. */
|
|
28
|
+
async function collectViteHubProviderOutputEntries(plugins) {
|
|
29
|
+
const entries = /* @__PURE__ */ new Map();
|
|
30
|
+
for (const contributor of await collectContributors(plugins)) for (const entry of contributor.providerOutput ?? []) entries.set(entry.path, entry);
|
|
31
|
+
return [...entries.values()];
|
|
32
|
+
}
|
|
33
|
+
/** Collects host resources from active plugins in plugin order. */
|
|
34
|
+
async function collectViteHubResourceSummaries(plugins) {
|
|
35
|
+
const resources = [];
|
|
36
|
+
for (const contributor of await collectContributors(plugins)) resources.push(...await contributor.resources?.() ?? []);
|
|
37
|
+
return resources;
|
|
38
|
+
}
|
|
39
|
+
const redactedInspectionValue = "[redacted]";
|
|
40
|
+
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
41
|
+
const secretValuePattern = /^(?:[a-z][a-z0-9+.-]*:\/\/[^/\s?#]*@|bearer\s)/i;
|
|
42
|
+
/** Whether an inspection field names a credential, regardless of its value. */
|
|
43
|
+
function isSecretInspectionKey(key) {
|
|
44
|
+
return secretKeyPattern.test(key);
|
|
45
|
+
}
|
|
46
|
+
const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
|
|
47
|
+
const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
|
|
48
|
+
const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
|
|
49
|
+
const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
|
|
50
|
+
const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
|
|
51
|
+
/**
|
|
52
|
+
* Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
|
|
53
|
+
* `name=value` pairs with a secret name are replaced with `[redacted]`.
|
|
54
|
+
*/
|
|
55
|
+
function redactInspectionText(value) {
|
|
56
|
+
return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Removes values that can carry credentials before inspection output leaves the process.
|
|
60
|
+
* Keys that name secrets, plaintext Worker `vars`, and URLs with embedded credentials are redacted.
|
|
61
|
+
*/
|
|
62
|
+
function redactInspectionValue(value, key) {
|
|
63
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
64
|
+
let remaining = 1e3;
|
|
65
|
+
function visit(entry, entryKey, depth = 0) {
|
|
66
|
+
if (entryKey && isSecretInspectionKey(entryKey)) return redactedInspectionValue;
|
|
67
|
+
if (--remaining < 0 || depth > 10) return "[truncated]";
|
|
68
|
+
if (typeof entry === "string") {
|
|
69
|
+
const text = entry.slice(0, 1e4);
|
|
70
|
+
return secretValuePattern.test(text) ? redactedInspectionValue : redactInspectionText(text);
|
|
71
|
+
}
|
|
72
|
+
if (typeof entry === "bigint") return entry.toString();
|
|
73
|
+
if (typeof entry === "number") return Number.isFinite(entry) ? entry : String(entry);
|
|
74
|
+
if (entry === null || typeof entry === "boolean") return entry;
|
|
75
|
+
if (typeof entry !== "object") return entry === void 0 ? null : "[unsupported]";
|
|
76
|
+
if (seen.has(entry)) return "[circular]";
|
|
77
|
+
seen.add(entry);
|
|
78
|
+
try {
|
|
79
|
+
let dateTime;
|
|
80
|
+
try {
|
|
81
|
+
dateTime = Date.prototype.getTime.call(entry);
|
|
82
|
+
} catch {}
|
|
83
|
+
if (dateTime !== void 0) return Number.isNaN(dateTime) ? "Invalid Date" : Date.prototype.toISOString.call(entry);
|
|
84
|
+
if (Array.isArray(entry)) return entry.slice(0, 100).map((item) => visit(item, void 0, depth + 1));
|
|
85
|
+
let setValues;
|
|
86
|
+
try {
|
|
87
|
+
setValues = [...Set.prototype.values.call(entry)];
|
|
88
|
+
} catch {}
|
|
89
|
+
if (setValues) return setValues.slice(0, 100).map((item) => visit(item, void 0, depth + 1));
|
|
90
|
+
let mapEntries;
|
|
91
|
+
try {
|
|
92
|
+
mapEntries = [...Map.prototype.entries.call(entry)];
|
|
93
|
+
} catch {}
|
|
94
|
+
const entries = mapEntries ? mapEntries.map(([name, item]) => [String(name), item]) : Object.entries(entry);
|
|
95
|
+
return Object.fromEntries(entries.slice(0, 100).map(([name, item]) => [name, name === "vars" && item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).slice(0, 100).map((variable) => [variable, redactedInspectionValue])) : visit(item, name, depth + 1)]));
|
|
96
|
+
} finally {
|
|
97
|
+
seen.delete(entry);
|
|
98
|
+
}
|
|
41
99
|
}
|
|
42
|
-
return
|
|
100
|
+
return visit(value, key);
|
|
43
101
|
}
|
|
44
102
|
//#endregion
|
|
45
|
-
//#region
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
103
|
+
//#region src/drain.ts
|
|
104
|
+
/** `vitehub drain MAINPID [STATUS_URL]`, for a service manager that stops a Node server. It needs no project. */
|
|
105
|
+
const drainCommand = {
|
|
106
|
+
description: "Drain a running Node server before it stops, for systemd ExecStop. Needs no project.",
|
|
107
|
+
name: "drain",
|
|
108
|
+
run: async (args, context) => {
|
|
109
|
+
const { runDrain } = await import("@vite-hub/runtime/internal/drain");
|
|
110
|
+
return await runDrain(args, context);
|
|
111
|
+
},
|
|
112
|
+
usage: "vitehub drain MAINPID [STATUS_URL]"
|
|
113
|
+
};
|
|
114
|
+
//#endregion
|
|
115
|
+
//#region src/inspect.ts
|
|
116
|
+
const definitionsUsage = "vitehub inspect definitions [--kind <kind>] [--json]";
|
|
117
|
+
const providerOutputUsage = "vitehub inspect output [--json]";
|
|
118
|
+
const resourcesUsage = "vitehub inspect resources [--json]";
|
|
119
|
+
const routesUsage = "vitehub inspect routes [--json]";
|
|
120
|
+
function parseArgs$1(args, options) {
|
|
121
|
+
const parsed = {
|
|
122
|
+
help: false,
|
|
123
|
+
json: false
|
|
124
|
+
};
|
|
125
|
+
for (let index = 0; index < args.length; index++) {
|
|
126
|
+
const arg = args[index];
|
|
127
|
+
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
128
|
+
else if (arg === "--json") parsed.json = true;
|
|
129
|
+
else if (options.kind && arg === "--kind") {
|
|
130
|
+
const kind = args[index + 1];
|
|
131
|
+
if (!kind || kind.startsWith("-")) parsed.error ??= "Option --kind requires a value.";
|
|
132
|
+
else {
|
|
133
|
+
parsed.kind = kind;
|
|
134
|
+
index++;
|
|
135
|
+
}
|
|
136
|
+
} else if (options.kind && arg?.startsWith("--kind=")) {
|
|
137
|
+
const kind = arg.slice(7);
|
|
138
|
+
if (!kind) parsed.error ??= "Option --kind requires a value.";
|
|
139
|
+
else parsed.kind = kind;
|
|
140
|
+
} else if (arg) parsed.error ??= `Unknown inspect argument: ${arg}`;
|
|
141
|
+
}
|
|
142
|
+
return parsed;
|
|
49
143
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
144
|
+
function writeJson(context, value) {
|
|
145
|
+
context.stdout.write(`${JSON.stringify(redactInspectionValue(value), null, 2)}\n`);
|
|
146
|
+
}
|
|
147
|
+
function redactSummary(summary) {
|
|
148
|
+
return {
|
|
149
|
+
...summary,
|
|
150
|
+
fields: summary.fields.map((field) => ({
|
|
151
|
+
label: field.label,
|
|
152
|
+
value: String(redactInspectionValue(field.value, field.label))
|
|
153
|
+
}))
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** The operations of the app as one Definition kind. */
|
|
157
|
+
function operationInspector(operations) {
|
|
158
|
+
return {
|
|
159
|
+
kind: "operation",
|
|
160
|
+
label: "Operations",
|
|
161
|
+
list: () => operations.map((operation) => ({
|
|
162
|
+
fields: [
|
|
163
|
+
{
|
|
164
|
+
label: "Kind",
|
|
165
|
+
value: operation.kind
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
label: "Section",
|
|
169
|
+
value: typeof operation.section === "string" ? operation.section : operation.section === false ? "any" : "from input"
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
label: "Description",
|
|
173
|
+
value: operation.description
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
label: "Command",
|
|
177
|
+
value: `vitehub ${operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, operation.name.indexOf(".")))} ${operation.cli?.command ?? operation.name.slice(operation.name.indexOf(".") + 1)}`
|
|
178
|
+
}
|
|
179
|
+
],
|
|
180
|
+
file: "operations",
|
|
181
|
+
name: operation.name,
|
|
182
|
+
source: "operations"
|
|
183
|
+
}))
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
async function runDefinitions(args, context, plugins, operations) {
|
|
187
|
+
const parsed = parseArgs$1(args, { kind: true });
|
|
188
|
+
if (parsed.help) {
|
|
189
|
+
context.stdout.write([
|
|
190
|
+
`Usage: ${definitionsUsage}`,
|
|
191
|
+
"",
|
|
192
|
+
"Lists the Definitions that each active package discovered.",
|
|
193
|
+
"",
|
|
194
|
+
"Options:",
|
|
195
|
+
" --kind <kind> Show one kind only, for example queue or rate-limit.",
|
|
196
|
+
" --json Print machine-readable JSON.",
|
|
197
|
+
" -h, --help Show this help.",
|
|
198
|
+
""
|
|
199
|
+
].join("\n"));
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
if (parsed.error) {
|
|
203
|
+
context.stderr.write(`${parsed.error}\nUsage: ${definitionsUsage}\n`);
|
|
204
|
+
return 1;
|
|
205
|
+
}
|
|
206
|
+
const inspectors = [...await collectViteHubDefinitionInspectors(plugins), ...operations.length ? [operationInspector(operations)] : []];
|
|
207
|
+
const selected = parsed.kind ? inspectors.filter((inspector) => inspector.kind === parsed.kind) : inspectors;
|
|
208
|
+
if (parsed.kind && !selected.length) {
|
|
209
|
+
const kinds = inspectors.map((inspector) => inspector.kind).sort();
|
|
210
|
+
context.stderr.write(`Unknown Definition kind: ${parsed.kind}\nAvailable kinds: ${kinds.length ? kinds.join(", ") : "none"}\n`);
|
|
211
|
+
return 1;
|
|
212
|
+
}
|
|
213
|
+
const groups = await Promise.all(selected.map(async (inspector) => ({
|
|
214
|
+
definitions: (await inspector.list()).map(redactSummary),
|
|
215
|
+
kind: inspector.kind,
|
|
216
|
+
label: inspector.label
|
|
217
|
+
})));
|
|
218
|
+
if (parsed.json) {
|
|
219
|
+
writeJson(context, { definitions: groups });
|
|
220
|
+
return 0;
|
|
221
|
+
}
|
|
222
|
+
if (!groups.length) {
|
|
223
|
+
context.stdout.write("No package contributes Definition inspection.\n");
|
|
224
|
+
return 0;
|
|
225
|
+
}
|
|
226
|
+
const lines = [];
|
|
227
|
+
for (const group of groups) {
|
|
228
|
+
lines.push(`${group.label} (${group.kind}): ${group.definitions.length}`);
|
|
229
|
+
if (!group.definitions.length) lines.push(" No Definitions discovered.");
|
|
230
|
+
for (const definition of group.definitions) {
|
|
231
|
+
lines.push(` ${definition.name} ${definition.file} [${definition.source}]`);
|
|
232
|
+
for (const field of definition.fields) lines.push(` ${field.label}: ${field.value}`);
|
|
233
|
+
}
|
|
234
|
+
lines.push("");
|
|
235
|
+
}
|
|
236
|
+
context.stdout.write(lines.join("\n"));
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
239
|
+
function readProviderOutputEntry(rootDir, entry) {
|
|
240
|
+
const path = relative(rootDir, entry.path) || ".";
|
|
241
|
+
if (!existsSync(entry.path)) return {
|
|
242
|
+
description: entry.description,
|
|
243
|
+
exists: false,
|
|
244
|
+
owner: entry.owner,
|
|
245
|
+
path
|
|
246
|
+
};
|
|
247
|
+
const directory = statSync(entry.path).isDirectory();
|
|
248
|
+
const report = {
|
|
249
|
+
description: entry.description,
|
|
250
|
+
exists: true,
|
|
251
|
+
owner: entry.owner,
|
|
252
|
+
path,
|
|
253
|
+
type: directory ? "directory" : "file"
|
|
254
|
+
};
|
|
255
|
+
if (!directory && entry.path.endsWith(".json")) try {
|
|
256
|
+
report.content = JSON.parse(readFileSync(entry.path, "utf8"));
|
|
53
257
|
} catch {
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
258
|
+
report.content = "[unreadable JSON]";
|
|
259
|
+
}
|
|
260
|
+
return report;
|
|
261
|
+
}
|
|
262
|
+
async function runProviderOutput(args, context, plugins) {
|
|
263
|
+
const parsed = parseArgs$1(args, { kind: false });
|
|
264
|
+
if (parsed.help) {
|
|
265
|
+
context.stdout.write([
|
|
266
|
+
`Usage: ${providerOutputUsage}`,
|
|
267
|
+
"",
|
|
268
|
+
"Lists generated Provider Output files and shows which exist.",
|
|
269
|
+
"Run a production build first to generate deployment output.",
|
|
270
|
+
"JSON output includes file contents with credentials and Worker vars redacted.",
|
|
271
|
+
"",
|
|
272
|
+
"Options:",
|
|
273
|
+
" --json Print machine-readable JSON.",
|
|
274
|
+
" -h, --help Show this help.",
|
|
275
|
+
""
|
|
276
|
+
].join("\n"));
|
|
277
|
+
return 0;
|
|
278
|
+
}
|
|
279
|
+
if (parsed.error) {
|
|
280
|
+
context.stderr.write(`${parsed.error}\nUsage: ${providerOutputUsage}\n`);
|
|
281
|
+
return 1;
|
|
282
|
+
}
|
|
283
|
+
const reports = [...await collectViteHubProviderOutputEntries(plugins), {
|
|
284
|
+
description: "Provision State with non-secret provider resource ids",
|
|
285
|
+
owner: "cli",
|
|
286
|
+
path: resolve(context.rootDir, PROVISION_STATE_FILE)
|
|
287
|
+
}].map((entry) => readProviderOutputEntry(context.rootDir, entry)).sort((left, right) => left.path.localeCompare(right.path));
|
|
288
|
+
if (parsed.json) {
|
|
289
|
+
const provisionPath = relative(context.rootDir, resolve(context.rootDir, ".vitehub/provision.json")) || ".";
|
|
290
|
+
const providerOutput = reports.map((report) => {
|
|
291
|
+
if (report.path === provisionPath && report.exists && report.owner === "cli" && report.type === "file" && report.content !== "[unreadable JSON]") {
|
|
292
|
+
const provisionState = readProvisionStateSync(context.rootDir);
|
|
293
|
+
const provisionStateOutput = Object.fromEntries(Object.entries(provisionState).map(([provider, categories]) => [provider, Object.fromEntries(Object.entries(categories ?? {}).map(([category, ids]) => [category, Object.fromEntries(Object.entries(ids ?? {}).map(([key, id]) => [key, redactInspectionValue(id)]))]))]));
|
|
294
|
+
return {
|
|
295
|
+
...report,
|
|
296
|
+
content: provisionStateOutput
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
return redactInspectionValue(report);
|
|
300
|
+
});
|
|
301
|
+
context.stdout.write(`${JSON.stringify({ providerOutput }, null, 2)}\n`);
|
|
302
|
+
return 0;
|
|
303
|
+
}
|
|
304
|
+
const present = reports.filter((report) => report.exists);
|
|
305
|
+
const missing = reports.filter((report) => !report.exists);
|
|
306
|
+
const lines = [`Provider Output: ${present.length} of ${reports.length} present`];
|
|
307
|
+
for (const report of present) lines.push(` ${report.path} (${report.owner}) ${report.description}`);
|
|
308
|
+
if (missing.length) {
|
|
309
|
+
lines.push("", "Not generated:");
|
|
310
|
+
for (const report of missing) lines.push(` ${report.path} (${report.owner}) ${report.description}`);
|
|
311
|
+
}
|
|
312
|
+
lines.push("");
|
|
313
|
+
context.stdout.write(lines.join("\n"));
|
|
314
|
+
return 0;
|
|
315
|
+
}
|
|
316
|
+
const wranglerIdFields = {
|
|
317
|
+
"cloudflare-d1": ["d1_databases", "database_id"],
|
|
318
|
+
"cloudflare-kv-namespace": ["kv_namespaces", "id"]
|
|
319
|
+
};
|
|
320
|
+
function readGeneratedWranglerIds(entries) {
|
|
321
|
+
const ids = /* @__PURE__ */ new Map();
|
|
322
|
+
for (const entry of entries) {
|
|
323
|
+
if (basename(entry.path) !== "wrangler.json" || !existsSync(entry.path) || !statSync(entry.path).isFile()) continue;
|
|
324
|
+
let config;
|
|
325
|
+
try {
|
|
326
|
+
config = JSON.parse(readFileSync(entry.path, "utf8"));
|
|
327
|
+
} catch {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (!config || typeof config !== "object") continue;
|
|
331
|
+
for (const [kind, [field, idField]] of Object.entries(wranglerIdFields)) {
|
|
332
|
+
const bindings = Reflect.get(config, field);
|
|
333
|
+
if (!Array.isArray(bindings)) continue;
|
|
334
|
+
for (const binding of bindings) {
|
|
335
|
+
const name = binding && typeof binding === "object" ? Reflect.get(binding, "binding") : void 0;
|
|
336
|
+
const id = binding && typeof binding === "object" ? Reflect.get(binding, idField) : void 0;
|
|
337
|
+
if (typeof name === "string" && typeof id === "string" && id && !ids.has(`${kind}:${name}`)) ids.set(`${kind}:${name}`, id);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return ids;
|
|
342
|
+
}
|
|
343
|
+
function describeSource(resource) {
|
|
344
|
+
switch (resource.source) {
|
|
345
|
+
case "config": return "config";
|
|
346
|
+
case "env": return `env ${resource.env ?? ""}`.trim();
|
|
347
|
+
case "name": return "bound by name";
|
|
348
|
+
case "provider-output": return "generated provider output";
|
|
349
|
+
case "provision-state": return PROVISION_STATE_FILE;
|
|
350
|
+
default: return "none";
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async function runResources(args, context, plugins) {
|
|
354
|
+
const parsed = parseArgs$1(args, { kind: false });
|
|
355
|
+
if (parsed.help) {
|
|
356
|
+
context.stdout.write([
|
|
357
|
+
`Usage: ${resourcesUsage}`,
|
|
358
|
+
"",
|
|
359
|
+
"Lists the host resources that Definitions and stores map to: D1, KV, R2, Queues, Vercel Blob, and the Sandbox Durable Object and Container.",
|
|
360
|
+
"Shows each resource name, its id, and where the id came from: config, env, Provision State, generated provider output, or the host binds it by name.",
|
|
361
|
+
"Reads local config and files only. It never calls a provider API.",
|
|
362
|
+
"",
|
|
363
|
+
"Options:",
|
|
364
|
+
" --json Print machine-readable JSON.",
|
|
365
|
+
" -h, --help Show this help.",
|
|
366
|
+
""
|
|
367
|
+
].join("\n"));
|
|
368
|
+
return 0;
|
|
369
|
+
}
|
|
370
|
+
if (parsed.error) {
|
|
371
|
+
context.stderr.write(`${parsed.error}\nUsage: ${resourcesUsage}\n`);
|
|
372
|
+
return 1;
|
|
373
|
+
}
|
|
374
|
+
const generatedIds = readGeneratedWranglerIds(await collectViteHubProviderOutputEntries(plugins));
|
|
375
|
+
const resources = (await collectViteHubResourceSummaries(plugins)).map((resource) => {
|
|
376
|
+
const generatedId = resource.id || !resource.binding ? void 0 : generatedIds.get(`${resource.kind}:${resource.binding}`);
|
|
377
|
+
return generatedId ? {
|
|
378
|
+
...resource,
|
|
379
|
+
id: generatedId,
|
|
380
|
+
source: "provider-output"
|
|
381
|
+
} : resource;
|
|
382
|
+
});
|
|
383
|
+
if (parsed.json) {
|
|
384
|
+
writeJson(context, { resources });
|
|
385
|
+
return 0;
|
|
386
|
+
}
|
|
387
|
+
if (!resources.length) {
|
|
388
|
+
context.stdout.write("No Definition maps to a host resource.\n");
|
|
389
|
+
return 0;
|
|
390
|
+
}
|
|
391
|
+
const lines = [];
|
|
392
|
+
for (const resource of resources) {
|
|
393
|
+
lines.push(`${resource.host}\t${resource.kind}\t${resource.definition}`);
|
|
394
|
+
if (resource.name) lines.push(` Name: ${resource.name}`);
|
|
395
|
+
if (resource.binding) lines.push(` Binding: ${resource.binding}`);
|
|
396
|
+
if (resource.id) lines.push(` Id: ${String(redactInspectionValue(resource.id, "id"))}`);
|
|
397
|
+
lines.push(` Source: ${describeSource(resource)}`);
|
|
398
|
+
if (resource.note) lines.push(` Note: ${resource.note}`);
|
|
399
|
+
}
|
|
400
|
+
lines.push("");
|
|
401
|
+
context.stdout.write(lines.join("\n"));
|
|
402
|
+
return 0;
|
|
403
|
+
}
|
|
404
|
+
function findPackage(file) {
|
|
405
|
+
for (let dir = dirname(file); dir !== dirname(dir); dir = dirname(dir)) {
|
|
406
|
+
const manifest = resolve(dir, "package.json");
|
|
407
|
+
if (!existsSync(manifest)) continue;
|
|
408
|
+
const name = Reflect.get(Object(JSON.parse(readFileSync(manifest, "utf8"))), "name");
|
|
409
|
+
if (typeof name === "string") return {
|
|
410
|
+
dir,
|
|
411
|
+
name
|
|
72
412
|
};
|
|
73
413
|
}
|
|
74
|
-
return merged;
|
|
75
414
|
}
|
|
76
|
-
function
|
|
77
|
-
const
|
|
78
|
-
|
|
415
|
+
function routeHandler(rootDir, file) {
|
|
416
|
+
const path = relative(rootDir, file);
|
|
417
|
+
const generated = file.lastIndexOf("/.vitehub/");
|
|
418
|
+
if (generated !== -1) {
|
|
419
|
+
const [first, second] = file.slice(generated + 10).split("/");
|
|
420
|
+
return {
|
|
421
|
+
handler: path,
|
|
422
|
+
owner: (first === "nitro" ? second : first) || "vite-hub"
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
const owned = path.startsWith("..") || path.split("/").includes("node_modules") ? findPackage(file) : void 0;
|
|
426
|
+
return owned ? {
|
|
427
|
+
handler: `${owned.name}/${relative(owned.dir, file)}`,
|
|
428
|
+
owner: owned.name
|
|
429
|
+
} : {
|
|
430
|
+
handler: path,
|
|
431
|
+
owner: "app"
|
|
432
|
+
};
|
|
79
433
|
}
|
|
80
|
-
function
|
|
81
|
-
|
|
434
|
+
function readRoutes(rootDir, handlers) {
|
|
435
|
+
const routes = [];
|
|
436
|
+
const seen = /* @__PURE__ */ new Set();
|
|
437
|
+
for (const entry of handlers) {
|
|
438
|
+
const handler = Reflect.get(Object(entry), "handler");
|
|
439
|
+
if (typeof handler !== "string") continue;
|
|
440
|
+
const middleware = Reflect.get(Object(entry), "middleware") === true;
|
|
441
|
+
const route = Reflect.get(Object(entry), "route");
|
|
442
|
+
const methods = Reflect.get(Object(entry), "method");
|
|
443
|
+
const method = typeof methods === "string" ? methods.toUpperCase() : Array.isArray(methods) && methods.length ? methods.map(String).join(",").toUpperCase() : "*";
|
|
444
|
+
const report = {
|
|
445
|
+
.../^[#\u0000]/.test(handler) ? {
|
|
446
|
+
handler,
|
|
447
|
+
owner: "app"
|
|
448
|
+
} : routeHandler(rootDir, resolve(rootDir, handler)),
|
|
449
|
+
method,
|
|
450
|
+
...middleware ? { middleware: true } : {},
|
|
451
|
+
route: typeof route === "string" && route ? route : "/**"
|
|
452
|
+
};
|
|
453
|
+
const key = `${report.method} ${report.route} ${report.handler} ${middleware}`;
|
|
454
|
+
if (seen.has(key)) continue;
|
|
455
|
+
seen.add(key);
|
|
456
|
+
routes.push(report);
|
|
457
|
+
}
|
|
458
|
+
return [...routes.filter((route) => route.middleware), ...routes.filter((route) => !route.middleware)];
|
|
82
459
|
}
|
|
83
|
-
function
|
|
84
|
-
|
|
85
|
-
|
|
460
|
+
async function runRoutes(args, context, handlers) {
|
|
461
|
+
const parsed = parseArgs$1(args, { kind: false });
|
|
462
|
+
if (parsed.help) {
|
|
463
|
+
context.stdout.write([
|
|
464
|
+
`Usage: ${routesUsage}`,
|
|
465
|
+
"",
|
|
466
|
+
"Lists the server routes and middleware that ViteHub and other Vite plugins add to the production build.",
|
|
467
|
+
"Shows each method, path, owner, and handler file. Routes in server/routes and server/api are not listed.",
|
|
468
|
+
"",
|
|
469
|
+
"Options:",
|
|
470
|
+
" --json Print machine-readable JSON.",
|
|
471
|
+
" -h, --help Show this help.",
|
|
472
|
+
""
|
|
473
|
+
].join("\n"));
|
|
474
|
+
return 0;
|
|
475
|
+
}
|
|
476
|
+
if (parsed.error) {
|
|
477
|
+
context.stderr.write(`${parsed.error}\nUsage: ${routesUsage}\n`);
|
|
478
|
+
return 1;
|
|
479
|
+
}
|
|
480
|
+
const routes = readRoutes(context.rootDir, handlers);
|
|
481
|
+
if (parsed.json) {
|
|
482
|
+
writeJson(context, { routes });
|
|
483
|
+
return 0;
|
|
484
|
+
}
|
|
485
|
+
if (!routes.length) {
|
|
486
|
+
context.stdout.write("No plugin adds a server route.\n");
|
|
487
|
+
return 0;
|
|
488
|
+
}
|
|
489
|
+
const methodWidth = Math.max(6, ...routes.map((route) => route.method.length));
|
|
490
|
+
const routeWidth = Math.max(4, ...routes.map((route) => route.route.length));
|
|
491
|
+
const ownerWidth = Math.max(5, ...routes.map((route) => route.owner.length));
|
|
492
|
+
const lines = [`${"METHOD".padEnd(methodWidth)} ${"PATH".padEnd(routeWidth)} ${"OWNER".padEnd(ownerWidth)} HANDLER`];
|
|
493
|
+
for (const route of routes) lines.push(`${route.method.padEnd(methodWidth)} ${route.route.padEnd(routeWidth)} ${route.owner.padEnd(ownerWidth)} ${route.handler}${route.middleware ? " (middleware)" : ""}`);
|
|
494
|
+
lines.push("");
|
|
495
|
+
context.stdout.write(lines.join("\n"));
|
|
496
|
+
return 0;
|
|
86
497
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
function resolveCloudflareProvisionConfig(env) {
|
|
90
|
-
const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
|
|
91
|
-
const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
|
|
92
|
-
if (!accountId || !token) return;
|
|
498
|
+
/** Built-in namespace that renders package-owned inspection data. */
|
|
499
|
+
function createInspectNamespace(plugins, operations = [], handlers = []) {
|
|
93
500
|
return {
|
|
94
|
-
|
|
95
|
-
|
|
501
|
+
description: "Inspect discovered Definitions, host resources, server routes, and generated Provider Output.",
|
|
502
|
+
features: [
|
|
503
|
+
{
|
|
504
|
+
description: "List Definitions discovered by each active package.",
|
|
505
|
+
name: "definitions",
|
|
506
|
+
run: (args, context) => runDefinitions(args, context, plugins, operations),
|
|
507
|
+
usage: definitionsUsage
|
|
508
|
+
},
|
|
509
|
+
{
|
|
510
|
+
description: "List generated Provider Output files with secrets redacted.",
|
|
511
|
+
name: "output",
|
|
512
|
+
run: (args, context) => runProviderOutput(args, context, plugins),
|
|
513
|
+
usage: providerOutputUsage
|
|
514
|
+
},
|
|
515
|
+
{
|
|
516
|
+
description: "List the host resources that Definitions map to and where their ids come from.",
|
|
517
|
+
name: "resources",
|
|
518
|
+
run: (args, context) => runResources(args, context, plugins),
|
|
519
|
+
usage: resourcesUsage
|
|
520
|
+
},
|
|
521
|
+
{
|
|
522
|
+
description: "List the server routes that plugins add to the build, with method, path, and owner.",
|
|
523
|
+
name: "routes",
|
|
524
|
+
run: (args, context) => runRoutes(args, context, handlers),
|
|
525
|
+
usage: routesUsage
|
|
526
|
+
}
|
|
527
|
+
],
|
|
528
|
+
name: "inspect"
|
|
96
529
|
};
|
|
97
530
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
531
|
+
//#endregion
|
|
532
|
+
//#region ../internal/dist/contributions.js
|
|
533
|
+
function isThenable(value) {
|
|
534
|
+
return typeof value.then === "function";
|
|
535
|
+
}
|
|
536
|
+
async function flattenPlugins(value, plugins, seen) {
|
|
537
|
+
if (Array.isArray(value)) {
|
|
538
|
+
for (const item of value) await flattenPlugins(item, plugins, seen);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (!isRecord(value) || seen.has(value)) return;
|
|
542
|
+
seen.add(value);
|
|
543
|
+
if (isThenable(value)) {
|
|
544
|
+
await flattenPlugins(await value, plugins, seen);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
plugins.push(value);
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
|
|
551
|
+
* list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
|
|
552
|
+
* filter this list, because `vitehub()` nests its plugins in an array.
|
|
553
|
+
*/
|
|
554
|
+
async function flattenPluginOptions(plugins) {
|
|
555
|
+
const flattened = [];
|
|
556
|
+
await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
|
|
557
|
+
return flattened;
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region src/operations.ts
|
|
561
|
+
/** Reads every contributed operation of the resolved plugins. A module that fails to load is reported on stderr. */
|
|
562
|
+
async function loadCliOperations(plugins, stderr) {
|
|
563
|
+
const sources = [];
|
|
564
|
+
for (const contribution of await collectOperationContributions(await flattenPluginOptions(plugins))) try {
|
|
565
|
+
const exported = contribution.load ? await contribution.load() : Reflect.get(Object(await import(
|
|
566
|
+
/* @vite-ignore */
|
|
567
|
+
contribution.module
|
|
568
|
+
)), contribution.export);
|
|
569
|
+
sources.push({
|
|
570
|
+
operations: operationsOf(exported),
|
|
571
|
+
plugin: contribution.plugin
|
|
572
|
+
});
|
|
573
|
+
} catch (error) {
|
|
574
|
+
stderr.write(`Could not load the operations of ${contribution.plugin} from ${contribution.module}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
575
|
+
}
|
|
576
|
+
return createOperationRegistry(sources).list();
|
|
577
|
+
}
|
|
578
|
+
function kebab(key) {
|
|
579
|
+
return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
580
|
+
}
|
|
581
|
+
function camel(flag) {
|
|
582
|
+
return flag.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
|
|
583
|
+
}
|
|
584
|
+
function isObject(value) {
|
|
585
|
+
return value !== null && Object(value) === value && !Array.isArray(value);
|
|
586
|
+
}
|
|
587
|
+
const scalarTypes = /* @__PURE__ */ new Set([
|
|
588
|
+
"boolean",
|
|
589
|
+
"integer",
|
|
590
|
+
"number",
|
|
591
|
+
"string"
|
|
592
|
+
]);
|
|
593
|
+
/** Reads the type of a JSON Schema node. Objects, unknown values, and lists of objects are JSON. */
|
|
594
|
+
function readType(schema) {
|
|
595
|
+
if (!isObject(schema)) return {
|
|
596
|
+
alternatives: [],
|
|
597
|
+
nullable: false,
|
|
598
|
+
type: "json"
|
|
599
|
+
};
|
|
600
|
+
const options = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : void 0;
|
|
601
|
+
if (options) {
|
|
602
|
+
const parts = options.map(readType);
|
|
603
|
+
const nulls = options.filter((option) => isObject(option) && option.type === "null").length;
|
|
604
|
+
const present = parts.filter((_part, index) => !(isObject(options[index]) && options[index].type === "null"));
|
|
605
|
+
const nullable = nulls > 0 || parts.some((part) => part.nullable);
|
|
606
|
+
if (present.length === 1) return {
|
|
607
|
+
...present[0],
|
|
608
|
+
nullable
|
|
609
|
+
};
|
|
610
|
+
const scalars = present.map((part) => part.type);
|
|
611
|
+
if (scalars.every((type) => type !== "json" && type !== "list")) return {
|
|
612
|
+
alternatives: scalars.includes("string") ? ["string"] : scalars,
|
|
613
|
+
nullable,
|
|
614
|
+
type: scalars.includes("string") ? "string" : scalars[0]
|
|
615
|
+
};
|
|
616
|
+
return {
|
|
617
|
+
alternatives: [],
|
|
618
|
+
nullable,
|
|
619
|
+
type: "json"
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
const declared = schema.type;
|
|
623
|
+
if (Array.isArray(declared)) {
|
|
624
|
+
const kinds = declared.filter((kind) => kind !== "null");
|
|
625
|
+
const nullable = declared.includes("null");
|
|
626
|
+
return kinds.length === 1 ? {
|
|
627
|
+
...readType({
|
|
628
|
+
...schema,
|
|
629
|
+
type: kinds[0]
|
|
630
|
+
}),
|
|
631
|
+
nullable
|
|
632
|
+
} : {
|
|
633
|
+
alternatives: [],
|
|
634
|
+
nullable,
|
|
635
|
+
type: "json"
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
if (typeof declared === "string" && scalarTypes.has(declared)) return {
|
|
639
|
+
alternatives: [],
|
|
640
|
+
nullable: false,
|
|
641
|
+
type: declared
|
|
642
|
+
};
|
|
643
|
+
if (declared === "array") {
|
|
644
|
+
const items = readType(schema.items);
|
|
645
|
+
return items.type === "json" || items.type === "list" ? {
|
|
646
|
+
alternatives: [],
|
|
647
|
+
nullable: false,
|
|
648
|
+
type: "json"
|
|
649
|
+
} : {
|
|
650
|
+
alternatives: [],
|
|
651
|
+
item: items.type,
|
|
652
|
+
nullable: false,
|
|
653
|
+
type: "list"
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === "string")) return {
|
|
657
|
+
alternatives: [],
|
|
658
|
+
nullable: false,
|
|
659
|
+
type: "string"
|
|
660
|
+
};
|
|
661
|
+
if (typeof schema.const === "string") return {
|
|
662
|
+
alternatives: [],
|
|
663
|
+
nullable: false,
|
|
664
|
+
type: "string"
|
|
665
|
+
};
|
|
101
666
|
return {
|
|
102
|
-
|
|
103
|
-
|
|
667
|
+
alternatives: [],
|
|
668
|
+
nullable: false,
|
|
669
|
+
type: "json"
|
|
104
670
|
};
|
|
105
671
|
}
|
|
106
|
-
function
|
|
107
|
-
const
|
|
108
|
-
|
|
672
|
+
function flagsOf(operation) {
|
|
673
|
+
const schema = operationInputJsonSchema(operation);
|
|
674
|
+
const properties = isObject(schema.properties) ? Object.entries(schema.properties) : [];
|
|
675
|
+
const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
|
|
676
|
+
return properties.map(([key, property]) => {
|
|
677
|
+
const description = isObject(property) ? property.description : void 0;
|
|
678
|
+
return {
|
|
679
|
+
...readType(property),
|
|
680
|
+
key,
|
|
681
|
+
required: required.includes(key),
|
|
682
|
+
...typeof description === "string" ? { description } : {}
|
|
683
|
+
};
|
|
684
|
+
});
|
|
109
685
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
686
|
+
function usageOf(operation, flags) {
|
|
687
|
+
const { command, namespace } = operationCliPath(operation);
|
|
688
|
+
const positional = operation.cli?.positional ?? [];
|
|
689
|
+
const names = positional.map((key) => {
|
|
690
|
+
return flags.find((entry) => entry.key === key)?.required === false ? `[${kebab(key)}]` : `<${kebab(key)}>`;
|
|
691
|
+
});
|
|
692
|
+
const options = flags.filter((flag) => !positional.includes(flag.key)).map((flag) => {
|
|
693
|
+
const name = `--${kebab(flag.key)}${flag.type === "boolean" ? "" : " <value>"}`;
|
|
694
|
+
return flag.required ? name : `[${name}]`;
|
|
695
|
+
});
|
|
696
|
+
return [
|
|
697
|
+
"vitehub",
|
|
698
|
+
namespace,
|
|
699
|
+
command,
|
|
700
|
+
...names,
|
|
701
|
+
...options,
|
|
702
|
+
"[--input <json|@file>]",
|
|
703
|
+
"[--json]",
|
|
704
|
+
...operation.kind === "destructive" ? ["[--yes]"] : [],
|
|
705
|
+
"[--url <origin>]"
|
|
706
|
+
].join(" ");
|
|
707
|
+
}
|
|
708
|
+
function describeFlag(flag) {
|
|
709
|
+
return `${flag.type === "json" ? "JSON" : flag.type === "list" ? "list (repeat the flag or separate with commas)" : flag.type}${flag.nullable ? " or null" : ""}${flag.required ? ", required" : ""}`;
|
|
710
|
+
}
|
|
711
|
+
function helpOf(operation, flags) {
|
|
712
|
+
const positional = operation.cli?.positional ?? [];
|
|
713
|
+
const lines = [
|
|
714
|
+
`Usage: ${usageOf(operation, flags)}`,
|
|
715
|
+
"",
|
|
716
|
+
operation.description,
|
|
717
|
+
""
|
|
718
|
+
];
|
|
719
|
+
const described = flags.map((flag) => ` ${positional.includes(flag.key) ? `<${kebab(flag.key)}>` : `--${kebab(flag.key)}`} ${describeFlag(flag)}${flag.description ? `. ${flag.description}` : ""}`);
|
|
720
|
+
if (described.length) lines.push("Input:", ...described, "");
|
|
721
|
+
lines.push("Options:", " --input <json|@file> Pass the whole input as JSON or from a file. Flags override it.", " --json Print JSON.", ...operation.kind === "destructive" ? [" --yes Run without asking. This operation changes or removes data."] : [], " --url <origin> The app URL, such as https://app.example.com. Without it the command calls the running dev server.", " --timeout <ms> Wait this long for the answer. Default 30000.", " -h, --help Show this help.", "");
|
|
722
|
+
return lines.join("\n");
|
|
723
|
+
}
|
|
724
|
+
function usageError(message) {
|
|
725
|
+
return cliErrorDiagnostics.CLI_R0003({ message });
|
|
726
|
+
}
|
|
727
|
+
function parseJson(raw, name) {
|
|
728
|
+
try {
|
|
729
|
+
return JSON.parse(raw);
|
|
730
|
+
} catch (error) {
|
|
731
|
+
throw usageError(`--${name} must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
function convertScalar(type, name, raw) {
|
|
735
|
+
switch (type) {
|
|
736
|
+
case "integer":
|
|
737
|
+
case "number": {
|
|
738
|
+
const value = Number(raw);
|
|
739
|
+
if (raw.trim() === "" || !Number.isFinite(value) || type === "integer" && !Number.isInteger(value)) throw usageError(`--${name} must be ${type === "integer" ? "a whole number" : "a number"}.`);
|
|
740
|
+
return value;
|
|
741
|
+
}
|
|
742
|
+
case "boolean":
|
|
743
|
+
if (raw !== "true" && raw !== "false") throw usageError(`--${name} must be true or false.`);
|
|
744
|
+
return raw === "true";
|
|
745
|
+
case "json": return parseJson(raw, name);
|
|
746
|
+
default: return raw;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
function convert(flag, name, raw) {
|
|
750
|
+
if (!flag) return raw;
|
|
751
|
+
if (flag.nullable && raw === "null") return null;
|
|
752
|
+
if (flag.alternatives.length > 1) {
|
|
753
|
+
for (const type of flag.alternatives) try {
|
|
754
|
+
return convertScalar(type, name, raw);
|
|
755
|
+
} catch {
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
throw usageError(`--${name} must be one of: ${flag.alternatives.join(", ")}.`);
|
|
759
|
+
}
|
|
760
|
+
return convertScalar(flag.type, name, raw);
|
|
761
|
+
}
|
|
762
|
+
function assign(input, flag, key, name, raw) {
|
|
763
|
+
if (flag?.type === "list") {
|
|
764
|
+
if (flag.nullable && raw === "null") {
|
|
765
|
+
input[key] = null;
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
const items = raw.trim().startsWith("[") ? parseJson(raw, name) : raw.split(",").map((item) => item.trim()).filter(Boolean).map((item) => convertScalar(flag.item ?? "string", name, item));
|
|
769
|
+
if (!Array.isArray(items)) throw usageError(`--${name} must be a list.`);
|
|
770
|
+
input[key] = [...Array.isArray(input[key]) ? input[key] : [], ...items];
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
input[key] = convert(flag, name, raw);
|
|
774
|
+
}
|
|
775
|
+
/** `--input '{"a":1}'` or `--input @file.json`. */
|
|
776
|
+
function readWholeInput(raw, cwd) {
|
|
777
|
+
let text = raw;
|
|
778
|
+
if (raw.startsWith("@")) try {
|
|
779
|
+
text = readFileSync(resolve(cwd, raw.slice(1)), "utf8");
|
|
780
|
+
} catch (error) {
|
|
781
|
+
throw usageError(`--input could not read ${raw.slice(1)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
782
|
+
}
|
|
783
|
+
const value = parseJson(text, "input");
|
|
784
|
+
if (!isObject(value)) throw usageError("--input must be a JSON object.");
|
|
785
|
+
return value;
|
|
786
|
+
}
|
|
787
|
+
function parseCall(operation, flags, args, cwd) {
|
|
113
788
|
const parsed = {
|
|
114
|
-
|
|
115
|
-
|
|
789
|
+
help: false,
|
|
790
|
+
input: {},
|
|
791
|
+
json: false,
|
|
792
|
+
yes: false
|
|
116
793
|
};
|
|
794
|
+
const positional = [...operation.cli?.positional ?? []];
|
|
795
|
+
const { command, namespace } = operationCliPath(operation);
|
|
796
|
+
let whole = {};
|
|
117
797
|
for (let index = 0; index < args.length; index++) {
|
|
118
798
|
const arg = args[index];
|
|
799
|
+
if (arg === "--") {
|
|
800
|
+
for (const rest of args.slice(index + 1)) {
|
|
801
|
+
const key = positional.shift();
|
|
802
|
+
if (!key) throw usageError(`Unexpected argument ${JSON.stringify(rest)}.`);
|
|
803
|
+
assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), rest);
|
|
804
|
+
}
|
|
805
|
+
break;
|
|
806
|
+
}
|
|
119
807
|
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
120
|
-
else if (arg === "--
|
|
121
|
-
else if (arg === "--
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
808
|
+
else if (arg === "--json") parsed.json = true;
|
|
809
|
+
else if (arg === "--yes" || arg === "-y") parsed.yes = true;
|
|
810
|
+
else if (arg.startsWith("--")) {
|
|
811
|
+
const equals = arg.indexOf("=");
|
|
812
|
+
const name = arg.slice(2, equals === -1 ? void 0 : equals);
|
|
813
|
+
const inline = equals === -1 ? void 0 : arg.slice(equals + 1);
|
|
814
|
+
const take = () => {
|
|
815
|
+
if (inline !== void 0) return inline;
|
|
816
|
+
const next = args[index + 1];
|
|
817
|
+
if (next === void 0 || next.startsWith("--") && next !== "--") throw usageError(`Option --${name} needs a value.`);
|
|
126
818
|
index++;
|
|
819
|
+
return next;
|
|
820
|
+
};
|
|
821
|
+
if (name === "url") parsed.url = take();
|
|
822
|
+
else if (name === "input") whole = readWholeInput(take(), cwd);
|
|
823
|
+
else if (name === "timeout") {
|
|
824
|
+
const timeout = Number(take());
|
|
825
|
+
if (!Number.isInteger(timeout) || timeout < 1) throw usageError("--timeout must be a whole number of milliseconds.");
|
|
826
|
+
parsed.timeout = timeout;
|
|
827
|
+
} else {
|
|
828
|
+
const negated = name.startsWith("no-") && flags.some((flag) => flag.key === camel(name.slice(3)) && flag.type === "boolean");
|
|
829
|
+
const key = camel(negated ? name.slice(3) : name);
|
|
830
|
+
const flag = flags.find((entry) => entry.key === key);
|
|
831
|
+
if (!flag) throw usageError(`Unknown option --${name}. Run \`vitehub ${namespace} ${command} --help\` for the input.`);
|
|
832
|
+
if (flag.type === "boolean") {
|
|
833
|
+
const next = args[index + 1];
|
|
834
|
+
const value = inline !== void 0 ? convertScalar("boolean", name, inline) : !negated && (next === "true" || next === "false") ? (index++, next === "true") : true;
|
|
835
|
+
parsed.input[key] = negated ? false : value;
|
|
836
|
+
} else assign(parsed.input, flag, key, name, take());
|
|
127
837
|
}
|
|
128
|
-
} else
|
|
129
|
-
const
|
|
130
|
-
if (!
|
|
131
|
-
|
|
132
|
-
}
|
|
838
|
+
} else {
|
|
839
|
+
const key = positional.shift();
|
|
840
|
+
if (!key) throw usageError(`Unexpected argument ${JSON.stringify(arg)}.`);
|
|
841
|
+
assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), arg);
|
|
842
|
+
}
|
|
133
843
|
}
|
|
844
|
+
parsed.input = {
|
|
845
|
+
...whole,
|
|
846
|
+
...parsed.input
|
|
847
|
+
};
|
|
134
848
|
return parsed;
|
|
135
849
|
}
|
|
136
|
-
function
|
|
850
|
+
function writeFailure(failure, parsed, context) {
|
|
851
|
+
if (parsed.json) {
|
|
852
|
+
context.stdout.write(`${JSON.stringify({ error: {
|
|
853
|
+
code: failure.code,
|
|
854
|
+
...failure.details ? { details: failure.details } : {},
|
|
855
|
+
...failure.docs ? { docs: failure.docs } : {},
|
|
856
|
+
...failure.fix ? { fix: failure.fix } : {},
|
|
857
|
+
message: failure.message
|
|
858
|
+
} }, null, 2)}\n`);
|
|
859
|
+
return 1;
|
|
860
|
+
}
|
|
861
|
+
context.stderr.write([
|
|
862
|
+
`${failure.code}: ${failure.message}`,
|
|
863
|
+
...failure.fix ? [`Fix: ${failure.fix}`] : [],
|
|
864
|
+
...failure.docs ? [`Docs: ${failure.docs}`] : [],
|
|
865
|
+
""
|
|
866
|
+
].join("\n"));
|
|
867
|
+
return 1;
|
|
868
|
+
}
|
|
869
|
+
/** A coded failure for a thrown diagnostic. */
|
|
870
|
+
function failureOf(error, status = 400) {
|
|
871
|
+
const code = Reflect.get(Object(error), "code");
|
|
872
|
+
const fix = Reflect.get(Object(error), "fix");
|
|
873
|
+
return {
|
|
874
|
+
code: typeof code === "string" && code ? code : "CLI_R0003",
|
|
875
|
+
...typeof fix === "string" && fix ? { fix } : {},
|
|
876
|
+
message: error instanceof Error ? error.message : String(error),
|
|
877
|
+
status
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
async function confirm(operation, target) {
|
|
881
|
+
const terminal = createInterface({
|
|
882
|
+
input: process.stdin,
|
|
883
|
+
output: process.stderr
|
|
884
|
+
});
|
|
885
|
+
try {
|
|
886
|
+
const answer = await terminal.question(`${operation.description} This changes data at ${target}. Continue? [y/N] `);
|
|
887
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
888
|
+
} finally {
|
|
889
|
+
terminal.close();
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
/** The roots that the CLI accepts a dev server for: the Vite root and the ViteHub project root. */
|
|
893
|
+
function acceptedRoots(rootDir) {
|
|
894
|
+
const roots = /* @__PURE__ */ new Set([rootDir]);
|
|
895
|
+
try {
|
|
896
|
+
roots.add(resolveViteHubProjectRoot(rootDir));
|
|
897
|
+
} catch {}
|
|
898
|
+
return [...roots];
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Where a command sends its call: `--url`, else the dev server that wrote `.vitehub/dev-server.json` in this project,
|
|
902
|
+
* else `VITEHUB_DEV_SERVER_URL`. There is no guess: another project may use port 5173.
|
|
903
|
+
*/
|
|
904
|
+
function resolveTarget(parsed, context) {
|
|
905
|
+
if (parsed.url) {
|
|
906
|
+
let base;
|
|
907
|
+
try {
|
|
908
|
+
base = new URL(parsed.url);
|
|
909
|
+
} catch {
|
|
910
|
+
return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must be a URL." })) };
|
|
911
|
+
}
|
|
912
|
+
const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
|
|
913
|
+
if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must use HTTPS, except for localhost." })) };
|
|
914
|
+
if (base.username || base.password || base.search || base.hash) return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must not contain credentials, a query, or a fragment." })) };
|
|
915
|
+
const consolePath = /(?:^|\/)_vitehub(?:\/|$)/.exec(base.pathname);
|
|
916
|
+
if (consolePath) {
|
|
917
|
+
const app = `${base.origin}${base.pathname.slice(0, consolePath.index).replace(/\/$/, "")}`;
|
|
918
|
+
return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: `--url is the app URL, not the Console URL. Pass --url ${app}.` })) };
|
|
919
|
+
}
|
|
920
|
+
return { target: parsed.url };
|
|
921
|
+
}
|
|
922
|
+
const roots = acceptedRoots(context.rootDir);
|
|
923
|
+
const found = findViteHubDevServerUrl(roots, context.env);
|
|
924
|
+
if (found) return { target: found };
|
|
925
|
+
return { failure: failureOf(cliErrorDiagnostics.CLI_R0005({ message: `No dev server is running for ${roots.at(-1)}.` }), 503) };
|
|
926
|
+
}
|
|
927
|
+
function featureOf(operation) {
|
|
928
|
+
const flags = flagsOf(operation);
|
|
929
|
+
const { command } = operationCliPath(operation);
|
|
930
|
+
return {
|
|
931
|
+
description: operation.description,
|
|
932
|
+
name: command,
|
|
933
|
+
async run(args, context) {
|
|
934
|
+
let parsed;
|
|
935
|
+
try {
|
|
936
|
+
parsed = parseCall(operation, flags, args, context.cwd);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
const failure = failureOf(error);
|
|
939
|
+
if (args.includes("--json")) return writeFailure(failure, { json: true }, context);
|
|
940
|
+
context.stderr.write(`${failure.message}\nUsage: ${usageOf(operation, flags)}\n`);
|
|
941
|
+
return 1;
|
|
942
|
+
}
|
|
943
|
+
if (parsed.help) {
|
|
944
|
+
context.stdout.write(helpOf(operation, flags));
|
|
945
|
+
return 0;
|
|
946
|
+
}
|
|
947
|
+
let reads;
|
|
948
|
+
try {
|
|
949
|
+
reads = operationCall(operation, await parseOperationInput(operation, parsed.input)).readOnly === true;
|
|
950
|
+
} catch (error) {
|
|
951
|
+
return writeFailure(failureOf(error), parsed, context);
|
|
952
|
+
}
|
|
953
|
+
const resolved = resolveTarget(parsed, context);
|
|
954
|
+
if ("failure" in resolved) return writeFailure(resolved.failure, parsed, context);
|
|
955
|
+
const target = resolved.target;
|
|
956
|
+
let confirmed = parsed.yes;
|
|
957
|
+
if (operation.kind === "destructive" && !parsed.yes && !reads) {
|
|
958
|
+
if (!(process.stdin.isTTY && process.stderr.isTTY) || !await confirm(operation, target)) return writeFailure(failureOf(cliErrorDiagnostics.CLI_R0004({ message: `${operation.name} changes or removes data and was not confirmed.` })), parsed, context);
|
|
959
|
+
confirmed = true;
|
|
960
|
+
}
|
|
961
|
+
const result = await callOperation({
|
|
962
|
+
confirmed,
|
|
963
|
+
env: context.env,
|
|
964
|
+
...context.fetch ? { fetch: context.fetch } : {},
|
|
965
|
+
...parsed.url ? {} : { roots: acceptedRoots(context.rootDir) },
|
|
966
|
+
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
967
|
+
url: target
|
|
968
|
+
}, operation.name, parsed.input);
|
|
969
|
+
if (!result.ok) return writeFailure(result, parsed, context);
|
|
970
|
+
const format = operation.cli?.format;
|
|
971
|
+
const output = !parsed.json && format ? format(result.value) : `${JSON.stringify(result.value ?? null, null, 2)}\n`;
|
|
972
|
+
context.stdout.write(output);
|
|
973
|
+
return 0;
|
|
974
|
+
},
|
|
975
|
+
usage: usageOf(operation, flags)
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
/** `vitehub <namespace> <group> <command>`: one feature that runs the commands whose name starts with `<group> `. */
|
|
979
|
+
function groupOf(namespace, name, commands) {
|
|
980
|
+
const usage = `vitehub ${namespace} ${name} <${commands.map((command) => command.name).join("|")}> [args...]`;
|
|
981
|
+
const help = () => {
|
|
982
|
+
const width = Math.max(...commands.map((command) => command.name.length));
|
|
983
|
+
return [
|
|
984
|
+
`Usage: ${usage}`,
|
|
985
|
+
"",
|
|
986
|
+
"Commands:",
|
|
987
|
+
...commands.map((command) => ` ${command.name.padEnd(width)} ${command.description ?? ""}`.trimEnd()),
|
|
988
|
+
"",
|
|
989
|
+
`Run \`vitehub ${namespace} ${name} <command> --help\` for the options of one command.`,
|
|
990
|
+
""
|
|
991
|
+
].join("\n");
|
|
992
|
+
};
|
|
993
|
+
return {
|
|
994
|
+
description: `${commands.map((command) => command.name).join(", ")}.`,
|
|
995
|
+
name,
|
|
996
|
+
async run(args, context) {
|
|
997
|
+
const [commandName, ...rest] = args;
|
|
998
|
+
if (commandName === "-h" || commandName === "--help") {
|
|
999
|
+
context.stdout.write(help());
|
|
1000
|
+
return 0;
|
|
1001
|
+
}
|
|
1002
|
+
const command = commands.find((candidate) => candidate.name === commandName);
|
|
1003
|
+
if (!command) {
|
|
1004
|
+
context.stderr.write(`${commandName ? `Unknown ViteHub CLI command: ${namespace} ${name} ${commandName}\n` : ""}${help()}`);
|
|
1005
|
+
return 1;
|
|
1006
|
+
}
|
|
1007
|
+
return await command.run(rest, context) ?? 0;
|
|
1008
|
+
},
|
|
1009
|
+
usage
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* One namespace per operation namespace, with a command for each operation. A command name with a space, such as
|
|
1014
|
+
* `jobs list`, becomes `list` in the `jobs` group: `vitehub queue jobs list`.
|
|
1015
|
+
*/
|
|
1016
|
+
function createOperationNamespaces(operations) {
|
|
1017
|
+
const namespaces = /* @__PURE__ */ new Map();
|
|
1018
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1019
|
+
for (const operation of operations) {
|
|
1020
|
+
const { command, namespace: name } = operationCliPath(operation);
|
|
1021
|
+
const namespace = namespaces.get(name) ?? {
|
|
1022
|
+
description: `Run the ${name} operations of the app.`,
|
|
1023
|
+
features: [],
|
|
1024
|
+
name
|
|
1025
|
+
};
|
|
1026
|
+
const space = command.indexOf(" ");
|
|
1027
|
+
if (space < 0) namespace.features.push(featureOf(operation));
|
|
1028
|
+
else {
|
|
1029
|
+
const groupName = command.slice(0, space);
|
|
1030
|
+
const key = `${name} ${groupName}`;
|
|
1031
|
+
const group = groups.get(key) ?? {
|
|
1032
|
+
commands: [],
|
|
1033
|
+
name: groupName,
|
|
1034
|
+
namespace: name
|
|
1035
|
+
};
|
|
1036
|
+
group.commands.push({
|
|
1037
|
+
...featureOf(operation),
|
|
1038
|
+
name: command.slice(space + 1)
|
|
1039
|
+
});
|
|
1040
|
+
groups.set(key, group);
|
|
1041
|
+
}
|
|
1042
|
+
if (operation.cli?.default) namespace.defaultFeature = command;
|
|
1043
|
+
namespaces.set(name, namespace);
|
|
1044
|
+
}
|
|
1045
|
+
for (const group of groups.values()) {
|
|
1046
|
+
const namespace = namespaces.get(group.namespace);
|
|
1047
|
+
if (!namespace.features.some((feature) => feature.name === group.name)) namespace.features.push(groupOf(group.namespace, group.name, group.commands));
|
|
1048
|
+
}
|
|
1049
|
+
return [...namespaces.values()];
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Adds the generated namespaces to the ones that packages wrote by hand. A hand-written command with the same name wins,
|
|
1053
|
+
* since it can offer more than the generated one, such as an editor.
|
|
1054
|
+
*/
|
|
1055
|
+
function mergeOperationNamespaces(written, generated) {
|
|
1056
|
+
const merged = written.map((namespace) => ({
|
|
1057
|
+
...namespace,
|
|
1058
|
+
features: [...namespace.features]
|
|
1059
|
+
}));
|
|
1060
|
+
for (const namespace of generated) {
|
|
1061
|
+
const existing = merged.find((candidate) => candidate.name === namespace.name);
|
|
1062
|
+
if (!existing) {
|
|
1063
|
+
merged.push(namespace);
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
for (const feature of namespace.features) if (!existing.features.some((candidate) => candidate.name === feature.name)) existing.features.push(feature);
|
|
1067
|
+
if (namespace.defaultFeature && !existing.defaultFeature) existing.defaultFeature = namespace.defaultFeature;
|
|
1068
|
+
}
|
|
1069
|
+
return merged;
|
|
1070
|
+
}
|
|
1071
|
+
//#endregion
|
|
1072
|
+
//#region src/seed.ts
|
|
1073
|
+
const usage = "vitehub seed [<primitive>...] [--remote [--url <url>]] [--stage <name>] [--database <name>] [--timeout <ms>]";
|
|
1074
|
+
function writeUsage(seeds, stream) {
|
|
137
1075
|
stream.write([
|
|
138
|
-
|
|
1076
|
+
`Usage: ${usage}`,
|
|
1077
|
+
"",
|
|
1078
|
+
"Writes the seed files of the app: the Database seed files, and the files in server/seed/kv/ and server/seed/blob/.",
|
|
1079
|
+
"Without --remote, it writes only local data: the local database, and the KV and Blob stores of the dev server.",
|
|
1080
|
+
"Name primitives to seed only them, such as `vitehub seed kv blob`.",
|
|
139
1081
|
"",
|
|
140
|
-
"
|
|
141
|
-
"
|
|
1082
|
+
"Seed files:",
|
|
1083
|
+
...seeds.length ? seeds.map((seed) => ` ${seed.name.padEnd(9)} ${seed.files}`) : [" None. Turn on Database, KV, or Blob in the ViteHub config."],
|
|
142
1084
|
"",
|
|
143
1085
|
"Options:",
|
|
144
|
-
" --
|
|
145
|
-
"
|
|
1086
|
+
" --remote Write the deployed data. KV and Blob seeds call the deployed app, with",
|
|
1087
|
+
" VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to sign the calls.",
|
|
1088
|
+
" --url <url> Deployed app URL for --remote. Defaults to `vitehub({ publicUrl })`.",
|
|
1089
|
+
" --stage <name> Load Vite env files for this mode. Variables from the current process take precedence.",
|
|
1090
|
+
" --database <name> Seed only this database.",
|
|
1091
|
+
" --timeout <ms> Request timeout of each call to the app.",
|
|
146
1092
|
" -h, --help Show this help.",
|
|
147
1093
|
""
|
|
148
1094
|
].join("\n"));
|
|
149
1095
|
}
|
|
150
|
-
|
|
151
|
-
const parsed =
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
1096
|
+
function parseArgs(args, seeds) {
|
|
1097
|
+
const parsed = {
|
|
1098
|
+
help: false,
|
|
1099
|
+
names: [],
|
|
1100
|
+
remote: false
|
|
1101
|
+
};
|
|
1102
|
+
for (let index = 0; index < args.length; index++) {
|
|
1103
|
+
const arg = args[index];
|
|
1104
|
+
if (arg === "-h" || arg === "--help") {
|
|
1105
|
+
parsed.help = true;
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
if (arg === "--remote") {
|
|
1109
|
+
parsed.remote = true;
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
const option = [
|
|
1113
|
+
"--database",
|
|
1114
|
+
"--stage",
|
|
1115
|
+
"--timeout",
|
|
1116
|
+
"--url"
|
|
1117
|
+
].find((name) => arg === name || arg.startsWith(`${name}=`));
|
|
1118
|
+
if (option) {
|
|
1119
|
+
const value = arg === option ? args[++index] : arg.slice(option.length + 1);
|
|
1120
|
+
if (!value || value.startsWith("-")) return `${option} requires a value.`;
|
|
1121
|
+
if (option === "--timeout") {
|
|
1122
|
+
const timeout = Number(value);
|
|
1123
|
+
if (!Number.isSafeInteger(timeout) || timeout <= 0) return "--timeout must be a positive integer of milliseconds.";
|
|
1124
|
+
parsed.timeout = timeout;
|
|
1125
|
+
} else parsed[option.slice(2)] = value;
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
if (arg.startsWith("-")) return `Unknown option: ${arg}`;
|
|
1129
|
+
if (!seeds.some((seed) => seed.name === arg)) return `Unknown seed: ${arg}. Seeds of this app: ${seeds.map((seed) => seed.name).join(", ") || "none"}.`;
|
|
1130
|
+
if (!parsed.names.includes(arg)) parsed.names.push(arg);
|
|
160
1131
|
}
|
|
161
|
-
if (parsed.
|
|
162
|
-
|
|
163
|
-
|
|
1132
|
+
if (parsed.url && !parsed.remote) return "--url names a deployed app. Add --remote to write its data.";
|
|
1133
|
+
if (parsed.database && parsed.names.some((name) => name !== "database")) return "--database seeds only the Database. Remove the other primitive names.";
|
|
1134
|
+
return parsed;
|
|
1135
|
+
}
|
|
1136
|
+
/** Runs the selected seeds in order and stops at the first failure. */
|
|
1137
|
+
async function runSeeds(seeds, parsed, context) {
|
|
1138
|
+
const selected = parsed.names.length || parsed.database ? seeds.filter((seed) => parsed.names.includes(seed.name) || parsed.database && seed.name === "database") : seeds;
|
|
1139
|
+
if (parsed.database && !selected.length) {
|
|
1140
|
+
context.stderr.write("[vitehub] --database needs the Database. Turn on Database in the ViteHub config.\n");
|
|
164
1141
|
return 1;
|
|
165
1142
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
1143
|
+
let env = { ...context.env };
|
|
1144
|
+
return await withViteStageEnvironment(env, async () => {
|
|
1145
|
+
if (parsed.stage) {
|
|
1146
|
+
const { loadEnv } = await import("vite");
|
|
1147
|
+
env = {
|
|
1148
|
+
...loadAllEnv(loadEnv, parsed.stage, context.rootDir),
|
|
1149
|
+
...env
|
|
1150
|
+
};
|
|
1151
|
+
Object.assign(process.env, env);
|
|
172
1152
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
1153
|
+
const options = {
|
|
1154
|
+
env,
|
|
1155
|
+
remote: parsed.remote,
|
|
1156
|
+
...parsed.database ? { database: parsed.database } : {},
|
|
1157
|
+
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
1158
|
+
...parsed.remote && (parsed.url ?? context.publicUrl) ? { url: parsed.url ?? context.publicUrl } : {}
|
|
1159
|
+
};
|
|
1160
|
+
const empty = [];
|
|
1161
|
+
for (const seed of selected) {
|
|
1162
|
+
const code = await seed.run(options, {
|
|
1163
|
+
...context,
|
|
1164
|
+
env
|
|
1165
|
+
});
|
|
1166
|
+
if (code === void 0) empty.push(seed);
|
|
1167
|
+
else if (code !== 0) return code;
|
|
181
1168
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
1169
|
+
const missing = parsed.names.length ? empty : empty.length === selected.length ? empty : [];
|
|
1170
|
+
if (!missing.length) return 0;
|
|
1171
|
+
context.stderr.write([
|
|
1172
|
+
"[vitehub] Nothing to seed. Add seed files:",
|
|
1173
|
+
...missing.map((seed) => ` ${seed.name.padEnd(9)} ${seed.files}`),
|
|
1174
|
+
""
|
|
1175
|
+
].join("\n"));
|
|
1176
|
+
return 1;
|
|
187
1177
|
});
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
1178
|
+
}
|
|
1179
|
+
/** The `vitehub seed` command, which runs the seeds that the ViteHub plugins contribute. */
|
|
1180
|
+
function createSeedNamespace(seeds) {
|
|
1181
|
+
return {
|
|
1182
|
+
defaultFeature: "seed",
|
|
1183
|
+
description: "Write the seed files of Database, KV, and Blob.",
|
|
1184
|
+
features: [{
|
|
1185
|
+
description: "Write the seed files of Database, KV, and Blob.",
|
|
1186
|
+
name: "seed",
|
|
1187
|
+
run: async (args, context) => {
|
|
1188
|
+
const parsed = parseArgs(args, seeds);
|
|
1189
|
+
if (typeof parsed === "string") {
|
|
1190
|
+
context.stderr.write(`[vitehub] ${parsed}\n`);
|
|
1191
|
+
writeUsage(seeds, context.stderr);
|
|
1192
|
+
return 1;
|
|
1193
|
+
}
|
|
1194
|
+
if (parsed.help) {
|
|
1195
|
+
writeUsage(seeds, context.stdout);
|
|
1196
|
+
return 0;
|
|
1197
|
+
}
|
|
1198
|
+
if (!seeds.length) {
|
|
1199
|
+
context.stderr.write("[vitehub] No ViteHub primitive of this app has seed files. Turn on Database, KV, or Blob in the ViteHub config.\n");
|
|
1200
|
+
return 1;
|
|
1201
|
+
}
|
|
1202
|
+
return await runSeeds(seeds, parsed, context);
|
|
1203
|
+
},
|
|
1204
|
+
usage
|
|
1205
|
+
}],
|
|
1206
|
+
name: "seed"
|
|
1207
|
+
};
|
|
204
1208
|
}
|
|
205
1209
|
//#endregion
|
|
206
1210
|
//#region src/index.ts
|
|
207
|
-
|
|
1211
|
+
const BUILTIN_NAMESPACE_NAMES = new Set(reservedOperationNamespaces);
|
|
1212
|
+
/**
|
|
1213
|
+
* `vitehub env diff` and `vitehub env push` read the names of the last build and the variables of the linked host, and
|
|
1214
|
+
* `vitehub env pull` reads a Console with the key of `vitehub login`, so they run before the project config loads. The
|
|
1215
|
+
* other `env` features come from `hubEnv()`.
|
|
1216
|
+
*/
|
|
1217
|
+
const hostEnvFeatures = {
|
|
1218
|
+
features: [
|
|
1219
|
+
{
|
|
1220
|
+
description: "Compare the env names of the last build with the names on the linked host. Exits with 1 when a required name is missing. Never reads values.",
|
|
1221
|
+
name: "diff",
|
|
1222
|
+
run: async (args, context) => await (await import("./env-DzoVtVJO.js").then((n) => n.n)).runEnvCommand({
|
|
1223
|
+
...hostEnvFeatures.features[0],
|
|
1224
|
+
name: "diff"
|
|
1225
|
+
}, args, context),
|
|
1226
|
+
usage: "vitehub env diff [--host <host>] [--to github [--repo <owner/name>] [--environment <name>]] [--stage <name>] [--json]"
|
|
1227
|
+
},
|
|
1228
|
+
{
|
|
1229
|
+
description: "Set the host variables of the build's env names from the shell and .env.<stage>, with the host CLI. Prints names, never values. Never deletes a host variable.",
|
|
1230
|
+
name: "push",
|
|
1231
|
+
run: async (args, context) => await (await import("./env-DzoVtVJO.js").then((n) => n.n)).runEnvCommand({
|
|
1232
|
+
...hostEnvFeatures.features[1],
|
|
1233
|
+
name: "push"
|
|
1234
|
+
}, args, context),
|
|
1235
|
+
usage: "vitehub env push [--host <host>] [--to github [--repo <owner/name>] [--environment <name>]] [--stage <name>] [--only <NAME>]... [--yes] [--json]"
|
|
1236
|
+
},
|
|
1237
|
+
{
|
|
1238
|
+
description: "Write the env values of a stage from a self-hosted Console to .env.<stage>. Needs `vitehub login` and the owner or admin role.",
|
|
1239
|
+
name: "pull",
|
|
1240
|
+
run: async (args, context) => await (await import("./console-env-C5YeAm2-.js")).envPullFeature.run(args, context),
|
|
1241
|
+
usage: "vitehub env pull --from console [--stage <name>] [--project <id>] [--console <url>] [--yes] [--json]"
|
|
1242
|
+
}
|
|
1243
|
+
],
|
|
1244
|
+
name: "env"
|
|
1245
|
+
};
|
|
1246
|
+
async function loadSetupCommands() {
|
|
1247
|
+
return (await import("./commands-DPg3kL8m.js").then((n) => n.t)).setupCommands;
|
|
1248
|
+
}
|
|
1249
|
+
async function loadNuxtViteConfig(rootDir, command, mode) {
|
|
208
1250
|
if (![
|
|
209
1251
|
"nuxt.config.ts",
|
|
210
1252
|
"nuxt.config.mts",
|
|
@@ -214,17 +1256,40 @@ async function loadNuxtViteConfig(rootDir) {
|
|
|
214
1256
|
"nuxt.config.cjs"
|
|
215
1257
|
].some((file) => existsSync(resolve(rootDir, file)))) return;
|
|
216
1258
|
let loadNuxt;
|
|
1259
|
+
let loadNuxtConfig;
|
|
217
1260
|
try {
|
|
218
|
-
({loadNuxt} = await import("nuxt/kit"));
|
|
1261
|
+
({loadNuxt, loadNuxtConfig} = await import("nuxt/kit"));
|
|
219
1262
|
} catch {
|
|
220
|
-
throw
|
|
1263
|
+
throw cliErrorDiagnostics.CLI_R0001({ message: "[vitehub] Nuxt config was found, but Nuxt could not be loaded for CLI discovery." });
|
|
221
1264
|
}
|
|
222
|
-
const
|
|
1265
|
+
const options = {
|
|
223
1266
|
cwd: rootDir,
|
|
224
|
-
dev:
|
|
225
|
-
|
|
1267
|
+
dev: command === "serve",
|
|
1268
|
+
envName: mode ?? (command === "build" ? "production" : "development"),
|
|
1269
|
+
overrides: {
|
|
1270
|
+
devtools: { enabled: false },
|
|
1271
|
+
...mode ? { vite: { mode } } : {},
|
|
1272
|
+
vitehubCliDiscovery: true
|
|
1273
|
+
},
|
|
226
1274
|
ready: true
|
|
227
|
-
}
|
|
1275
|
+
};
|
|
1276
|
+
if (mode) {
|
|
1277
|
+
const config = await loadNuxtConfig({
|
|
1278
|
+
...options,
|
|
1279
|
+
dotenv: false,
|
|
1280
|
+
overrides: {
|
|
1281
|
+
...options.overrides,
|
|
1282
|
+
dev: options.dev
|
|
1283
|
+
}
|
|
1284
|
+
});
|
|
1285
|
+
const nuxtRoot = config.rootDir || rootDir;
|
|
1286
|
+
const viteRoot = resolve(nuxtRoot, config.vite.root || nuxtRoot);
|
|
1287
|
+
const envDir = config.vite.envDir === false ? false : resolve(viteRoot, config.vite.envDir || ".");
|
|
1288
|
+
const { loadEnv } = await import("vite");
|
|
1289
|
+
Object.assign(process$1.env, loadAllEnv(loadEnv, mode, envDir));
|
|
1290
|
+
options.dotenv = false;
|
|
1291
|
+
}
|
|
1292
|
+
const nuxt = await loadNuxt(options);
|
|
228
1293
|
try {
|
|
229
1294
|
const { resolveConfig } = await import("vite");
|
|
230
1295
|
const viteRoot = nuxt.options.vite.root;
|
|
@@ -233,8 +1298,23 @@ async function loadNuxtViteConfig(rootDir) {
|
|
|
233
1298
|
configFile: false,
|
|
234
1299
|
root: viteRoot ? resolve(nuxt.options.rootDir || rootDir, viteRoot) : nuxt.options.rootDir || rootDir,
|
|
235
1300
|
vitehubCliDiscovery: true
|
|
236
|
-
}, "
|
|
1301
|
+
}, command, mode ?? (command === "build" ? "production" : "development"));
|
|
237
1302
|
return {
|
|
1303
|
+
nitro: { handlers: [...resolveRouteHandlers({
|
|
1304
|
+
...Object(Reflect.get(config, "nitro")),
|
|
1305
|
+
alias: {
|
|
1306
|
+
...nuxt.options.alias,
|
|
1307
|
+
...Reflect.get(nuxt.options.nitro, "alias"),
|
|
1308
|
+
...Reflect.get(Object(Reflect.get(config, "nitro")), "alias")
|
|
1309
|
+
}
|
|
1310
|
+
}, config.root), ...resolveRouteHandlers({
|
|
1311
|
+
...nuxt.options.nitro,
|
|
1312
|
+
alias: {
|
|
1313
|
+
...nuxt.options.alias,
|
|
1314
|
+
...Reflect.get(nuxt.options.nitro, "alias")
|
|
1315
|
+
},
|
|
1316
|
+
handlers: [...nitroHandlers(nuxt.options.nitro), ...nuxt.options.serverHandlers]
|
|
1317
|
+
}, nuxt.options.rootDir || rootDir)] },
|
|
238
1318
|
plugins: config.plugins,
|
|
239
1319
|
root: config.root
|
|
240
1320
|
};
|
|
@@ -242,111 +1322,277 @@ async function loadNuxtViteConfig(rootDir) {
|
|
|
242
1322
|
await nuxt.close();
|
|
243
1323
|
}
|
|
244
1324
|
}
|
|
1325
|
+
function nitroHandlers(nitro) {
|
|
1326
|
+
const handlers = Reflect.get(Object(nitro), "handlers");
|
|
1327
|
+
return Array.isArray(handlers) ? handlers : [];
|
|
1328
|
+
}
|
|
1329
|
+
function resolveRouteHandlers(nitro, projectRoot) {
|
|
1330
|
+
const options = Object(nitro);
|
|
1331
|
+
const rootDir = resolve(projectRoot, Reflect.get(options, "rootDir") || ".");
|
|
1332
|
+
const pathOptions = {
|
|
1333
|
+
...options,
|
|
1334
|
+
rootDir,
|
|
1335
|
+
buildDir: resolve(rootDir, Reflect.get(options, "buildDir") || ".")
|
|
1336
|
+
};
|
|
1337
|
+
const aliases = Object.entries(Reflect.get(options, "alias") || {}).filter((entry) => typeof entry[1] === "string").sort(([a], [b]) => b.length - a.length);
|
|
1338
|
+
return nitroHandlers(nitro).map((entry) => {
|
|
1339
|
+
const handler = Reflect.get(Object(entry), "handler");
|
|
1340
|
+
if (typeof handler !== "string") return entry;
|
|
1341
|
+
let file = handler.replace(/{{ ?([\w.]+) ?}}/g, (_, key) => {
|
|
1342
|
+
const value = key.split(".").reduce((object, part) => Reflect.get(Object(object), part), pathOptions);
|
|
1343
|
+
return value ? String(value) : key;
|
|
1344
|
+
});
|
|
1345
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1346
|
+
while (true) {
|
|
1347
|
+
const alias = aliases.find(([key]) => file === key || file.startsWith(`${key}/`));
|
|
1348
|
+
if (!alias || visited.has(alias[0])) break;
|
|
1349
|
+
visited.add(alias[0]);
|
|
1350
|
+
file = alias[1] + file.slice(alias[0].length);
|
|
1351
|
+
}
|
|
1352
|
+
return {
|
|
1353
|
+
...Object(entry),
|
|
1354
|
+
handler: /^[#\u0000]/.test(file) ? file : resolve(rootDir, file)
|
|
1355
|
+
};
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
245
1358
|
function defaultSpawn(command, args, options = {}) {
|
|
246
1359
|
return new Promise((resolveResult, reject) => {
|
|
247
1360
|
const child = spawn(command, args, {
|
|
248
1361
|
cwd: options.cwd,
|
|
249
1362
|
env: options.env,
|
|
250
|
-
shell: process.platform === "win32",
|
|
1363
|
+
shell: process$1.platform === "win32" && command !== process$1.execPath,
|
|
251
1364
|
stdio: [
|
|
252
|
-
"inherit",
|
|
253
|
-
options.stdout || "inherit",
|
|
1365
|
+
options.stdin || "inherit",
|
|
1366
|
+
options.stdout === "stderr" ? process$1.stderr : options.stdout || "inherit",
|
|
254
1367
|
options.stderr || "inherit"
|
|
255
1368
|
]
|
|
256
1369
|
});
|
|
1370
|
+
const stdout = [];
|
|
1371
|
+
child.stdout?.on("data", (chunk) => stdout.push(chunk));
|
|
1372
|
+
child.stderr?.resume();
|
|
257
1373
|
child.on("error", reject);
|
|
258
1374
|
child.on("close", (exitCode, signal) => resolveResult({
|
|
259
1375
|
exitCode,
|
|
260
|
-
signal
|
|
1376
|
+
signal,
|
|
1377
|
+
...child.stdout ? { stdout: Buffer.concat(stdout).toString("utf8") } : {}
|
|
261
1378
|
}));
|
|
262
1379
|
});
|
|
263
1380
|
}
|
|
264
|
-
async function loadViteConfig(rootDir) {
|
|
1381
|
+
async function loadViteConfig(rootDir, command, mode) {
|
|
265
1382
|
const { resolveConfig } = await import("vite");
|
|
266
|
-
|
|
1383
|
+
const inlineConfig = {
|
|
267
1384
|
root: rootDir,
|
|
1385
|
+
...mode ? { mode } : {},
|
|
268
1386
|
vitehubCliDiscovery: true
|
|
269
|
-
}, "serve", "development");
|
|
270
|
-
}
|
|
271
|
-
function createProvisionNamespace(plugins) {
|
|
272
|
-
const collectSteps = () => collectViteHubProvisionSteps(plugins);
|
|
273
|
-
const run = (args, context) => runProvision(args, context, { collectSteps });
|
|
274
|
-
return {
|
|
275
|
-
description: "Idempotently create missing provider resources.",
|
|
276
|
-
features: [{
|
|
277
|
-
description: "Create missing provider resources for the app's Definitions.",
|
|
278
|
-
name: "run",
|
|
279
|
-
run,
|
|
280
|
-
usage: "vitehub provision run --provider <cloudflare|vercel> [--dry-run]"
|
|
281
|
-
}],
|
|
282
|
-
name: "provision"
|
|
283
1387
|
};
|
|
1388
|
+
const nitro = createCliDiscoveryNitroCloser();
|
|
1389
|
+
try {
|
|
1390
|
+
return await resolveConfig({
|
|
1391
|
+
...inlineConfig,
|
|
1392
|
+
plugins: [nitro.plugin]
|
|
1393
|
+
}, command, mode ?? (command === "build" ? "production" : "development"));
|
|
1394
|
+
} finally {
|
|
1395
|
+
await nitro.close();
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
/** Keeps at least two spaces between a help name and its description. */
|
|
1399
|
+
function helpNameWidth(names) {
|
|
1400
|
+
return Math.max(12, ...names.map((name) => name.length + 1));
|
|
284
1401
|
}
|
|
285
|
-
function writeRootHelp(namespaces, stdout) {
|
|
1402
|
+
function writeRootHelp(namespaces, commands, stdout) {
|
|
1403
|
+
const width = helpNameWidth([...commands, ...namespaces].map((item) => item.name));
|
|
286
1404
|
stdout.write([
|
|
287
1405
|
"Usage: vitehub <namespace> <feature> [args...]",
|
|
1406
|
+
" vitehub <command> [args...]",
|
|
288
1407
|
"",
|
|
1408
|
+
...commands.length ? [
|
|
1409
|
+
"Project:",
|
|
1410
|
+
...commands.map((command) => ` ${command.name.padEnd(width)} ${command.description}`.trimEnd()),
|
|
1411
|
+
""
|
|
1412
|
+
] : [],
|
|
289
1413
|
"Available namespaces:",
|
|
290
|
-
...namespaces.map((namespace) => ` ${namespace.name.padEnd(
|
|
1414
|
+
...namespaces.map((namespace) => ` ${namespace.name.padEnd(width)} ${namespace.description || ""}`.trimEnd()),
|
|
291
1415
|
""
|
|
292
1416
|
].join("\n"));
|
|
293
1417
|
}
|
|
294
1418
|
function writeNamespaceHelp(namespace, stdout) {
|
|
1419
|
+
const width = helpNameWidth(namespace.features.map((feature) => feature.name));
|
|
295
1420
|
stdout.write([
|
|
296
1421
|
`Usage: vitehub ${namespace.name} <feature> [args...]`,
|
|
297
1422
|
"",
|
|
298
1423
|
namespace.description || "",
|
|
299
1424
|
"",
|
|
300
1425
|
"Available features:",
|
|
301
|
-
...namespace.features.flatMap((feature) => [` ${feature.name.padEnd(
|
|
1426
|
+
...namespace.features.flatMap((feature) => [` ${feature.name.padEnd(width)} ${feature.description || ""}`.trimEnd(), ...feature.usage ? [` Usage: ${feature.usage}`] : []]),
|
|
302
1427
|
""
|
|
303
1428
|
].filter(Boolean).join("\n"));
|
|
304
1429
|
}
|
|
305
1430
|
function isRootHelp(args) {
|
|
306
1431
|
return args[0] === "-h" || args[0] === "--help";
|
|
307
1432
|
}
|
|
1433
|
+
function isHelpFlag(arg) {
|
|
1434
|
+
return arg === "-h" || arg === "--help";
|
|
1435
|
+
}
|
|
1436
|
+
/** The namespace that answers `vitehub <namespace> [<feature>] --help` without the project, if one does. */
|
|
1437
|
+
async function loadHelpNamespace(args, helpNamespaces) {
|
|
1438
|
+
const [name, feature, ...rest] = args;
|
|
1439
|
+
if (!name || !helpNamespaces || !Object.hasOwn(helpNamespaces, name) || BUILTIN_NAMESPACE_NAMES.has(name)) return;
|
|
1440
|
+
if (!isHelpFlag(feature) && !rest.some(isHelpFlag)) return;
|
|
1441
|
+
const namespace = await helpNamespaces[name]();
|
|
1442
|
+
if (namespace && (isHelpFlag(feature) || namespace.features.some((item) => item.name === feature))) return namespace;
|
|
1443
|
+
}
|
|
308
1444
|
function readPackageVersion() {
|
|
309
1445
|
const manifest = readFileSync(new URL("../package.json", import.meta.url), "utf8");
|
|
310
1446
|
const version = /"version"\s*:\s*"([^"\\]+)"/u.exec(manifest)?.[1];
|
|
311
|
-
if (!version) throw
|
|
1447
|
+
if (!version) throw cliErrorDiagnostics.CLI_R0002({ message: "[vitehub] The installed @vite-hub/cli package manifest has no valid version." });
|
|
312
1448
|
return version;
|
|
313
1449
|
}
|
|
1450
|
+
/** The last `--stage <name>` or `--stage=<name>` of the command. */
|
|
1451
|
+
function readStageArg(args) {
|
|
1452
|
+
let stage;
|
|
1453
|
+
for (let index = 0; index < args.length; index++) {
|
|
1454
|
+
const arg = args[index];
|
|
1455
|
+
if (arg.startsWith("--stage=")) stage = arg.slice(8) || void 0;
|
|
1456
|
+
else if (arg === "--stage") {
|
|
1457
|
+
const value = args[++index];
|
|
1458
|
+
stage = value && !value.startsWith("-") ? value : void 0;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
return stage;
|
|
1462
|
+
}
|
|
314
1463
|
async function runViteHubCli(options = {}) {
|
|
315
|
-
const args = options.args || process.argv.slice(2);
|
|
316
|
-
const stdout = options.stdout
|
|
1464
|
+
const args = options.args || process$1.argv.slice(2);
|
|
1465
|
+
const stdout = { write: options.stdout ? options.stdout.write.bind(options.stdout) : getStableStdoutWrite() };
|
|
317
1466
|
if (args[0] === "-v" || args[0] === "--version") {
|
|
318
1467
|
stdout.write(`${readPackageVersion()}\n`);
|
|
319
1468
|
return 0;
|
|
320
1469
|
}
|
|
321
|
-
const cwd = options.cwd || process.cwd();
|
|
322
|
-
const env = options.env || process.env;
|
|
323
|
-
const stderr = options.stderr || process.stderr;
|
|
324
|
-
const
|
|
325
|
-
const
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
1470
|
+
const cwd = options.cwd || process$1.cwd();
|
|
1471
|
+
const env = options.env || process$1.env;
|
|
1472
|
+
const stderr = options.stderr || { write: (chunk, encoding, callback) => typeof encoding === "function" ? process$1.stderr.write(chunk, encoding) : process$1.stderr.write(chunk, encoding, callback) };
|
|
1473
|
+
const spawn = options.spawn || defaultSpawn;
|
|
1474
|
+
const stage = args[0] === "channels" && (args[1] === "sync" || args[1] === "history") || args[0] === "seed" ? readStageArg(args) : void 0;
|
|
1475
|
+
const loadProject = (command) => withStdoutOnStderr(async () => {
|
|
1476
|
+
const loadConfig = options.loadConfig || loadViteConfig;
|
|
1477
|
+
const loadNuxtConfig = options.loadNuxtViteConfig || loadNuxtViteConfig;
|
|
1478
|
+
const config = await (stage ? loadConfig(cwd, command, stage) : loadConfig(cwd, command));
|
|
1479
|
+
const nuxtConfig = config.vitehubConfigResolved ? void 0 : await (stage ? loadNuxtConfig(cwd, command, stage) : loadNuxtConfig(cwd, command));
|
|
1480
|
+
const plugins = nuxtConfig?.plugins ?? config.plugins;
|
|
1481
|
+
return {
|
|
1482
|
+
contribution: await collectViteHubCliContribution(plugins),
|
|
1483
|
+
handlers: resolveRouteHandlers(nuxtConfig ? nuxtConfig.nitro : config.nitro, nuxtConfig?.root || config.root || cwd),
|
|
1484
|
+
operations: await loadCliOperations(plugins, stderr),
|
|
1485
|
+
plugins,
|
|
1486
|
+
rootDir: resolve(nuxtConfig?.root || config.root || cwd)
|
|
1487
|
+
};
|
|
1488
|
+
}, stderr);
|
|
1489
|
+
const loadProvision = options.loadProvision ?? (async (host) => {
|
|
1490
|
+
const loaded = await withViteStageEnvironment({
|
|
1491
|
+
...env,
|
|
1492
|
+
VITEHUB_HOST: host,
|
|
1493
|
+
VITEHUB_HOST_SOURCE: "cli"
|
|
1494
|
+
}, () => loadProject("build"));
|
|
1495
|
+
return {
|
|
1496
|
+
rootDir: loaded.rootDir,
|
|
1497
|
+
steps: loaded.contribution.provision
|
|
1498
|
+
};
|
|
1499
|
+
});
|
|
1500
|
+
const loadCommands = async () => options.commands ?? [...await loadSetupCommands(), drainCommand];
|
|
1501
|
+
const setupCommand = options.commands || setupCommandNames.includes(args[0] ?? "") ? (await loadCommands()).find((item) => item.name === args[0]) : void 0;
|
|
1502
|
+
if (setupCommand) return await setupCommand.run(args.slice(1), {
|
|
1503
|
+
cwd,
|
|
1504
|
+
env,
|
|
1505
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
1506
|
+
loadProvision,
|
|
1507
|
+
rootDir: cwd,
|
|
1508
|
+
...options.runHostCli ? { runHostCli: options.runHostCli } : {},
|
|
1509
|
+
spawn,
|
|
1510
|
+
stderr,
|
|
1511
|
+
stdout
|
|
1512
|
+
});
|
|
1513
|
+
const runtimeNamespace = options.runtimeNamespaces?.find((namespace) => namespace.name === args[0] && !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
|
|
1514
|
+
if (runtimeNamespace) return await runNamespace(runtimeNamespace, args, {
|
|
1515
|
+
cwd,
|
|
1516
|
+
env,
|
|
1517
|
+
rootDir: cwd,
|
|
1518
|
+
spawn,
|
|
1519
|
+
stderr,
|
|
1520
|
+
stdout
|
|
1521
|
+
});
|
|
1522
|
+
const runtimeFeatures = [...options.runtimeFeatures ?? [], hostEnvFeatures].find((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && namespace.name === args[0] && namespace.features.some((feature) => feature.name === args[1]));
|
|
1523
|
+
if (runtimeFeatures && (await options.runtimeFeatureGuard?.(args[0], args[1], cwd) ?? true)) return await runNamespace(runtimeFeatures, args, {
|
|
1524
|
+
cwd,
|
|
1525
|
+
env,
|
|
1526
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
1527
|
+
rootDir: cwd,
|
|
1528
|
+
...options.runHostCli ? { runHostCli: options.runHostCli } : {},
|
|
1529
|
+
spawn,
|
|
1530
|
+
stderr,
|
|
1531
|
+
stdout
|
|
1532
|
+
});
|
|
1533
|
+
const helpNamespace = await loadHelpNamespace(args, options.helpNamespaces);
|
|
1534
|
+
if (helpNamespace) return await runNamespace(helpNamespace, args, {
|
|
1535
|
+
cwd,
|
|
1536
|
+
env,
|
|
1537
|
+
rootDir: cwd,
|
|
1538
|
+
spawn,
|
|
1539
|
+
stderr,
|
|
1540
|
+
stdout
|
|
1541
|
+
});
|
|
1542
|
+
const command = args[0] === "inspect" && (args[1] === "output" || args[1] === "resources" || args[1] === "routes") ? "build" : "serve";
|
|
1543
|
+
const { contribution, handlers, operations, plugins, rootDir } = await (stage ? withViteStageEnvironment(env, () => loadProject(command)) : loadProject(command));
|
|
1544
|
+
const runtimeNamespaces = (options.runtimeNamespaces ?? []).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
|
|
1545
|
+
const runtimeNames = new Set(runtimeNamespaces.map((namespace) => namespace.name));
|
|
1546
|
+
const namespaces = [
|
|
1547
|
+
...mergeOperationNamespaces(contribution.namespaces, createOperationNamespaces(operations)).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && !runtimeNames.has(namespace.name)),
|
|
1548
|
+
createInspectNamespace(plugins, operations, handlers),
|
|
1549
|
+
createProvisionNamespace(contribution.provision),
|
|
1550
|
+
createSeedNamespace(contribution.seeds),
|
|
1551
|
+
...runtimeNamespaces
|
|
1552
|
+
];
|
|
1553
|
+
const envIndex = namespaces.findIndex((namespace) => namespace.name === hostEnvFeatures.name);
|
|
1554
|
+
const envNamespace = namespaces[envIndex];
|
|
1555
|
+
if (envNamespace) namespaces[envIndex] = {
|
|
1556
|
+
...envNamespace,
|
|
1557
|
+
features: [...envNamespace.features, ...hostEnvFeatures.features.filter((feature) => !envNamespace.features.some((item) => item.name === feature.name))]
|
|
1558
|
+
};
|
|
1559
|
+
else namespaces.push(hostEnvFeatures);
|
|
329
1560
|
const context = {
|
|
330
1561
|
cwd,
|
|
331
1562
|
env,
|
|
1563
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
1564
|
+
...contribution.publicUrl ? { publicUrl: contribution.publicUrl } : {},
|
|
332
1565
|
rootDir,
|
|
333
|
-
|
|
1566
|
+
...options.runHostCli ? { runHostCli: options.runHostCli } : {},
|
|
1567
|
+
spawn,
|
|
334
1568
|
stderr,
|
|
335
1569
|
stdout
|
|
336
1570
|
};
|
|
337
1571
|
if (!args.length || isRootHelp(args)) {
|
|
338
|
-
writeRootHelp(namespaces, stdout);
|
|
1572
|
+
writeRootHelp(namespaces, await loadCommands(), stdout);
|
|
339
1573
|
return 0;
|
|
340
1574
|
}
|
|
341
1575
|
const namespaceName = args[0];
|
|
342
1576
|
const namespace = namespaces.find((item) => item.name === namespaceName);
|
|
343
1577
|
if (!namespace) {
|
|
344
1578
|
stderr.write(`Unknown ViteHub CLI namespace: ${namespaceName}\n`);
|
|
345
|
-
|
|
1579
|
+
if (namespaces.every((item) => BUILTIN_NAMESPACE_NAMES.has(item.name) || item === hostEnvFeatures)) stderr.write(`No ViteHub integration contributed the "${namespaceName}" commands. Run this from a configured project and enable the matching integration in vite.config.ts or nuxt.config.ts.\n`);
|
|
1580
|
+
writeRootHelp(namespaces, await loadCommands(), stderr);
|
|
346
1581
|
return 1;
|
|
347
1582
|
}
|
|
1583
|
+
return await runNamespace(namespace, args, context);
|
|
1584
|
+
}
|
|
1585
|
+
async function runNamespace(namespace, args, context) {
|
|
1586
|
+
const { stderr, stdout } = context;
|
|
348
1587
|
const featureName = args[1];
|
|
349
|
-
|
|
1588
|
+
const defaultFeature = namespace.defaultFeature ? namespace.features.find((item) => item.name === namespace.defaultFeature) : void 0;
|
|
1589
|
+
if (defaultFeature?.name === namespace.name && namespace.features.length === 1) return await defaultFeature.run(args.slice(1), context) ?? 0;
|
|
1590
|
+
if (featureName === "-h" || featureName === "--help") {
|
|
1591
|
+
writeNamespaceHelp(namespace, stdout);
|
|
1592
|
+
return 0;
|
|
1593
|
+
}
|
|
1594
|
+
if (defaultFeature && (!featureName || featureName.startsWith("-") || !namespace.features.some((item) => item.name === featureName))) return await defaultFeature.run(args.slice(1), context) ?? 0;
|
|
1595
|
+
if (!featureName) {
|
|
350
1596
|
writeNamespaceHelp(namespace, stdout);
|
|
351
1597
|
return 0;
|
|
352
1598
|
}
|
|
@@ -361,8 +1607,12 @@ async function runViteHubCli(options = {}) {
|
|
|
361
1607
|
function trackStream(stream) {
|
|
362
1608
|
const writes = [];
|
|
363
1609
|
return {
|
|
364
|
-
stream: { write(chunk) {
|
|
365
|
-
const result = stream.write
|
|
1610
|
+
stream: { write(chunk, encoding, callback) {
|
|
1611
|
+
const result = Reflect.apply(stream.write, stream, [
|
|
1612
|
+
chunk,
|
|
1613
|
+
encoding,
|
|
1614
|
+
callback
|
|
1615
|
+
]);
|
|
366
1616
|
writes.push(Promise.resolve(result).then((value) => ({
|
|
367
1617
|
status: "fulfilled",
|
|
368
1618
|
value
|
|
@@ -392,12 +1642,15 @@ function processEntrypointStream(stream) {
|
|
|
392
1642
|
if (error) rejectFlush(error);
|
|
393
1643
|
else resolveFlush();
|
|
394
1644
|
})),
|
|
395
|
-
write: (chunk) =>
|
|
1645
|
+
write: ((chunk, encoding, callback) => {
|
|
1646
|
+
if (typeof encoding === "function") return stream.write(chunk, encoding);
|
|
1647
|
+
return stream.write(chunk, encoding, callback);
|
|
1648
|
+
})
|
|
396
1649
|
};
|
|
397
1650
|
}
|
|
398
1651
|
function runViteHubCliEntrypoint(options = {}) {
|
|
399
|
-
const stderr = trackStream(options.stderr || processEntrypointStream(process.stderr));
|
|
400
|
-
const stdout = trackStream(options.stdout || processEntrypointStream(process.stdout));
|
|
1652
|
+
const stderr = trackStream(options.stderr || processEntrypointStream(process$1.stderr));
|
|
1653
|
+
const stdout = trackStream(options.stdout || processEntrypointStream(process$1.stdout));
|
|
401
1654
|
(async () => {
|
|
402
1655
|
let exitCode;
|
|
403
1656
|
try {
|
|
@@ -408,22 +1661,13 @@ function runViteHubCliEntrypoint(options = {}) {
|
|
|
408
1661
|
});
|
|
409
1662
|
} catch (error) {
|
|
410
1663
|
try {
|
|
411
|
-
stderr.stream.write(`${error
|
|
1664
|
+
stderr.stream.write(`${formatRuntimeDiagnosticError(error)}\n`);
|
|
412
1665
|
} catch {}
|
|
413
1666
|
exitCode = 1;
|
|
414
1667
|
}
|
|
415
1668
|
if ((await Promise.allSettled([stdout.flush(), stderr.flush()])).some((result) => result.status === "rejected")) exitCode = 1;
|
|
416
|
-
process.exit(exitCode);
|
|
1669
|
+
process$1.exit(exitCode);
|
|
417
1670
|
})();
|
|
418
1671
|
}
|
|
419
|
-
function isCliEntrypoint() {
|
|
420
|
-
if (!process.argv[1]) return false;
|
|
421
|
-
try {
|
|
422
|
-
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
423
|
-
} catch {
|
|
424
|
-
return false;
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
if (isCliEntrypoint()) runViteHubCliEntrypoint();
|
|
428
1672
|
//#endregion
|
|
429
1673
|
export { runViteHubCli, runViteHubCliEntrypoint };
|