@vite-hub/workspace 0.1.0 → 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 +164 -107
- package/dist/abort-BCwpdrN0.js +32 -0
- package/dist/blob-database.d.ts +70 -117
- package/dist/blob-database.js +48 -41
- package/dist/checkout.d.ts +128 -0
- package/dist/checkout.js +849 -0
- package/dist/cloudflare.d.ts +2 -2
- package/dist/cloudflare.js +1 -1
- package/dist/config-B-863EgC.js +15 -0
- package/dist/{config-B7dmzDX3.js → config-BAgL2dtB.js} +48 -84
- package/dist/{config-DLKdaFWN.d.ts → config-BQKcPawI.d.ts} +1 -1
- package/dist/discard-CNNtCozM.js +8 -0
- package/dist/durability.d.ts +22 -0
- package/dist/durability.js +70 -0
- package/dist/error-diagnostics-CtKjGtGb.js +188 -0
- package/dist/error-diagnostics-DSkCJC_L.js +266 -0
- package/dist/file-2pFYNtsU.js +22 -0
- package/dist/{files-C7Px8uaC.js → files-BOo4SbwE.js} +2 -2
- package/dist/files.d.ts +38 -0
- package/dist/files.js +6 -0
- package/dist/{github-CPxHtFB7.js → github-CrYp4v8k.js} +32 -5
- package/dist/{glob--XcLlcml.js → glob-B8YGvTrZ.js} +4 -5
- package/dist/{glob--kNYDbfU.js → glob-Cjxms1t7.js} +1 -1
- package/dist/{host-CFnrTXTK.js → host-BFBpXn0N.js} +58 -47
- package/dist/{hosted-acMA5XyL.js → hosted-KcUR_jPv.js} +216 -93
- package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
- package/dist/hosted-vercel-blob.d.ts +2 -2
- package/dist/hosted-vercel-blob.js +1 -1
- package/dist/hosted.d.ts +5 -3
- package/dist/hosted.js +2 -2
- package/dist/index.d.ts +9 -51
- package/dist/index.js +21 -91
- package/dist/{lifecycle-BwZ7c9hb.js → lifecycle-B-enk_4A.js} +8 -8
- package/dist/lineage.d.ts +26 -0
- package/dist/lineage.js +76 -0
- package/dist/loader.d.ts +1 -1
- package/dist/loader.js +2 -2
- package/dist/{mcp-resources-BREFCmtn.js → mcp-resources-DF0F5rcL.js} +2 -2
- package/dist/{memory-BbwOqDXl.js → memory-BOexthyW.js} +3 -4
- package/dist/{metadata-target-DZEZQGHA.js → metadata-target-CWz6KHKq.js} +17 -16
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-C6FpR8Rr.js +389 -0
- package/dist/operations-CE2drFih.js +1234 -0
- package/dist/operations.d.ts +41 -4
- package/dist/operations.js +3 -2
- package/dist/{path-CNAwN7pw.js → path--wrT_Azm.js} +2 -3
- package/dist/path-AxMho1wo.d.ts +7 -0
- package/dist/{plugins-DqQ8b4T5.d.ts → plugins-C8C0auoW.d.ts} +1 -1
- package/dist/{provider-kXjfli9u.js → provider-9s4Ufkm5.js} +104 -82
- package/dist/providers/github/store.d.ts +1 -1
- package/dist/providers/github/store.js +1 -1
- package/dist/registry-B3BBm4Ts.d.ts +19 -0
- package/dist/{registry-Bp-8UUfG.js → registry-CNphafBx.js} +55 -20
- package/dist/registry-CYNN623b.d.ts +9 -0
- package/dist/request-scope-Dw5n8bMC.js +83 -0
- package/dist/results-DgkZUmTL.js +8 -0
- package/dist/{rolldown-runtime-B4iAMlE-.js → rolldown-runtime-rQ84J-ij.js} +2 -3
- package/dist/runtime/assets.d.ts +1 -1
- package/dist/runtime/assets.js +3 -3
- package/dist/runtime/empty-assets-registry.d.ts +1 -1
- package/dist/runtime/empty-registry.d.ts +2 -1
- package/dist/runtime/registry.d.ts +2 -0
- package/dist/runtime/registry.js +23 -0
- package/dist/runtime/request.d.ts +4 -0
- package/dist/runtime/request.js +8 -0
- package/dist/runtime/state.d.ts +5 -4
- package/dist/runtime/state.js +8 -18
- package/dist/runtime/workspace.d.ts +1 -1
- package/dist/runtime/workspace.js +1 -1
- package/dist/runtime.d.ts +9 -8
- package/dist/runtime.js +23 -26
- package/dist/{search-CrTmXj5h.js → search-C_RfoM2j.js} +2 -2
- package/dist/{server-BNQ-Nbjj.js → server-8tGltlGz.js} +53 -40
- package/dist/server.d.ts +17 -8
- package/dist/server.js +1 -1
- package/dist/shared-B3_EUk89.js +848 -0
- package/dist/source-metadata.d.ts +6 -2
- package/dist/source-metadata.js +8 -8
- package/dist/state-BISnUf1s.d.ts +35 -0
- package/dist/{ai-BZyLwULx.js → state-DbrW-njQ.js} +96 -54
- package/dist/{store-CXgmu-uw.js → store-ybhyD38Z.js} +250 -106
- package/dist/{sync-CN6ec-5M.js → sync-CCD_VYC8.js} +4 -4
- package/dist/target-jWhTdIuF.js +89 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/{types-DeK9GIxy.d.ts → types-BbtwmBZ5.d.ts} +68 -14
- package/dist/use-C6lV3-wC.d.ts +321 -0
- package/dist/{use-BQj7nSz6.js → use-CSpT5W87.js} +75 -82
- package/dist/{utils-Blrh4N2n.js → utils-CgMZCHsX.js} +112 -41
- package/dist/vite.d.ts +585 -2
- package/dist/vite.js +21368 -1
- package/dist/{workspace-BWJQBK1u.d.ts → workspace-CYB2xZ1T.d.ts} +1 -1
- package/dist/{workspace-6pxkOuxr.js → workspace-sPWn2Jxj.js} +125 -40
- package/package.json +46 -55
- package/dist/ai-BW2ZhizI.d.ts +0 -177
- package/dist/ai.d.ts +0 -3
- package/dist/ai.js +0 -2
- package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +0 -19
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-DY5GP47p.js +0 -96
- package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +0 -354
- package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +0 -214
- package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +0 -527
- package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +0 -248
- package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +0 -179
- package/dist/file-C0_aPWSS.js +0 -26
- package/dist/file-metadata-CxDy-E2H.js +0 -58
- package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +0 -2278
- package/dist/github-DtncTfmv-Du2S8lGF.js +0 -4159
- package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +0 -2530
- package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +0 -489
- package/dist/hosted-vercel-blob-DKntsHaf.js +0 -12603
- package/dist/inspect-BoObD2cJ.js +0 -167
- package/dist/mountx.d.ts +0 -8
- package/dist/mountx.js +0 -145
- package/dist/nitro.d.ts +0 -2
- package/dist/nitro.js +0 -2
- package/dist/nuxt.d.ts +0 -27
- package/dist/nuxt.js +0 -38
- package/dist/operations-BcpWr41m.js +0 -159
- package/dist/operations-CGqY1XeG.js +0 -965
- package/dist/operations-DnOwKsJT.d.ts +0 -136
- package/dist/registry-Cg1TJVVZ.d.ts +0 -10
- package/dist/request-execution-Dk9rY-Yh.js +0 -84
- package/dist/shared-DalXdP0i.js +0 -2158
- package/dist/state-B8zbLi5t.d.ts +0 -26
- package/dist/target-D4Bqb1eH.js +0 -11
- package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +0 -125
- package/dist/token-CO62GglH.js +0 -61
- package/dist/use-DhwhbAVV.d.ts +0 -108
- package/dist/vite-BEvgU2GY.js +0 -20909
- package/dist/vite-CcZmMQ7S.d.ts +0 -476
- package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +0 -1565
|
@@ -0,0 +1,1234 @@
|
|
|
1
|
+
import { t as workspaceCommitRequestBytes } from "./results-DgkZUmTL.js";
|
|
2
|
+
import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
|
|
3
|
+
import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
|
|
4
|
+
import { basename, dirname, join, parse, resolve } from "node:path";
|
|
5
|
+
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
6
|
+
import "node:fs/promises";
|
|
7
|
+
import * as v from "valibot";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
10
|
+
import { createBirpc } from "birpc";
|
|
11
|
+
import { toJsonSchema } from "@valibot/to-json-schema";
|
|
12
|
+
//#region ../internal/src/build/vite.ts
|
|
13
|
+
const generatedViteHubFilesPattern = "**/.vitehub/**";
|
|
14
|
+
const projectRootDirectoryMarkers = [
|
|
15
|
+
["server", "agents"],
|
|
16
|
+
["server", "channels"],
|
|
17
|
+
["server", "connections"],
|
|
18
|
+
["server", "browsers"],
|
|
19
|
+
["server", "emails"],
|
|
20
|
+
["server", "schedules"],
|
|
21
|
+
["server", "workspaces"]
|
|
22
|
+
];
|
|
23
|
+
const projectRootFileMarkers = [
|
|
24
|
+
["package.json"],
|
|
25
|
+
["nuxt.config.ts"],
|
|
26
|
+
["nuxt.config.mts"],
|
|
27
|
+
["nuxt.config.js"],
|
|
28
|
+
["nuxt.config.mjs"]
|
|
29
|
+
];
|
|
30
|
+
const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
|
|
31
|
+
const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
|
|
32
|
+
const VITEHUB_ENV_DESCRIPTION_ID = "#vitehub/env/description";
|
|
33
|
+
function createNoExternalAddition(...packageNames) {
|
|
34
|
+
return (current) => {
|
|
35
|
+
if (current === true) return;
|
|
36
|
+
const values = Array.isArray(current) ? current : [current];
|
|
37
|
+
const missing = packageNames.filter((packageName) => !values.includes(packageName));
|
|
38
|
+
return missing.length ? missing : void 0;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function isServerEnvironment(name, config) {
|
|
42
|
+
return name === "ssr" || config.consumer === "server";
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Whether Node loads installed ViteHub packages directly in this environment, without Vite's SSR transform.
|
|
46
|
+
* This is the Nitro environment of `vite dev`. Generated Nitro plugins give these packages the registries and the
|
|
47
|
+
* `define` values that Vite gives to the code it transforms. Builds and other environments still inline the packages.
|
|
48
|
+
*/
|
|
49
|
+
function loadsViteHubPackagesNatively(name, env) {
|
|
50
|
+
return env.command === "serve" && name === "nitro";
|
|
51
|
+
}
|
|
52
|
+
const nativePackageDistFile = /\/node_modules\/@vite-hub\/(?:agent|connections|runtime|workspace)\/dist\/.+\.js$/;
|
|
53
|
+
/**
|
|
54
|
+
* Generated code imports the runtime files of its owner by path. Vite gives Node only bare package names, so in the
|
|
55
|
+
* Nitro environment of `vite dev` it would inline a second copy of a package that Node already loaded, with its own
|
|
56
|
+
* registries. This returns a module that lets Node load the file instead, so the app and the generated code share one
|
|
57
|
+
* instance. Use it as the `load` hook result for the file. It returns nothing for other files and environments.
|
|
58
|
+
*/
|
|
59
|
+
function loadNativePackageModule(id, environmentName, command) {
|
|
60
|
+
if (!environmentName || !loadsViteHubPackagesNatively(environmentName, { command })) return;
|
|
61
|
+
const file = id.startsWith("file:") ? fileURLToPath(id) : id;
|
|
62
|
+
if (!nativePackageDistFile.test(file.replace(/\\/g, "/"))) return;
|
|
63
|
+
const url = JSON.stringify(pathToFileURL(realpathSync(file)).href);
|
|
64
|
+
const hasDefault = /\bexport default\b|\bas default\b/.test(readFileSync(file, "utf8"));
|
|
65
|
+
const native = JSON.stringify(`data:text/javascript,${encodeURIComponent(`export * from ${url}${hasDefault ? `\nexport { default } from ${url}` : ""}`)}`);
|
|
66
|
+
return `export * from ${native}\n${hasDefault ? `export { default } from ${native}\n` : ""}`;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Server directories that ViteHub scans for Definitions. The first entry is the application.
|
|
70
|
+
* Later entries are Nuxt layers in Nuxt priority order.
|
|
71
|
+
*/
|
|
72
|
+
const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
|
|
73
|
+
function shouldSkipViteProviderBuild(command) {
|
|
74
|
+
return command === "serve";
|
|
75
|
+
}
|
|
76
|
+
function generatedViteHubWatchIgnoredAddition(ignored) {
|
|
77
|
+
return (Array.isArray(ignored) ? ignored : [ignored]).includes(generatedViteHubFilesPattern) ? void 0 : [generatedViteHubFilesPattern];
|
|
78
|
+
}
|
|
79
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
80
|
+
const resolvedRoot = resolve(root);
|
|
81
|
+
const temporaryRoot = resolve(tmpdir());
|
|
82
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
83
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
84
|
+
if (basename(resolvedRoot) === "app") {
|
|
85
|
+
const parent = dirname(resolvedRoot);
|
|
86
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
87
|
+
"nuxt.config.ts",
|
|
88
|
+
"nuxt.config.mts",
|
|
89
|
+
"nuxt.config.js",
|
|
90
|
+
"nuxt.config.mjs"
|
|
91
|
+
]))) return parent;
|
|
92
|
+
}
|
|
93
|
+
let current = resolvedRoot;
|
|
94
|
+
while (true) {
|
|
95
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
96
|
+
if (hasProjectRootMarker(current)) return current;
|
|
97
|
+
const parent = dirname(current);
|
|
98
|
+
if (parent === current) return resolvedRoot;
|
|
99
|
+
current = parent;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
103
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
104
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (error.code !== "ENOENT") throw error;
|
|
107
|
+
}
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
function hasProjectRootMarker(root) {
|
|
111
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
112
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
113
|
+
}
|
|
114
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
115
|
+
for (const marker of markers) {
|
|
116
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
117
|
+
try {
|
|
118
|
+
if (statSync(resolve(root, ...path)).isFile()) return true;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error.code !== "ENOENT") throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
function viteHubEnvPublicModulePath(root) {
|
|
126
|
+
return resolve(root, ".vitehub", "env", "public.mjs");
|
|
127
|
+
}
|
|
128
|
+
function viteHubEnvServerModulePath(root) {
|
|
129
|
+
return resolve(root, ".vitehub", "env", "server.mjs");
|
|
130
|
+
}
|
|
131
|
+
function viteHubEnvDescriptionModulePath(root) {
|
|
132
|
+
return resolve(root, ".vitehub", "env", "description.mjs");
|
|
133
|
+
}
|
|
134
|
+
function createViteHubEnvImportAliases(root) {
|
|
135
|
+
return {
|
|
136
|
+
[VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
|
|
137
|
+
[VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root),
|
|
138
|
+
[VITEHUB_ENV_DESCRIPTION_ID]: viteHubEnvDescriptionModulePath(root)
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
143
|
+
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
144
|
+
function normalizeWindowsPath(input = "") {
|
|
145
|
+
if (!input) return input;
|
|
146
|
+
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
147
|
+
}
|
|
148
|
+
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
|
149
|
+
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
|
150
|
+
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
151
|
+
function cwd() {
|
|
152
|
+
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
|
|
153
|
+
return "/";
|
|
154
|
+
}
|
|
155
|
+
const resolve$1 = function(...arguments_) {
|
|
156
|
+
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
|
157
|
+
let resolvedPath = "";
|
|
158
|
+
let resolvedAbsolute = false;
|
|
159
|
+
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
|
160
|
+
const path = index >= 0 ? arguments_[index] : cwd();
|
|
161
|
+
if (!path || path.length === 0) continue;
|
|
162
|
+
resolvedPath = `${path}/${resolvedPath}`;
|
|
163
|
+
resolvedAbsolute = isAbsolute$1(path);
|
|
164
|
+
}
|
|
165
|
+
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
166
|
+
if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
|
|
167
|
+
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
168
|
+
};
|
|
169
|
+
function normalizeString(path, allowAboveRoot) {
|
|
170
|
+
let res = "";
|
|
171
|
+
let lastSegmentLength = 0;
|
|
172
|
+
let lastSlash = -1;
|
|
173
|
+
let dots = 0;
|
|
174
|
+
let char = null;
|
|
175
|
+
for (let index = 0; index <= path.length; ++index) {
|
|
176
|
+
if (index < path.length) char = path[index];
|
|
177
|
+
else if (char === "/") break;
|
|
178
|
+
else char = "/";
|
|
179
|
+
if (char === "/") {
|
|
180
|
+
if (lastSlash === index - 1 || dots === 1);
|
|
181
|
+
else if (dots === 2) {
|
|
182
|
+
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
183
|
+
if (res.length > 2) {
|
|
184
|
+
const lastSlashIndex = res.lastIndexOf("/");
|
|
185
|
+
if (lastSlashIndex === -1) {
|
|
186
|
+
res = "";
|
|
187
|
+
lastSegmentLength = 0;
|
|
188
|
+
} else {
|
|
189
|
+
res = res.slice(0, lastSlashIndex);
|
|
190
|
+
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
191
|
+
}
|
|
192
|
+
lastSlash = index;
|
|
193
|
+
dots = 0;
|
|
194
|
+
continue;
|
|
195
|
+
} else if (res.length > 0) {
|
|
196
|
+
res = "";
|
|
197
|
+
lastSegmentLength = 0;
|
|
198
|
+
lastSlash = index;
|
|
199
|
+
dots = 0;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (allowAboveRoot) {
|
|
204
|
+
res += res.length > 0 ? "/.." : "..";
|
|
205
|
+
lastSegmentLength = 2;
|
|
206
|
+
}
|
|
207
|
+
} else {
|
|
208
|
+
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
|
|
209
|
+
else res = path.slice(lastSlash + 1, index);
|
|
210
|
+
lastSegmentLength = index - lastSlash - 1;
|
|
211
|
+
}
|
|
212
|
+
lastSlash = index;
|
|
213
|
+
dots = 0;
|
|
214
|
+
} else if (char === "." && dots !== -1) ++dots;
|
|
215
|
+
else dots = -1;
|
|
216
|
+
}
|
|
217
|
+
return res;
|
|
218
|
+
}
|
|
219
|
+
const isAbsolute$1 = function(p) {
|
|
220
|
+
return _IS_ABSOLUTE_RE.test(p);
|
|
221
|
+
};
|
|
222
|
+
const relative$1 = function(from, to) {
|
|
223
|
+
const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
224
|
+
const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
225
|
+
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
|
|
226
|
+
const _fromCopy = [..._from];
|
|
227
|
+
for (const segment of _fromCopy) {
|
|
228
|
+
if (_to[0] !== segment) break;
|
|
229
|
+
_from.shift();
|
|
230
|
+
_to.shift();
|
|
231
|
+
}
|
|
232
|
+
return [..._from.map(() => ".."), ..._to].join("/");
|
|
233
|
+
};
|
|
234
|
+
const dirname$1 = function(p) {
|
|
235
|
+
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
|
236
|
+
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
|
|
237
|
+
return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
|
|
238
|
+
};
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region ../internal/src/inspect.ts
|
|
241
|
+
function relativeDefinitionFile(projectRoot, file) {
|
|
242
|
+
return relative$1(projectRoot, file).replaceAll("\\", "/");
|
|
243
|
+
}
|
|
244
|
+
const redactedInspectionValue = "[redacted]";
|
|
245
|
+
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
246
|
+
const secretValuePattern = /^(?:[a-z][a-z0-9+.-]*:\/\/[^/\s?#]*@|bearer\s)/i;
|
|
247
|
+
/** Whether an inspection field names a credential, regardless of its value. */
|
|
248
|
+
function isSecretInspectionKey(key) {
|
|
249
|
+
return secretKeyPattern.test(key);
|
|
250
|
+
}
|
|
251
|
+
const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
|
|
252
|
+
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;
|
|
253
|
+
const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
|
|
254
|
+
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");
|
|
255
|
+
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");
|
|
256
|
+
/**
|
|
257
|
+
* Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
|
|
258
|
+
* `name=value` pairs with a secret name are replaced with `[redacted]`.
|
|
259
|
+
*/
|
|
260
|
+
function redactInspectionText(value) {
|
|
261
|
+
return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Removes values that can carry credentials before inspection output leaves the process.
|
|
265
|
+
* Keys that name secrets, plaintext Worker `vars`, and URLs with embedded credentials are redacted.
|
|
266
|
+
*/
|
|
267
|
+
function redactInspectionValue(value, key) {
|
|
268
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
269
|
+
let remaining = 1e3;
|
|
270
|
+
function visit(entry, entryKey, depth = 0) {
|
|
271
|
+
if (entryKey && isSecretInspectionKey(entryKey)) return redactedInspectionValue;
|
|
272
|
+
if (--remaining < 0 || depth > 10) return "[truncated]";
|
|
273
|
+
if (typeof entry === "string") {
|
|
274
|
+
const text = entry.slice(0, 1e4);
|
|
275
|
+
return secretValuePattern.test(text) ? redactedInspectionValue : redactInspectionText(text);
|
|
276
|
+
}
|
|
277
|
+
if (typeof entry === "bigint") return entry.toString();
|
|
278
|
+
if (typeof entry === "number") return Number.isFinite(entry) ? entry : String(entry);
|
|
279
|
+
if (entry === null || typeof entry === "boolean") return entry;
|
|
280
|
+
if (typeof entry !== "object") return entry === void 0 ? null : "[unsupported]";
|
|
281
|
+
if (seen.has(entry)) return "[circular]";
|
|
282
|
+
seen.add(entry);
|
|
283
|
+
try {
|
|
284
|
+
let dateTime;
|
|
285
|
+
try {
|
|
286
|
+
dateTime = Date.prototype.getTime.call(entry);
|
|
287
|
+
} catch {}
|
|
288
|
+
if (dateTime !== void 0) return Number.isNaN(dateTime) ? "Invalid Date" : Date.prototype.toISOString.call(entry);
|
|
289
|
+
if (Array.isArray(entry)) return entry.slice(0, 100).map((item) => visit(item, void 0, depth + 1));
|
|
290
|
+
let setValues;
|
|
291
|
+
try {
|
|
292
|
+
setValues = [...Set.prototype.values.call(entry)];
|
|
293
|
+
} catch {}
|
|
294
|
+
if (setValues) return setValues.slice(0, 100).map((item) => visit(item, void 0, depth + 1));
|
|
295
|
+
let mapEntries;
|
|
296
|
+
try {
|
|
297
|
+
mapEntries = [...Map.prototype.entries.call(entry)];
|
|
298
|
+
} catch {}
|
|
299
|
+
const entries = mapEntries ? mapEntries.map(([name, item]) => [String(name), item]) : Object.entries(entry);
|
|
300
|
+
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)]));
|
|
301
|
+
} finally {
|
|
302
|
+
seen.delete(entry);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return visit(value, key);
|
|
306
|
+
}
|
|
307
|
+
function resolveViteHubDevServerUrl(env) {
|
|
308
|
+
return env["VITEHUB_DEV_SERVER_URL"] || "http://localhost:5173";
|
|
309
|
+
}
|
|
310
|
+
function parseViteHubDevTimeout(value, error) {
|
|
311
|
+
if (!/^\d+$/.test(value)) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
|
|
312
|
+
const timeout = Number(value);
|
|
313
|
+
if (timeout > 2147483647) throw error("--timeout must be at most 2147483647 milliseconds.");
|
|
314
|
+
if (!Number.isInteger(timeout) || timeout < 1) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
|
|
315
|
+
return timeout;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Reads one dev target option at `args[index]`: `--url <url>`, `--server <url>`,
|
|
319
|
+
* `--url=<url>`, `--timeout <ms>` or `--timeout=<ms>`.
|
|
320
|
+
*
|
|
321
|
+
* Returns the number of extra arguments that the option used (`0` or `1`), or
|
|
322
|
+
* `undefined` when `args[index]` is not a dev target option.
|
|
323
|
+
*/
|
|
324
|
+
function readViteHubDevTargetOption(args, index, target, errors) {
|
|
325
|
+
const arg = args[index];
|
|
326
|
+
if (arg === void 0) return;
|
|
327
|
+
const readValue = () => {
|
|
328
|
+
const value = args[index + 1];
|
|
329
|
+
if (!value || value.startsWith("-")) throw errors.missingValue(`Missing value for ${arg}.`);
|
|
330
|
+
return value;
|
|
331
|
+
};
|
|
332
|
+
if (arg === "--url" || arg === "--server") {
|
|
333
|
+
target.url = readValue();
|
|
334
|
+
return 1;
|
|
335
|
+
}
|
|
336
|
+
if (arg.startsWith("--url=")) {
|
|
337
|
+
const value = arg.slice(6);
|
|
338
|
+
if (!value) throw errors.missingValue(`Missing value for ${arg}.`);
|
|
339
|
+
target.url = value;
|
|
340
|
+
return 0;
|
|
341
|
+
}
|
|
342
|
+
if (arg === "--timeout") {
|
|
343
|
+
target.timeout = parseViteHubDevTimeout(readValue(), errors.invalidTimeout);
|
|
344
|
+
return 1;
|
|
345
|
+
}
|
|
346
|
+
if (arg.startsWith("--timeout=")) {
|
|
347
|
+
target.timeout = parseViteHubDevTimeout(arg.slice(10), errors.invalidInlineTimeout);
|
|
348
|
+
return 0;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Resolves a dev endpoint route against the dev server URL. Throws when the URL is not valid.
|
|
353
|
+
*/
|
|
354
|
+
function viteHubDevEndpointUrl(serverUrl, route) {
|
|
355
|
+
return new URL(route, serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`).href;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Calls a guarded dev endpoint. Adds the endpoint guard header to `init.headers`.
|
|
359
|
+
*/
|
|
360
|
+
async function fetchViteHubDevEndpoint(fetchImpl, url, endpoint, init = {}) {
|
|
361
|
+
const headers = {
|
|
362
|
+
...Object.fromEntries(new Headers(init.headers)),
|
|
363
|
+
[endpoint.header]: endpoint.headerValue
|
|
364
|
+
};
|
|
365
|
+
return await fetchImpl(url, {
|
|
366
|
+
...init,
|
|
367
|
+
redirect: "manual",
|
|
368
|
+
headers
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
function redactInspectionUrlPart(value) {
|
|
372
|
+
const separator = value[0];
|
|
373
|
+
if (separator !== "?" && separator !== "#") return redactInspectionText(value);
|
|
374
|
+
return `${separator}${redactInspectionText(value.slice(1).split("&").map((pair) => {
|
|
375
|
+
const equals = pair.indexOf("=");
|
|
376
|
+
if (equals < 0) return pair;
|
|
377
|
+
const rawKey = pair.slice(0, equals);
|
|
378
|
+
try {
|
|
379
|
+
const entry = new URLSearchParams(pair).entries().next().value;
|
|
380
|
+
if (entry && redactInspectionValue(entry[1], entry[0]) !== entry[1]) return `${rawKey}=[redacted]`;
|
|
381
|
+
} catch {}
|
|
382
|
+
return pair;
|
|
383
|
+
}).join("&"))}`;
|
|
384
|
+
}
|
|
385
|
+
function devServerDisplayUrl(value) {
|
|
386
|
+
try {
|
|
387
|
+
const url = new URL(value);
|
|
388
|
+
const query = redactInspectionUrlPart(url.search);
|
|
389
|
+
const fragment = redactInspectionUrlPart(url.hash);
|
|
390
|
+
const hasSecretQuery = query !== url.search;
|
|
391
|
+
const hasSecretFragment = fragment !== url.hash;
|
|
392
|
+
if (!url.username && !url.password && !hasSecretQuery && !hasSecretFragment) return redactInspectionText(url.origin === "null" ? value.replace(/^[\s\S]+@/, "[redacted]@") : value);
|
|
393
|
+
if (url.username) url.username = "[redacted]";
|
|
394
|
+
if (url.password) url.password = "[redacted]";
|
|
395
|
+
const display = url.href.replace(/%5Bredacted%5D/g, "[redacted]");
|
|
396
|
+
const queryStart = display.indexOf("?");
|
|
397
|
+
const fragmentStart = display.indexOf("#");
|
|
398
|
+
const pathEnd = [queryStart, fragmentStart].filter((index) => index >= 0).sort((a, b) => a - b)[0] ?? display.length;
|
|
399
|
+
const path = display.slice(0, pathEnd);
|
|
400
|
+
return `${redactInspectionText(url.origin === "null" ? path.replace(/^[\s\S]+@/, "[redacted]@") : path)}${queryStart >= 0 ? query : ""}${fragmentStart >= 0 ? fragment : ""}`;
|
|
401
|
+
} catch {
|
|
402
|
+
const redacted = value.replace(/\/\/[\s\S]+@/g, "//[redacted]@").replace(/^[\s\S]+@/, "[redacted]@");
|
|
403
|
+
const queryStart = redacted.indexOf("?");
|
|
404
|
+
const fragmentStart = redacted.indexOf("#");
|
|
405
|
+
const pathEnd = [queryStart, fragmentStart].filter((index) => index >= 0).sort((a, b) => a - b)[0] ?? redacted.length;
|
|
406
|
+
const path = redacted.slice(0, pathEnd);
|
|
407
|
+
const queryEnd = fragmentStart >= 0 && fragmentStart > queryStart ? fragmentStart : void 0;
|
|
408
|
+
const query = queryStart >= 0 ? redactInspectionUrlPart(redacted.slice(queryStart, queryEnd)) : "";
|
|
409
|
+
const fragment = fragmentStart >= 0 ? redactInspectionUrlPart(redacted.slice(fragmentStart)) : "";
|
|
410
|
+
return `${redactInspectionText(path)}${query}${fragment}`;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Finds a Compatible Vite Development Server through the discovery `GET` of a guarded dev endpoint.
|
|
415
|
+
*
|
|
416
|
+
* Writes the reason to `stderr` and returns `undefined` when the URL is not
|
|
417
|
+
* valid, the server does not answer, or the server root does not match.
|
|
418
|
+
*/
|
|
419
|
+
async function discoverViteHubDevServer(options) {
|
|
420
|
+
let url;
|
|
421
|
+
try {
|
|
422
|
+
url = viteHubDevEndpointUrl(options.serverUrl, options.endpoint.route);
|
|
423
|
+
} catch {
|
|
424
|
+
options.stderr.write(`Invalid Vite Development Server URL: ${devServerDisplayUrl(options.serverUrl)}\n`);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
let response;
|
|
428
|
+
try {
|
|
429
|
+
response = await fetchViteHubDevEndpoint(options.fetch, url, options.endpoint, {
|
|
430
|
+
headers: { accept: "application/json" },
|
|
431
|
+
...options.signal ? { signal: options.signal } : {}
|
|
432
|
+
});
|
|
433
|
+
} catch {
|
|
434
|
+
options.stderr.write(`No Compatible Vite Development Server found at ${devServerDisplayUrl(options.serverUrl)}.\n`);
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (!response.ok) {
|
|
438
|
+
options.stderr.write(`No Compatible Vite Development Server found at ${devServerDisplayUrl(options.serverUrl)}.\n`);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
const payload = await response.json().catch(() => ({}));
|
|
442
|
+
const discovery = options.parseDiscovery ? options.parseDiscovery(payload) : isRecord(payload) ? payload : {};
|
|
443
|
+
if (options.signal?.aborted) {
|
|
444
|
+
options.stderr.write(`No Compatible Vite Development Server found at ${devServerDisplayUrl(options.serverUrl)}.\n`);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const isCompatibleRoot = options.isCompatibleRoot ?? ((rootDir, serverRoot) => serverRoot === rootDir);
|
|
448
|
+
if (discovery.root !== void 0 && typeof discovery.root !== "string") {
|
|
449
|
+
options.stderr.write("Invalid Vite Development Server discovery root.\n");
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (typeof discovery.root === "string" && !isCompatibleRoot(options.rootDir, discovery.root)) {
|
|
453
|
+
options.stderr.write(`Compatible Vite Development Server root mismatch: ${devServerDisplayUrl(discovery.root)}\n`);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
return {
|
|
457
|
+
discovery,
|
|
458
|
+
url
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
/** File in the project root where the running dev server tells commands where it listens. */
|
|
462
|
+
const viteHubDevServerFile = ".vitehub/dev-server.json";
|
|
463
|
+
/** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
|
|
464
|
+
function readViteHubDevServerFile(root) {
|
|
465
|
+
try {
|
|
466
|
+
const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
|
|
467
|
+
const url = isRecord(value) ? value.url : void 0;
|
|
468
|
+
const served = isRecord(value) ? value.root : void 0;
|
|
469
|
+
return typeof url === "string" && url && typeof served === "string" && served ? {
|
|
470
|
+
root: served,
|
|
471
|
+
url
|
|
472
|
+
} : void 0;
|
|
473
|
+
} catch {
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Where a command finds the dev server of its project: the file that the server wrote in a project root, else
|
|
479
|
+
* `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
|
|
480
|
+
*/
|
|
481
|
+
function findViteHubDevServerUrl(roots, env) {
|
|
482
|
+
for (const root of roots) {
|
|
483
|
+
const file = readViteHubDevServerFile(root);
|
|
484
|
+
if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
|
|
485
|
+
}
|
|
486
|
+
return env["VITEHUB_DEV_SERVER_URL"] || void 0;
|
|
487
|
+
}
|
|
488
|
+
//#endregion
|
|
489
|
+
//#region ../internal/src/operation-rpc.ts
|
|
490
|
+
/** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
|
|
491
|
+
const operationRpcPath = "/_vitehub/rpc";
|
|
492
|
+
function text(value) {
|
|
493
|
+
return String(value) === value && value ? value : void 0;
|
|
494
|
+
}
|
|
495
|
+
/** Read an untrusted failure body. It keeps only the diagnostic fields, so a stack never passes through. */
|
|
496
|
+
function readOperationRpcError(value) {
|
|
497
|
+
if (!isRecord(value)) return void 0;
|
|
498
|
+
const code = text(value.code);
|
|
499
|
+
const message = text(value.message);
|
|
500
|
+
const status = value.status;
|
|
501
|
+
if (!code || !message || !Number.isInteger(status)) return void 0;
|
|
502
|
+
const failure = {
|
|
503
|
+
code,
|
|
504
|
+
message,
|
|
505
|
+
status: Number(status)
|
|
506
|
+
};
|
|
507
|
+
if (text(value.fix)) failure.fix = text(value.fix);
|
|
508
|
+
if (text(value.docs)) failure.docs = text(value.docs);
|
|
509
|
+
if (isRecord(value.details)) failure.details = value.details;
|
|
510
|
+
return failure;
|
|
511
|
+
}
|
|
512
|
+
/** Read one response message. */
|
|
513
|
+
function readOperationRpcReply(value) {
|
|
514
|
+
if (!isRecord(value) || value.t !== "s") return void 0;
|
|
515
|
+
const id = text(value.i);
|
|
516
|
+
if (Object.hasOwn(value, "e")) {
|
|
517
|
+
const error = readOperationRpcError(value.e);
|
|
518
|
+
return error ? {
|
|
519
|
+
t: "s",
|
|
520
|
+
...id ? { i: id } : {},
|
|
521
|
+
e: error
|
|
522
|
+
} : void 0;
|
|
523
|
+
}
|
|
524
|
+
return id ? {
|
|
525
|
+
t: "s",
|
|
526
|
+
i: id,
|
|
527
|
+
r: value.r
|
|
528
|
+
} : void 0;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Call one operation with birpc over a request and answer transport, such as one HTTP POST per call. `send` posts the
|
|
532
|
+
* JSON message and returns the parsed answer; its own failures, such as a network error or an abort, reject.
|
|
533
|
+
*/
|
|
534
|
+
async function callOperationRpc(name, input, send) {
|
|
535
|
+
let receive;
|
|
536
|
+
let answer;
|
|
537
|
+
const notReply = /* @__PURE__ */ new Error("The answer is not a reply to the operation call.");
|
|
538
|
+
const rpc = createBirpc({}, {
|
|
539
|
+
on: (listener) => {
|
|
540
|
+
receive = listener;
|
|
541
|
+
},
|
|
542
|
+
post: async (message) => {
|
|
543
|
+
answer = await send(JSON.stringify(message));
|
|
544
|
+
const reply = readOperationRpcReply(answer.body);
|
|
545
|
+
if (!reply || reply.i !== void 0 && reply.i !== message.i) throw notReply;
|
|
546
|
+
await receive({
|
|
547
|
+
...reply,
|
|
548
|
+
i: message.i
|
|
549
|
+
});
|
|
550
|
+
},
|
|
551
|
+
proxify: false,
|
|
552
|
+
timeout: -1
|
|
553
|
+
});
|
|
554
|
+
try {
|
|
555
|
+
return {
|
|
556
|
+
ok: true,
|
|
557
|
+
value: await rpc.$call(name, ...input === void 0 ? [] : [input]),
|
|
558
|
+
answer
|
|
559
|
+
};
|
|
560
|
+
} catch (error) {
|
|
561
|
+
if (!answer) throw error;
|
|
562
|
+
if (error === notReply) return {
|
|
563
|
+
ok: false,
|
|
564
|
+
error: void 0,
|
|
565
|
+
answer
|
|
566
|
+
};
|
|
567
|
+
return {
|
|
568
|
+
ok: false,
|
|
569
|
+
error: readOperationRpcError(error),
|
|
570
|
+
answer
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
//#endregion
|
|
575
|
+
//#region ../internal/src/console-signature.ts
|
|
576
|
+
/**
|
|
577
|
+
* Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
|
|
578
|
+
* CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
|
|
579
|
+
* its env cannot sign a request. The module uses only Web Crypto, so it runs in Node, Workers, Deno, and browsers.
|
|
580
|
+
*
|
|
581
|
+
* The signature covers this text, one field per line:
|
|
582
|
+
*
|
|
583
|
+
* ```txt
|
|
584
|
+
* vitehub-signature-v1
|
|
585
|
+
* POST
|
|
586
|
+
* /_vitehub/rpc
|
|
587
|
+
* https://app.example.com
|
|
588
|
+
* 1794400000
|
|
589
|
+
* CONSOLE_3F9A12BC
|
|
590
|
+
* <SHA-256 of the body bytes, base64url>
|
|
591
|
+
* <the x-vitehub-caller header>
|
|
592
|
+
* ```
|
|
593
|
+
*/
|
|
594
|
+
/** The signature header: `key=<NAME>, t=<seconds>, origin=<app origin>, body=<SHA-256>, v1=<signature>`. */
|
|
595
|
+
const consoleSignatureHeader = "x-vitehub-signature";
|
|
596
|
+
/** Who calls, as base64url JSON. The signature covers it. See {@link ConsoleCaller}. */
|
|
597
|
+
const consoleCallerHeader = "x-vitehub-caller";
|
|
598
|
+
/** The first line of the signed text. A new format gets a new tag. */
|
|
599
|
+
const consoleSignatureVersion = "vitehub-signature-v1";
|
|
600
|
+
/** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
|
|
601
|
+
const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
|
|
602
|
+
const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
|
|
603
|
+
const encoder = new TextEncoder();
|
|
604
|
+
new TextDecoder();
|
|
605
|
+
const ed25519 = { name: "Ed25519" };
|
|
606
|
+
const pkcs8Prefix = Uint8Array.of(48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32);
|
|
607
|
+
function base64url(bytes) {
|
|
608
|
+
let binary = "";
|
|
609
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
610
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
611
|
+
}
|
|
612
|
+
/** The bytes of a base64url value, or `undefined` when it is not canonical base64url without padding. */
|
|
613
|
+
function fromBase64url(value) {
|
|
614
|
+
if (!/^[\w-]*$/.test(value) || value.length % 4 === 1) return void 0;
|
|
615
|
+
const bytes = Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
|
|
616
|
+
return base64url(bytes) === value ? bytes : void 0;
|
|
617
|
+
}
|
|
618
|
+
function bytesOf(body) {
|
|
619
|
+
if (typeof body === "string") return encoder.encode(body);
|
|
620
|
+
return body instanceof Uint8Array ? Uint8Array.from(body) : new Uint8Array(body);
|
|
621
|
+
}
|
|
622
|
+
/** The SHA-256 of the exact body bytes, base64url. A request without a body hashes zero bytes. */
|
|
623
|
+
async function consoleBodySha256(body = "") {
|
|
624
|
+
return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytesOf(body))));
|
|
625
|
+
}
|
|
626
|
+
/** The text that the signature covers. Fields are joined with `\n`. */
|
|
627
|
+
function consoleSignedText(fields) {
|
|
628
|
+
return [
|
|
629
|
+
consoleSignatureVersion,
|
|
630
|
+
fields.method.toUpperCase(),
|
|
631
|
+
fields.target,
|
|
632
|
+
fields.origin,
|
|
633
|
+
fields.timestamp,
|
|
634
|
+
fields.key,
|
|
635
|
+
fields.bodySha256,
|
|
636
|
+
fields.caller
|
|
637
|
+
].join("\n");
|
|
638
|
+
}
|
|
639
|
+
/** The path and query of a URL, the part of the request target that the signature covers. */
|
|
640
|
+
function requestTarget(url) {
|
|
641
|
+
return `${url.pathname}${url.search}`;
|
|
642
|
+
}
|
|
643
|
+
/** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
|
|
644
|
+
function isConsoleKeyName(name) {
|
|
645
|
+
return keyNamePattern.test(name);
|
|
646
|
+
}
|
|
647
|
+
async function importPrivateKey(seed) {
|
|
648
|
+
const bytes = fromBase64url(seed.trim());
|
|
649
|
+
if (bytes?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_INVALID();
|
|
650
|
+
const der = new Uint8Array(pkcs8Prefix.length + 32);
|
|
651
|
+
der.set(pkcs8Prefix);
|
|
652
|
+
der.set(bytes, pkcs8Prefix.length);
|
|
653
|
+
return await crypto.subtle.importKey("pkcs8", der, ed25519, false, ["sign"]);
|
|
654
|
+
}
|
|
655
|
+
/** The `x-vitehub-caller` value of a caller: its JSON as base64url. */
|
|
656
|
+
function encodeConsoleCaller(caller) {
|
|
657
|
+
return base64url(encoder.encode(JSON.stringify(caller)));
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Sign one request. `url` is the full URL that the request goes to, and `body` is the exact body that it sends. Returns
|
|
661
|
+
* the two headers to add: `x-vitehub-signature` and `x-vitehub-caller`.
|
|
662
|
+
*/
|
|
663
|
+
async function signConsoleRequest(options) {
|
|
664
|
+
if (!isConsoleKeyName(options.key.name)) throw internalErrorDiagnostics.INTERNAL_CONSOLE_KEY_NAME_INVALID({ name: options.key.name });
|
|
665
|
+
const url = new URL(options.url);
|
|
666
|
+
const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
|
|
667
|
+
const bodySha256 = await consoleBodySha256(options.body);
|
|
668
|
+
const caller = encodeConsoleCaller(options.caller);
|
|
669
|
+
const text = consoleSignedText({
|
|
670
|
+
bodySha256,
|
|
671
|
+
caller,
|
|
672
|
+
key: options.key.name,
|
|
673
|
+
method: options.method,
|
|
674
|
+
origin: url.origin,
|
|
675
|
+
target: requestTarget(url),
|
|
676
|
+
timestamp
|
|
677
|
+
});
|
|
678
|
+
const signature = new Uint8Array(await crypto.subtle.sign(ed25519, await importPrivateKey(options.key.privateKey), encoder.encode(text)));
|
|
679
|
+
return {
|
|
680
|
+
[consoleCallerHeader]: caller,
|
|
681
|
+
[consoleSignatureHeader]: `key=${options.key.name}, t=${timestamp}, origin=${url.origin}, body=${bodySha256}, v1=${base64url(signature)}`
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* The signing key of a CLI from its env: the one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable. Returns `undefined`
|
|
686
|
+
* without one. Throws a coded error when there are several, or when the value is not a 32-byte seed.
|
|
687
|
+
*/
|
|
688
|
+
function readConsoleSigningKey(env) {
|
|
689
|
+
const variables = Object.keys(env).filter((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && env[name]?.trim()).sort();
|
|
690
|
+
if (!variables.length) return void 0;
|
|
691
|
+
if (variables.length > 1) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE({
|
|
692
|
+
prefix: consolePrivateKeyPrefix,
|
|
693
|
+
variables: variables.join(", ")
|
|
694
|
+
});
|
|
695
|
+
const variable = variables[0];
|
|
696
|
+
const name = variable.slice(28);
|
|
697
|
+
const privateKey = env[variable].trim();
|
|
698
|
+
if (!isConsoleKeyName(name) || fromBase64url(privateKey)?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID({ variable });
|
|
699
|
+
return {
|
|
700
|
+
name,
|
|
701
|
+
privateKey
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
//#endregion
|
|
705
|
+
//#region ../internal/src/standard-schema.ts
|
|
706
|
+
function readOwn(value, key) {
|
|
707
|
+
if (value === null || Object(value) !== value) return;
|
|
708
|
+
try {
|
|
709
|
+
return Reflect.get(Object(value), key);
|
|
710
|
+
} catch {
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Read a Standard JSON Schema projection without throwing.
|
|
716
|
+
*
|
|
717
|
+
* Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
|
|
718
|
+
* (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
|
|
719
|
+
*/
|
|
720
|
+
function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
|
|
721
|
+
const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
|
|
722
|
+
const project = readOwn(jsonSchema, direction);
|
|
723
|
+
if (typeof project !== "function") return;
|
|
724
|
+
try {
|
|
725
|
+
const result = project.call(jsonSchema, libraryOptions ? {
|
|
726
|
+
target,
|
|
727
|
+
libraryOptions
|
|
728
|
+
} : { target });
|
|
729
|
+
return isRecordOrFunction(result) ? result : void 0;
|
|
730
|
+
} catch {
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
//#endregion
|
|
735
|
+
//#region ../internal/src/valibot.ts
|
|
736
|
+
const valibotTargets = /* @__PURE__ */ new Set([
|
|
737
|
+
"draft-07",
|
|
738
|
+
"draft-2020-12",
|
|
739
|
+
"openapi-3.0"
|
|
740
|
+
]);
|
|
741
|
+
function isValibotTarget(value) {
|
|
742
|
+
return valibotTargets.has(String(value));
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Add Standard JSON Schema conversion to a plain Valibot schema. Valibot schemas validate as Standard Schema but carry
|
|
746
|
+
* no JSON Schema, so forms, tools, and model providers would get no shape for them. Other schemas, Valibot schemas that
|
|
747
|
+
* already convert, and async Valibot schemas return unchanged. The copy keeps every Valibot property, so validation
|
|
748
|
+
* does not change.
|
|
749
|
+
*
|
|
750
|
+
* `target` fixes the JSON Schema dialect. Without it, each conversion uses the dialect that the caller asks for.
|
|
751
|
+
*/
|
|
752
|
+
function withValibotJsonSchema(schema, options = {}) {
|
|
753
|
+
const standard = schema["~standard"];
|
|
754
|
+
if (standard.vendor !== "valibot" || Reflect.get(schema, "async") === true) return schema;
|
|
755
|
+
if (Object.hasOwn(standard, "jsonSchema") && standard.jsonSchema) return schema;
|
|
756
|
+
const convert = (typeMode) => (request) => {
|
|
757
|
+
const target = options.target ?? request.target;
|
|
758
|
+
if (!isValibotTarget(target)) throw internalErrorDiagnostics.INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED({ target: String(target) });
|
|
759
|
+
return toJsonSchema(schema, {
|
|
760
|
+
target,
|
|
761
|
+
typeMode,
|
|
762
|
+
errorMode: "ignore"
|
|
763
|
+
});
|
|
764
|
+
};
|
|
765
|
+
return {
|
|
766
|
+
...schema,
|
|
767
|
+
"~standard": {
|
|
768
|
+
...standard,
|
|
769
|
+
jsonSchema: {
|
|
770
|
+
input: convert("input"),
|
|
771
|
+
output: convert("output")
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
//#endregion
|
|
777
|
+
//#region ../internal/src/operation-definition.ts
|
|
778
|
+
const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
|
|
779
|
+
const kinds = /* @__PURE__ */ new Set([
|
|
780
|
+
"read",
|
|
781
|
+
"write",
|
|
782
|
+
"destructive"
|
|
783
|
+
]);
|
|
784
|
+
function invalidDefinition(name, reason) {
|
|
785
|
+
return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
|
|
786
|
+
}
|
|
787
|
+
function checkDefinition(definition) {
|
|
788
|
+
if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
|
|
789
|
+
const { name } = definition;
|
|
790
|
+
if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
|
|
791
|
+
if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
|
|
792
|
+
const { section } = definition;
|
|
793
|
+
if (section !== false && !(section instanceof Function) && !isSectionId(section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false; section ids cannot contain ':'.");
|
|
794
|
+
if (definition.scope !== void 0 && (!(definition.scope instanceof Function) || String(section) !== section)) throw invalidDefinition(name, "scope must be a function, and it needs a section id.");
|
|
795
|
+
if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
|
|
796
|
+
const input = definition.input;
|
|
797
|
+
if (!isRecordOrFunction(input) || !isRecordOrFunction(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
|
|
798
|
+
if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
|
|
799
|
+
const { maxRequestBytes } = definition;
|
|
800
|
+
if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
|
|
801
|
+
if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
|
|
802
|
+
const { mcp } = definition;
|
|
803
|
+
if (mcp !== void 0 && mcp !== false && (!isRecordOrFunction(mcp) || mcp.title !== void 0 && (String(mcp.title) !== mcp.title || !mcp.title) || mcp.format !== void 0 && !(mcp.format instanceof Function))) throw invalidDefinition(name, "mcp must be false, or an object with a title string and a format function.");
|
|
804
|
+
}
|
|
805
|
+
/** The default limit of a call, in bytes. */
|
|
806
|
+
const defaultRequestBytes = 65536;
|
|
807
|
+
/** Input keys that the generated CLI commands read themselves. */
|
|
808
|
+
const reservedOperationFlags = [
|
|
809
|
+
"input",
|
|
810
|
+
"json",
|
|
811
|
+
"timeout",
|
|
812
|
+
"url",
|
|
813
|
+
"yes"
|
|
814
|
+
];
|
|
815
|
+
/**
|
|
816
|
+
* Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
|
|
817
|
+
* `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
|
|
818
|
+
*/
|
|
819
|
+
function defineOperation(definition) {
|
|
820
|
+
checkDefinition(definition);
|
|
821
|
+
const defined = {
|
|
822
|
+
...definition,
|
|
823
|
+
input: withValibotJsonSchema(definition.input)
|
|
824
|
+
};
|
|
825
|
+
const properties = operationInputJsonSchema(defined).properties;
|
|
826
|
+
const clashes = isRecordOrFunction(properties) ? Object.keys(properties).filter((key) => reservedOperationFlags.includes(key)) : [];
|
|
827
|
+
if (clashes.length) throw invalidDefinition(definition.name, `the input key ${clashes.map((key) => JSON.stringify(key)).join(", ")} is a CLI flag of every command (${reservedOperationFlags.join(", ")}). Rename it.`);
|
|
828
|
+
return defined;
|
|
829
|
+
}
|
|
830
|
+
function isSectionId(section) {
|
|
831
|
+
return typeof section === "string" && section !== "" && !section.includes(":");
|
|
832
|
+
}
|
|
833
|
+
/** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
|
|
834
|
+
function operationInputJsonSchema(operation) {
|
|
835
|
+
return standardJsonSchema(operation.input, "input") ?? { type: "object" };
|
|
836
|
+
}
|
|
837
|
+
//#endregion
|
|
838
|
+
//#region ../internal/src/operations.ts
|
|
839
|
+
/** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
|
|
840
|
+
const operationRpcHeader = "x-vitehub-console";
|
|
841
|
+
/** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
|
|
842
|
+
const operationRootHeader = "x-vitehub-root";
|
|
843
|
+
const operationExpectedRootsHeader = "x-vitehub-expected-roots";
|
|
844
|
+
/** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
|
|
845
|
+
function projectRootHash(root) {
|
|
846
|
+
const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
847
|
+
let first = 3735928559;
|
|
848
|
+
let second = 1103547991;
|
|
849
|
+
for (let index = 0; index < normalized.length; index++) {
|
|
850
|
+
const code = normalized.charCodeAt(index);
|
|
851
|
+
first = Math.imul(first ^ code, 2654435761);
|
|
852
|
+
second = Math.imul(second ^ code, 1597334677);
|
|
853
|
+
}
|
|
854
|
+
first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
|
|
855
|
+
second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
|
|
856
|
+
return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
|
|
857
|
+
}
|
|
858
|
+
/** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
|
|
859
|
+
const operationSurfaceHeader = "x-vitehub-surface";
|
|
860
|
+
/** Generated CLI commands ask the server to check confirmation after it parses the input. */
|
|
861
|
+
const operationConfirmationHeader = "x-vitehub-confirmation";
|
|
862
|
+
const operationCredentialHint = "Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key that `vitehub secret console-key` printed, and its public key in VITEHUB_CONSOLE_KEY_<NAME> on the app.";
|
|
863
|
+
/** Headers of an operation call, without a signature. */
|
|
864
|
+
function operationHeaders() {
|
|
865
|
+
const headers = new Headers();
|
|
866
|
+
headers.set("accept", "application/json");
|
|
867
|
+
headers.set("content-type", "application/json");
|
|
868
|
+
headers.set(operationRpcHeader, "1");
|
|
869
|
+
headers.set(operationSurfaceHeader, "cli");
|
|
870
|
+
return headers;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* The headers of one operation call to a deployed app: {@link operationHeaders}, and the signature of `body` when the
|
|
874
|
+
* env has a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. The CLI signs as itself, `via: "cli"`. Throws a `TypeError` for a
|
|
875
|
+
* malformed private key.
|
|
876
|
+
*/
|
|
877
|
+
async function signedOperationHeaders(env, url, body) {
|
|
878
|
+
const headers = operationHeaders();
|
|
879
|
+
const key = readConsoleSigningKey(env);
|
|
880
|
+
if (key) {
|
|
881
|
+
const signed = await signConsoleRequest({
|
|
882
|
+
body,
|
|
883
|
+
caller: { via: "cli" },
|
|
884
|
+
key,
|
|
885
|
+
method: "POST",
|
|
886
|
+
url
|
|
887
|
+
});
|
|
888
|
+
for (const [name, value] of Object.entries(signed)) headers.set(name, value);
|
|
889
|
+
}
|
|
890
|
+
return headers;
|
|
891
|
+
}
|
|
892
|
+
function unreachable(message, status = 503) {
|
|
893
|
+
const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
|
|
894
|
+
return {
|
|
895
|
+
ok: false,
|
|
896
|
+
code: error.code,
|
|
897
|
+
fix: error.fix,
|
|
898
|
+
message,
|
|
899
|
+
status
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
function hasCredentials(env) {
|
|
903
|
+
return Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && Boolean(env[name]));
|
|
904
|
+
}
|
|
905
|
+
/** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
|
|
906
|
+
async function callOperation(target, name, input) {
|
|
907
|
+
let origin = "the ViteHub app";
|
|
908
|
+
try {
|
|
909
|
+
const base = new URL(target.url);
|
|
910
|
+
if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
|
|
911
|
+
const url = new URL(operationRpcPath.slice(1), base);
|
|
912
|
+
origin = url.origin;
|
|
913
|
+
const env = target.roots?.length ? {} : target.env;
|
|
914
|
+
try {
|
|
915
|
+
readConsoleSigningKey(env);
|
|
916
|
+
} catch (error) {
|
|
917
|
+
return {
|
|
918
|
+
ok: false,
|
|
919
|
+
code: "INTERNAL_R0024",
|
|
920
|
+
fix: "Run `vitehub secret console-key` for a new key pair. Set its private key here and its public key on the app.",
|
|
921
|
+
message: error instanceof Error ? error.message : String(error),
|
|
922
|
+
status: 401
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
|
|
926
|
+
const headers = await signedOperationHeaders(env, url, body);
|
|
927
|
+
if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
|
|
928
|
+
if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
|
|
929
|
+
const response = await (target.fetch ?? fetch)(url.href, {
|
|
930
|
+
body,
|
|
931
|
+
headers,
|
|
932
|
+
method: "POST",
|
|
933
|
+
redirect: "manual",
|
|
934
|
+
signal: AbortSignal.timeout(target.timeout ?? 3e4)
|
|
935
|
+
});
|
|
936
|
+
const text = await response.text();
|
|
937
|
+
let json;
|
|
938
|
+
try {
|
|
939
|
+
json = text ? JSON.parse(text) : void 0;
|
|
940
|
+
} catch {
|
|
941
|
+
json = void 0;
|
|
942
|
+
}
|
|
943
|
+
return {
|
|
944
|
+
body: json,
|
|
945
|
+
response
|
|
946
|
+
};
|
|
947
|
+
});
|
|
948
|
+
const { response } = outcome.answer;
|
|
949
|
+
const served = response.headers.get(operationRootHeader);
|
|
950
|
+
if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
|
|
951
|
+
const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
|
|
952
|
+
const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
|
|
953
|
+
return {
|
|
954
|
+
ok: false,
|
|
955
|
+
code: error.code,
|
|
956
|
+
fix: error.fix,
|
|
957
|
+
message,
|
|
958
|
+
status: 409
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
if (outcome.ok) return {
|
|
962
|
+
ok: true,
|
|
963
|
+
value: outcome.value
|
|
964
|
+
};
|
|
965
|
+
const failure = outcome.error ?? readOperationRpcError(isRecordOrFunction(outcome.answer.body) ? {
|
|
966
|
+
status: response.status,
|
|
967
|
+
...outcome.answer.body
|
|
968
|
+
} : void 0);
|
|
969
|
+
if (failure) {
|
|
970
|
+
if (target.roots?.length && failure.status === 401) failure.fix = `Pass --url ${base.href.slice(0, -1)} to send credentials. A command sends none to the dev server that it finds. ${failure.fix ?? "Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key that `vitehub secret console-key` printed, and its public key in VITEHUB_CONSOLE_KEY_<NAME> on the app."}`;
|
|
971
|
+
if ((failure.status === 401 || failure.status === 403) && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
|
|
972
|
+
return {
|
|
973
|
+
ok: false,
|
|
974
|
+
...failure
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
|
|
978
|
+
return unreachable(`${url.origin} did not answer as a ViteHub app (HTTP ${response.status}). Pass the origin of an app that runs ViteHub.`, response.status);
|
|
979
|
+
} catch (error) {
|
|
980
|
+
return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
|
|
985
|
+
* started. Never throws. Without a dev server the result is an `INTERNAL_R0024` failure that says to start one.
|
|
986
|
+
*/
|
|
987
|
+
async function callOperationFromCli(call, name, input) {
|
|
988
|
+
let roots;
|
|
989
|
+
try {
|
|
990
|
+
roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
|
|
991
|
+
} catch {
|
|
992
|
+
roots = [call.rootDir];
|
|
993
|
+
}
|
|
994
|
+
const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
|
|
995
|
+
if (!url) return unreachable(`No dev server is running for ${roots.at(-1)}.`);
|
|
996
|
+
return await callOperation({
|
|
997
|
+
...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
|
|
998
|
+
env: call.env,
|
|
999
|
+
...call.fetch ? { fetch: call.fetch } : {},
|
|
1000
|
+
...call.url ? {} : { roots },
|
|
1001
|
+
...call.timeout ? { timeout: call.timeout } : {},
|
|
1002
|
+
url
|
|
1003
|
+
}, name, input);
|
|
1004
|
+
}
|
|
1005
|
+
/** Align rows of text cells in columns for CLI output. The last column is not padded. */
|
|
1006
|
+
function table(rows) {
|
|
1007
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
1008
|
+
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
|
|
1009
|
+
}
|
|
1010
|
+
//#endregion
|
|
1011
|
+
//#region src/operations.ts
|
|
1012
|
+
const runtime = () => import("./operations-C6FpR8Rr.js");
|
|
1013
|
+
const name = v.pipe(v.string(), v.check((value) => value.trim() !== "", "Name a Workspace."));
|
|
1014
|
+
const nonEmpty = (message) => v.pipe(v.string(), v.check((value) => value !== "", message));
|
|
1015
|
+
function defineWorkspaceOperation(definition, kind = "read") {
|
|
1016
|
+
return defineOperation({
|
|
1017
|
+
...definition,
|
|
1018
|
+
kind,
|
|
1019
|
+
section: "workspaces",
|
|
1020
|
+
...kind === "read" ? { user: false } : {}
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
function oneLine(value) {
|
|
1024
|
+
return value?.split(/\r?\n/, 1)[0]?.trim() || "-";
|
|
1025
|
+
}
|
|
1026
|
+
function formatHistory(result) {
|
|
1027
|
+
if (!result.revisions.length) return result.ref ? `No revisions on ref ${result.ref}.\n` : "No revisions.\n";
|
|
1028
|
+
const lines = [table([[
|
|
1029
|
+
"REVISION",
|
|
1030
|
+
"REF",
|
|
1031
|
+
"CREATED AT",
|
|
1032
|
+
"AUTHOR",
|
|
1033
|
+
"FILES",
|
|
1034
|
+
"MESSAGE"
|
|
1035
|
+
], ...result.revisions.map((revision) => [
|
|
1036
|
+
revision.id,
|
|
1037
|
+
revision.ref,
|
|
1038
|
+
revision.createdAt,
|
|
1039
|
+
revision.author ?? "-",
|
|
1040
|
+
String(revision.files),
|
|
1041
|
+
oneLine(revision.message)
|
|
1042
|
+
])])];
|
|
1043
|
+
if (result.cursor && result.ref) lines.push(`More revisions: vitehub workspace history ${result.workspace} --ref ${result.ref} --cursor ${result.cursor}`);
|
|
1044
|
+
else if (result.more) lines.push("More revisions exist. Use --ref <ref> to page through one ref.");
|
|
1045
|
+
return `${lines.join("\n")}\n`;
|
|
1046
|
+
}
|
|
1047
|
+
function formatRefs(result) {
|
|
1048
|
+
if (!result.refs.length) return "No refs. The Workspace has no retained revisions yet.\n";
|
|
1049
|
+
return `${table([[
|
|
1050
|
+
"REF",
|
|
1051
|
+
"HEAD",
|
|
1052
|
+
"CREATED AT",
|
|
1053
|
+
"AUTHOR",
|
|
1054
|
+
"MESSAGE"
|
|
1055
|
+
], ...result.refs.map((ref) => [
|
|
1056
|
+
ref.name,
|
|
1057
|
+
ref.head.id,
|
|
1058
|
+
ref.head.createdAt,
|
|
1059
|
+
ref.head.author ?? "-",
|
|
1060
|
+
oneLine(ref.head.message)
|
|
1061
|
+
])])}\n`;
|
|
1062
|
+
}
|
|
1063
|
+
function formatFiles(files) {
|
|
1064
|
+
if (!files.length) return "No files.";
|
|
1065
|
+
return table([[
|
|
1066
|
+
"PATH",
|
|
1067
|
+
"SIZE",
|
|
1068
|
+
"MEDIA TYPE",
|
|
1069
|
+
"DIGEST"
|
|
1070
|
+
], ...files.map((file) => [
|
|
1071
|
+
file.path,
|
|
1072
|
+
file.size === void 0 ? "-" : String(file.size),
|
|
1073
|
+
file.mediaType ?? "-",
|
|
1074
|
+
file.digest ?? "-"
|
|
1075
|
+
])]);
|
|
1076
|
+
}
|
|
1077
|
+
function formatRevision(revision) {
|
|
1078
|
+
return [
|
|
1079
|
+
`Revision: ${revision.id}`,
|
|
1080
|
+
`Ref: ${revision.ref}`,
|
|
1081
|
+
`Parent: ${revision.parentId ?? "-"}`,
|
|
1082
|
+
`Created at: ${revision.createdAt}`,
|
|
1083
|
+
`Author: ${revision.author ?? "-"}`,
|
|
1084
|
+
`Message: ${revision.message ?? "-"}`,
|
|
1085
|
+
`Files: ${revision.files} (${revision.bytes} bytes)`
|
|
1086
|
+
];
|
|
1087
|
+
}
|
|
1088
|
+
function formatShow(result) {
|
|
1089
|
+
if (result.file) {
|
|
1090
|
+
if (result.file.encoding === "utf8") return result.file.content;
|
|
1091
|
+
return `${result.file.path} is binary (${result.file.size ?? "unknown"} bytes). Run the command with --json to read its content as base64.\n`;
|
|
1092
|
+
}
|
|
1093
|
+
return `${[
|
|
1094
|
+
...formatRevision(result.revision),
|
|
1095
|
+
...result.path ? [`Path: ${result.path}`] : [],
|
|
1096
|
+
"",
|
|
1097
|
+
formatFiles(result.files ?? [])
|
|
1098
|
+
].join("\n")}\n`;
|
|
1099
|
+
}
|
|
1100
|
+
const history = defineWorkspaceOperation({
|
|
1101
|
+
cli: {
|
|
1102
|
+
command: "history",
|
|
1103
|
+
format: formatHistory,
|
|
1104
|
+
namespace: "workspace",
|
|
1105
|
+
positional: ["workspace"]
|
|
1106
|
+
},
|
|
1107
|
+
description: `List the retained revisions of a Workspace, newest first. Without \`ref\`, the list merges every ref. \`limit\` defaults to 20.`,
|
|
1108
|
+
input: v.object({
|
|
1109
|
+
cursor: v.optional(nonEmpty("The cursor cannot be empty.")),
|
|
1110
|
+
limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100))),
|
|
1111
|
+
ref: v.optional(nonEmpty("The ref cannot be empty.")),
|
|
1112
|
+
workspace: name
|
|
1113
|
+
}),
|
|
1114
|
+
name: "workspace.history",
|
|
1115
|
+
run: async (input) => await (await runtime()).runWorkspaceOperation("history", input)
|
|
1116
|
+
});
|
|
1117
|
+
const refs = defineWorkspaceOperation({
|
|
1118
|
+
cli: {
|
|
1119
|
+
command: "refs",
|
|
1120
|
+
format: formatRefs,
|
|
1121
|
+
namespace: "workspace",
|
|
1122
|
+
positional: ["workspace"]
|
|
1123
|
+
},
|
|
1124
|
+
description: "List the history refs of a Workspace and the head revision of each ref.",
|
|
1125
|
+
input: v.object({ workspace: name }),
|
|
1126
|
+
name: "workspace.refs",
|
|
1127
|
+
run: async (input) => await (await runtime()).runWorkspaceOperation("refs", input)
|
|
1128
|
+
});
|
|
1129
|
+
const show = defineWorkspaceOperation({
|
|
1130
|
+
cli: {
|
|
1131
|
+
command: "show",
|
|
1132
|
+
format: formatShow,
|
|
1133
|
+
namespace: "workspace",
|
|
1134
|
+
positional: [
|
|
1135
|
+
"workspace",
|
|
1136
|
+
"target",
|
|
1137
|
+
"path"
|
|
1138
|
+
]
|
|
1139
|
+
},
|
|
1140
|
+
description: "Show one revision of a Workspace by ref or revision id, with its files. With `path`, return that file as it was in the revision.",
|
|
1141
|
+
input: v.object({
|
|
1142
|
+
path: v.optional(nonEmpty("The path cannot be empty.")),
|
|
1143
|
+
target: nonEmpty("Name a ref or revision."),
|
|
1144
|
+
workspace: name
|
|
1145
|
+
}),
|
|
1146
|
+
name: "workspace.show",
|
|
1147
|
+
run: async (input) => await (await runtime()).runWorkspaceOperation("show", input)
|
|
1148
|
+
});
|
|
1149
|
+
function formatChanges(result) {
|
|
1150
|
+
if (!result.head) return `Ref ${result.ref} has no revisions.\n`;
|
|
1151
|
+
if (!result.files.length) return `No changes. Ref ${result.ref} is at ${result.head.id}.\n`;
|
|
1152
|
+
return `${table([["PATH", "CHANGE"], ...result.files.map((file) => [file.path, file.deleted ? "deleted" : file.base ? "changed" : "added"])])}\nHead: ${result.head.id}\n`;
|
|
1153
|
+
}
|
|
1154
|
+
const encodedFile = v.object({
|
|
1155
|
+
content: v.string(),
|
|
1156
|
+
encoding: v.picklist(["base64", "utf8"])
|
|
1157
|
+
});
|
|
1158
|
+
const changes = defineWorkspaceOperation({
|
|
1159
|
+
cli: {
|
|
1160
|
+
command: "changes",
|
|
1161
|
+
format: formatChanges,
|
|
1162
|
+
namespace: "workspace",
|
|
1163
|
+
positional: ["workspace"]
|
|
1164
|
+
},
|
|
1165
|
+
description: "List the files of a ref that changed since a revision, with their content at the head and at that revision. Without `since`, list every file of the head. `vitehub pull` reads it.",
|
|
1166
|
+
input: v.object({
|
|
1167
|
+
content: v.optional(v.boolean()),
|
|
1168
|
+
ref: v.optional(nonEmpty("The ref cannot be empty.")),
|
|
1169
|
+
since: v.optional(v.nullable(nonEmpty("The revision cannot be empty."))),
|
|
1170
|
+
workspace: name
|
|
1171
|
+
}),
|
|
1172
|
+
name: "workspace.changes",
|
|
1173
|
+
run: async (input) => await (await runtime()).runWorkspaceChanges(input)
|
|
1174
|
+
});
|
|
1175
|
+
const commit = defineWorkspaceOperation({
|
|
1176
|
+
cli: {
|
|
1177
|
+
command: "commit",
|
|
1178
|
+
namespace: "workspace",
|
|
1179
|
+
positional: ["workspace"]
|
|
1180
|
+
},
|
|
1181
|
+
description: "Commit files to a ref when its head is still `ifHead`, else fail with WORKSPACE_CONFLICT. `put` writes files and `delete` removes paths; other files keep their content. A replaced file keeps its media type and metadata. The revision records the signed-in user as its author. Workspace write rules and validators run, and a file that someone else holds an edit lease on fails the commit unless lease is override. `vitehub push` calls it.",
|
|
1182
|
+
input: v.object({
|
|
1183
|
+
delete: v.optional(v.array(nonEmpty("A path cannot be empty."))),
|
|
1184
|
+
ifHead: v.nullable(nonEmpty("The head cannot be empty.")),
|
|
1185
|
+
lease: v.optional(v.literal("override")),
|
|
1186
|
+
message: v.optional(v.string()),
|
|
1187
|
+
put: v.optional(v.record(nonEmpty("A path cannot be empty."), encodedFile)),
|
|
1188
|
+
ref: v.optional(nonEmpty("The ref cannot be empty.")),
|
|
1189
|
+
workspace: name
|
|
1190
|
+
}),
|
|
1191
|
+
maxRequestBytes: workspaceCommitRequestBytes,
|
|
1192
|
+
name: "workspace.commit",
|
|
1193
|
+
run: async (input, context) => await (await runtime()).runWorkspaceCommit(input, context)
|
|
1194
|
+
}, "write");
|
|
1195
|
+
function formatStale(result) {
|
|
1196
|
+
if (!result.head) return `Ref ${result.ref} has no revisions.\n`;
|
|
1197
|
+
if (!result.stale.length) return `No stale derived files on ${result.ref}.\n`;
|
|
1198
|
+
return `${table([[
|
|
1199
|
+
"PATH",
|
|
1200
|
+
"SOURCE",
|
|
1201
|
+
"REASON",
|
|
1202
|
+
"SOURCE DIGEST"
|
|
1203
|
+
], ...result.stale.map((file) => [
|
|
1204
|
+
file.path,
|
|
1205
|
+
file.derivedFrom.path,
|
|
1206
|
+
file.reason,
|
|
1207
|
+
file.sourceDigest ?? "-"
|
|
1208
|
+
])])}\nWrite SOURCE DIGEST as derivedFrom.digest after you update a file.\n`;
|
|
1209
|
+
}
|
|
1210
|
+
/** The `workspace.*` operations: history, refs, show, changes, commit, and stale. The Console, `vitehub workspace`, and agents run them. */
|
|
1211
|
+
const workspaceOperations = [
|
|
1212
|
+
history,
|
|
1213
|
+
refs,
|
|
1214
|
+
show,
|
|
1215
|
+
changes,
|
|
1216
|
+
commit,
|
|
1217
|
+
defineWorkspaceOperation({
|
|
1218
|
+
cli: {
|
|
1219
|
+
command: "stale",
|
|
1220
|
+
format: formatStale,
|
|
1221
|
+
namespace: "workspace",
|
|
1222
|
+
positional: ["workspace"]
|
|
1223
|
+
},
|
|
1224
|
+
description: "List the derived files on a ref, such as translations, whose `derivedFrom` source changed or is gone. Each changed entry has `sourceDigest`: write it as `derivedFrom.digest` after you update the file.",
|
|
1225
|
+
input: v.object({
|
|
1226
|
+
ref: v.optional(nonEmpty("The ref cannot be empty.")),
|
|
1227
|
+
workspace: name
|
|
1228
|
+
}),
|
|
1229
|
+
name: "workspace.stale",
|
|
1230
|
+
run: async (input) => await (await runtime()).runWorkspaceStale(input)
|
|
1231
|
+
})
|
|
1232
|
+
];
|
|
1233
|
+
//#endregion
|
|
1234
|
+
export { isServerEnvironment as _, readViteHubDevTargetOption as a, resolveViteHubProjectRoot as b, relativeDefinitionFile as c, relative$1 as d, resolve$1 as f, generatedViteHubWatchIgnoredAddition as g, createViteHubEnvImportAliases as h, fetchViteHubDevEndpoint as i, dirname$1 as l, createNoExternalAddition as m, callOperationFromCli as n, resolveViteHubDevServerUrl as o, VITEHUB_SERVER_DIRS as p, discoverViteHubDevServer as r, redactInspectionText as s, workspaceOperations as t, isAbsolute$1 as u, loadNativePackageModule as v, shouldSkipViteProviderBuild as x, loadsViteHubPackagesNatively as y };
|