@vite-hub/source 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 +83 -49
- package/dist/client.d.ts +1 -1
- package/dist/client.js +30 -4
- package/dist/{collection-B_4w_J8h.d.ts → collection-B8sgxw5-.d.ts} +52 -19
- package/dist/collection-C0Rvrx3p.js +297 -0
- package/dist/drizzle.d.ts +11 -4
- package/dist/drizzle.js +6 -8
- package/dist/error-diagnostics-ClQKdi7c.js +194 -0
- package/dist/github-D5S0dEZe.js +1312 -0
- package/dist/{glob-BmFqTvJY.js → glob-DmdMVqjx.js} +1 -2
- package/dist/index.d.ts +186 -55
- package/dist/index.js +152 -207
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +25 -140
- package/dist/object-CtSHeGQO.js +17 -0
- package/dist/{path-BS8rYm0n.js → path-DFlSryRA.js} +32 -2
- package/dist/root-DJNmqCEW.js +11 -0
- package/dist/server.d.ts +7 -244
- package/dist/server.js +38 -45
- package/dist/{types-BigOktIj.d.ts → types-Ln-FxVFn.d.ts} +6 -1
- package/dist/vite.d.ts +77 -10
- package/dist/vite.js +619 -713
- package/package.json +25 -47
- package/dist/auth-B-tX_rp0.js +0 -1426
- package/dist/client-BwstxtdY.js +0 -8280
- package/dist/collection-cursor-WzV1Jd6v.js +0 -124
- package/dist/error-diagnostics-X0kuFjBT.js +0 -51
- package/dist/file-BX0FSvgE.js +0 -60
- package/dist/file-DadN9dbN.d.ts +0 -19
- package/dist/file.d.ts +0 -2
- package/dist/file.js +0 -2
- package/dist/files.d.ts +0 -15
- package/dist/files.js +0 -38
- package/dist/github.d.ts +0 -20
- package/dist/github.js +0 -1332
- package/dist/glob.d.ts +0 -23
- package/dist/glob.js +0 -2
- package/dist/markdown.d.ts +0 -5
- package/dist/markdown.js +0 -10
- package/dist/mrmime-40h5OOIp.js +0 -448
- package/dist/path-DOBpV8ol.js +0 -32
- package/dist/sse-D9gqqNPj.js +0 -448
- package/dist/streamableHttp-BL-E7pl5.js +0 -509
- package/dist/types-CoWcW8oz.js +0 -7590
- package/tsconfig.vite.json +0 -6
- package/types/source/fallback.d.ts +0 -1
- package/types/source/index.d.ts +0 -1
|
@@ -0,0 +1,1312 @@
|
|
|
1
|
+
import { a as normalizeSafeSourcePath, n as matchesAny, o as normalizeSourcePath, s as sourceError } from "./path-DFlSryRA.js";
|
|
2
|
+
import { t as sourceErrorDiagnostics } from "./error-diagnostics-ClQKdi7c.js";
|
|
3
|
+
import { n as isRecord } from "./object-CtSHeGQO.js";
|
|
4
|
+
import { t as normalizeGitHubRoot } from "./root-DJNmqCEW.js";
|
|
5
|
+
import { n as invariantError } from "./invariant-DolT9EEx.js";
|
|
6
|
+
import { defineDiagnostics } from "nostics";
|
|
7
|
+
import { devNull } from "node:os";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { gunzipSync } from "node:zlib";
|
|
10
|
+
import { defineCachedFunction } from "ocache";
|
|
11
|
+
import { Buffer } from "node:buffer";
|
|
12
|
+
//#region src/sources/github/archive.ts
|
|
13
|
+
function parseGitHubArchive(bytes) {
|
|
14
|
+
const tar = gunzipSync(bytes);
|
|
15
|
+
const files = [];
|
|
16
|
+
let offset = 0;
|
|
17
|
+
let paxPath;
|
|
18
|
+
while (offset + 512 <= tar.length) {
|
|
19
|
+
const header = tar.subarray(offset, offset + 512);
|
|
20
|
+
if (header.every((byte) => byte === 0)) break;
|
|
21
|
+
const name = readTarString(header, 0, 100);
|
|
22
|
+
const prefix = readTarString(header, 345, 155);
|
|
23
|
+
const path = paxPath || [prefix, name].filter(Boolean).join("/");
|
|
24
|
+
const sizeField = readTarString(header, 124, 12).trim();
|
|
25
|
+
if (sizeField && !/^[0-7]+$/.test(sizeField)) throw sourceErrorDiagnostics.SOURCE_GITHUB_ARCHIVE_INVALID();
|
|
26
|
+
const size = sizeField ? Number.parseInt(sizeField, 8) : 0;
|
|
27
|
+
if (!Number.isSafeInteger(size) || size < 0) throw sourceErrorDiagnostics.SOURCE_GITHUB_ARCHIVE_INVALID();
|
|
28
|
+
const type = String.fromCharCode(header[156] || 0);
|
|
29
|
+
const contentStart = offset + 512;
|
|
30
|
+
const contentEnd = contentStart + size;
|
|
31
|
+
const entryEnd = contentStart + Math.ceil(size / 512) * 512;
|
|
32
|
+
if (entryEnd > tar.length) throw sourceErrorDiagnostics.SOURCE_GITHUB_ARCHIVE_INVALID();
|
|
33
|
+
const content = tar.subarray(contentStart, contentEnd);
|
|
34
|
+
if (type === "x") paxPath = readPaxPath(content);
|
|
35
|
+
else {
|
|
36
|
+
if (type === "0" || type === "\0") {
|
|
37
|
+
const entryPath = stripArchiveRoot(path);
|
|
38
|
+
if (entryPath) files.push({
|
|
39
|
+
content: new Uint8Array(content),
|
|
40
|
+
path: entryPath
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
paxPath = void 0;
|
|
44
|
+
}
|
|
45
|
+
offset = entryEnd;
|
|
46
|
+
}
|
|
47
|
+
return files;
|
|
48
|
+
}
|
|
49
|
+
function readTarString(buffer, offset, length) {
|
|
50
|
+
const slice = buffer.subarray(offset, offset + length);
|
|
51
|
+
const end = slice.indexOf(0);
|
|
52
|
+
return Buffer.from(end === -1 ? slice : slice.subarray(0, end)).toString("utf8");
|
|
53
|
+
}
|
|
54
|
+
function readPaxPath(content) {
|
|
55
|
+
let index = 0;
|
|
56
|
+
while (index < content.length) {
|
|
57
|
+
let space = index;
|
|
58
|
+
while (space < content.length && content[space] !== 32) space++;
|
|
59
|
+
if (space >= content.length) return;
|
|
60
|
+
const length = Number.parseInt(Buffer.from(content.subarray(index, space)).toString("ascii"), 10);
|
|
61
|
+
if (!Number.isFinite(length) || length <= 0 || index + length > content.length) return;
|
|
62
|
+
const record = content.subarray(space + 1, index + length - 1);
|
|
63
|
+
const equals = record.indexOf(61);
|
|
64
|
+
if (equals !== -1 && Buffer.from(record.subarray(0, equals)).toString("utf8") === "path") return Buffer.from(record.subarray(equals + 1)).toString("utf8");
|
|
65
|
+
index += length;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function stripArchiveRoot(path) {
|
|
69
|
+
try {
|
|
70
|
+
normalizeSafeSourcePath(path);
|
|
71
|
+
const slash = path.indexOf("/");
|
|
72
|
+
if (slash === -1) return;
|
|
73
|
+
return normalizeSafeSourcePath(path.slice(slash + 1));
|
|
74
|
+
} catch {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/sources/github/cache.ts
|
|
80
|
+
function normalizeGitHubCache(options) {
|
|
81
|
+
if (options.cache === false) return;
|
|
82
|
+
if (options.cache && typeof options.cache === "object") return { maxAge: options.cache.maxAge };
|
|
83
|
+
}
|
|
84
|
+
function createGitHubCacheKey(input) {
|
|
85
|
+
return JSON.stringify([
|
|
86
|
+
input.kind,
|
|
87
|
+
input.repo,
|
|
88
|
+
input.ref,
|
|
89
|
+
input.root,
|
|
90
|
+
input.include ?? null,
|
|
91
|
+
input.ignore ?? null,
|
|
92
|
+
input.authScope,
|
|
93
|
+
input.key || ""
|
|
94
|
+
]);
|
|
95
|
+
}
|
|
96
|
+
function githubAuthenticationScope(token) {
|
|
97
|
+
return token ? createHash("sha256").update(token).digest("hex") : "anonymous";
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region ../internal/src/error-diagnostics.ts
|
|
101
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
102
|
+
const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
103
|
+
docsBase: "https://vitehub.dev/docs/development/diagnostics",
|
|
104
|
+
codes: {
|
|
105
|
+
INTERNAL_R0012: {
|
|
106
|
+
...dynamicError,
|
|
107
|
+
fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
|
|
108
|
+
},
|
|
109
|
+
INTERNAL_R0013: {
|
|
110
|
+
...dynamicError,
|
|
111
|
+
fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
|
|
112
|
+
},
|
|
113
|
+
INTERNAL_R0014: {
|
|
114
|
+
why: ({ path }) => `Cannot read Provision State from "${path}".`,
|
|
115
|
+
fix: "Check file access and restore valid JSON while preserving existing resource IDs."
|
|
116
|
+
},
|
|
117
|
+
INTERNAL_R0020: {
|
|
118
|
+
fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
|
|
119
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
120
|
+
},
|
|
121
|
+
INTERNAL_R0021: {
|
|
122
|
+
fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
|
|
123
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
124
|
+
},
|
|
125
|
+
INTERNAL_R0022: {
|
|
126
|
+
fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
|
|
127
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
128
|
+
},
|
|
129
|
+
INTERNAL_R0024: {
|
|
130
|
+
fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
|
|
131
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
132
|
+
},
|
|
133
|
+
INTERNAL_R0023: {
|
|
134
|
+
fix: "Ask for access to the section of this operation.",
|
|
135
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
136
|
+
},
|
|
137
|
+
INTERNAL_B0001: {
|
|
138
|
+
...dynamicError,
|
|
139
|
+
fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
|
|
140
|
+
},
|
|
141
|
+
INTERNAL_B0015: {
|
|
142
|
+
...dynamicError,
|
|
143
|
+
fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
|
|
144
|
+
},
|
|
145
|
+
INTERNAL_B0016: {
|
|
146
|
+
...dynamicError,
|
|
147
|
+
fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
|
|
148
|
+
},
|
|
149
|
+
INTERNAL_B0017: {
|
|
150
|
+
...dynamicError,
|
|
151
|
+
fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
|
|
152
|
+
},
|
|
153
|
+
INTERNAL_B0018: {
|
|
154
|
+
...dynamicError,
|
|
155
|
+
fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
|
|
156
|
+
},
|
|
157
|
+
INTERNAL_B0019: {
|
|
158
|
+
...dynamicError,
|
|
159
|
+
fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
|
|
160
|
+
},
|
|
161
|
+
INTERNAL_B0020: {
|
|
162
|
+
...dynamicError,
|
|
163
|
+
fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
|
|
164
|
+
},
|
|
165
|
+
INTERNAL_B0021: {
|
|
166
|
+
...dynamicError,
|
|
167
|
+
fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
|
|
168
|
+
},
|
|
169
|
+
INTERNAL_B0022: {
|
|
170
|
+
...dynamicError,
|
|
171
|
+
fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
|
|
172
|
+
},
|
|
173
|
+
INTERNAL_B0025: {
|
|
174
|
+
...dynamicError,
|
|
175
|
+
fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
|
|
176
|
+
},
|
|
177
|
+
INTERNAL_B0026: {
|
|
178
|
+
...dynamicError,
|
|
179
|
+
fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
|
|
180
|
+
},
|
|
181
|
+
INTERNAL_B0027: {
|
|
182
|
+
...dynamicError,
|
|
183
|
+
fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
|
|
184
|
+
},
|
|
185
|
+
INTERNAL_B0028: {
|
|
186
|
+
...dynamicError,
|
|
187
|
+
fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
|
|
188
|
+
},
|
|
189
|
+
INTERNAL_B0029: {
|
|
190
|
+
...dynamicError,
|
|
191
|
+
fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
|
|
192
|
+
},
|
|
193
|
+
INTERNAL_B0031: {
|
|
194
|
+
...dynamicError,
|
|
195
|
+
fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
|
|
196
|
+
},
|
|
197
|
+
INTERNAL_B0032: {
|
|
198
|
+
...dynamicError,
|
|
199
|
+
fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
|
|
200
|
+
},
|
|
201
|
+
INTERNAL_B0035: {
|
|
202
|
+
...dynamicError,
|
|
203
|
+
fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
|
|
204
|
+
},
|
|
205
|
+
INTERNAL_B0039: {
|
|
206
|
+
...dynamicError,
|
|
207
|
+
fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
|
|
208
|
+
},
|
|
209
|
+
INTERNAL_B0040: {
|
|
210
|
+
...dynamicError,
|
|
211
|
+
fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
|
|
212
|
+
},
|
|
213
|
+
INTERNAL_B0043: {
|
|
214
|
+
...dynamicError,
|
|
215
|
+
fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
|
|
216
|
+
},
|
|
217
|
+
INTERNAL_B0046: {
|
|
218
|
+
...dynamicError,
|
|
219
|
+
fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
|
|
220
|
+
},
|
|
221
|
+
INTERNAL_B0047: {
|
|
222
|
+
...dynamicError,
|
|
223
|
+
fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
|
|
224
|
+
},
|
|
225
|
+
INTERNAL_B0048: {
|
|
226
|
+
fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
|
|
227
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
228
|
+
},
|
|
229
|
+
INTERNAL_B0049: {
|
|
230
|
+
fix: "Set `cli: { namespace, command }` on one of the two operations.",
|
|
231
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
232
|
+
},
|
|
233
|
+
INTERNAL_B0050: {
|
|
234
|
+
fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
|
|
235
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
236
|
+
},
|
|
237
|
+
INTERNAL_B0051: {
|
|
238
|
+
why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
|
|
239
|
+
fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
|
|
240
|
+
},
|
|
241
|
+
INTERNAL_B0052: {
|
|
242
|
+
why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
|
|
243
|
+
fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
|
|
244
|
+
},
|
|
245
|
+
INTERNAL_R0025: {
|
|
246
|
+
fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
|
|
247
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
248
|
+
},
|
|
249
|
+
INTERNAL_R0026: {
|
|
250
|
+
why: "The server parsed a destructive operation that the CLI did not confirm.",
|
|
251
|
+
fix: "Review the operation, then run it again with --yes to confirm the change."
|
|
252
|
+
},
|
|
253
|
+
INTERNAL_C0001: {
|
|
254
|
+
...dynamicError,
|
|
255
|
+
fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
|
|
256
|
+
},
|
|
257
|
+
INTERNAL_C0002: {
|
|
258
|
+
...dynamicError,
|
|
259
|
+
fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
|
|
260
|
+
},
|
|
261
|
+
INTERNAL_R0001: {
|
|
262
|
+
...dynamicError,
|
|
263
|
+
fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
|
|
264
|
+
},
|
|
265
|
+
INTERNAL_R0002: {
|
|
266
|
+
...dynamicError,
|
|
267
|
+
fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
|
|
268
|
+
},
|
|
269
|
+
INTERNAL_R0004: {
|
|
270
|
+
...dynamicError,
|
|
271
|
+
fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
|
|
272
|
+
},
|
|
273
|
+
INTERNAL_R0005: {
|
|
274
|
+
...dynamicError,
|
|
275
|
+
fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
|
|
276
|
+
},
|
|
277
|
+
INTERNAL_R0006: {
|
|
278
|
+
...dynamicError,
|
|
279
|
+
fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
|
|
280
|
+
},
|
|
281
|
+
INTERNAL_R0007: {
|
|
282
|
+
...dynamicError,
|
|
283
|
+
fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
|
|
284
|
+
},
|
|
285
|
+
INTERNAL_R0008: {
|
|
286
|
+
...dynamicError,
|
|
287
|
+
fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
|
|
288
|
+
},
|
|
289
|
+
INTERNAL_R0009: {
|
|
290
|
+
...dynamicError,
|
|
291
|
+
fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
|
|
292
|
+
},
|
|
293
|
+
INTERNAL_R0010: {
|
|
294
|
+
...dynamicError,
|
|
295
|
+
fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
|
|
296
|
+
},
|
|
297
|
+
INTERNAL_R0011: {
|
|
298
|
+
...dynamicError,
|
|
299
|
+
fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
|
|
300
|
+
},
|
|
301
|
+
INTERNAL_CONSOLE_KEY_NAME_INVALID: {
|
|
302
|
+
why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
|
|
303
|
+
fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
|
|
304
|
+
},
|
|
305
|
+
INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
|
|
306
|
+
why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
|
|
307
|
+
fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
|
|
308
|
+
},
|
|
309
|
+
INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
|
|
310
|
+
why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
|
|
311
|
+
fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
|
|
312
|
+
},
|
|
313
|
+
INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
|
|
314
|
+
why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
|
|
315
|
+
fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
|
|
316
|
+
},
|
|
317
|
+
INTERNAL_FORGE_NOT_INSTALLED: {
|
|
318
|
+
why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
|
|
319
|
+
fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
|
|
320
|
+
},
|
|
321
|
+
INTERNAL_MCP_ARGUMENTS_INVALID: {
|
|
322
|
+
why: ({ detail }) => detail,
|
|
323
|
+
fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
|
|
324
|
+
},
|
|
325
|
+
INTERNAL_MCP_METHOD_FAILED: {
|
|
326
|
+
why: ({ name }) => `${name} failed on the server.`,
|
|
327
|
+
fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
|
|
328
|
+
},
|
|
329
|
+
INTERNAL_MCP_RESOURCE_NOT_FOUND: {
|
|
330
|
+
why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
|
|
331
|
+
fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
|
|
332
|
+
},
|
|
333
|
+
INTERNAL_PRESET_OPTION_UNKNOWN: {
|
|
334
|
+
why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
|
|
335
|
+
fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
|
|
336
|
+
},
|
|
337
|
+
INTERNAL_PRESET_TUPLE_INVALID: {
|
|
338
|
+
why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
|
|
339
|
+
fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
|
|
340
|
+
},
|
|
341
|
+
INTERNAL_SECRET_PURPOSE_MISSING: {
|
|
342
|
+
why: "[vitehub] A derived secret requires a purpose.",
|
|
343
|
+
fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
|
|
344
|
+
},
|
|
345
|
+
INTERNAL_SECRET_TOO_SHORT: {
|
|
346
|
+
why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
|
|
347
|
+
fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
|
|
348
|
+
},
|
|
349
|
+
INTERNAL_SQLITE_ARGUMENT_INVALID: {
|
|
350
|
+
why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
|
|
351
|
+
fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
|
|
352
|
+
},
|
|
353
|
+
INTERNAL_SQLITE_INTEGER_UNSAFE: {
|
|
354
|
+
why: "Received integer which cannot be safely represented as a JavaScript number",
|
|
355
|
+
fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
|
|
356
|
+
},
|
|
357
|
+
INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
|
|
358
|
+
why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
|
|
359
|
+
fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
//#endregion
|
|
364
|
+
//#region ../internal/src/forge.ts
|
|
365
|
+
/**
|
|
366
|
+
* Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
|
|
367
|
+
* Channels, Capabilities, Workspaces and Sources read the same names.
|
|
368
|
+
* `FORGES_*` names are the ones that `forgesFromEnv()` in the `forges` library reads.
|
|
369
|
+
* Fields without a `forges` equivalent have only a `VITEHUB_` name.
|
|
370
|
+
*/
|
|
371
|
+
const forgeEnv = {
|
|
372
|
+
github: {
|
|
373
|
+
appId: { names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"] },
|
|
374
|
+
installationId: { names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"] },
|
|
375
|
+
appOwner: { names: ["VITEHUB_GITHUB_APP_OWNER"] },
|
|
376
|
+
appInstallations: { names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"] },
|
|
377
|
+
privateKey: {
|
|
378
|
+
names: ["VITEHUB_GITHUB_PRIVATE_KEY", "FORGES_GITHUB_PRIVATE_KEY"],
|
|
379
|
+
secret: true
|
|
380
|
+
},
|
|
381
|
+
privateKeyPath: { names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"] },
|
|
382
|
+
token: {
|
|
383
|
+
names: ["VITEHUB_GITHUB_TOKEN", "FORGES_GITHUB_TOKEN"],
|
|
384
|
+
secret: true
|
|
385
|
+
},
|
|
386
|
+
webhookSecret: {
|
|
387
|
+
names: ["VITEHUB_GITHUB_WEBHOOK_SECRET", "FORGES_GITHUB_WEBHOOK_SECRET"],
|
|
388
|
+
secret: true
|
|
389
|
+
}
|
|
390
|
+
},
|
|
391
|
+
gitlab: {
|
|
392
|
+
baseUrl: { names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"] },
|
|
393
|
+
token: {
|
|
394
|
+
names: ["VITEHUB_GITLAB_TOKEN", "FORGES_GITLAB_TOKEN"],
|
|
395
|
+
secret: true
|
|
396
|
+
},
|
|
397
|
+
webhookSecret: {
|
|
398
|
+
names: ["VITEHUB_GITLAB_WEBHOOK_SECRET", "FORGES_GITLAB_WEBHOOK_SECRET"],
|
|
399
|
+
secret: true
|
|
400
|
+
}
|
|
401
|
+
},
|
|
402
|
+
forgejo: {
|
|
403
|
+
baseUrl: { names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"] },
|
|
404
|
+
token: {
|
|
405
|
+
names: ["VITEHUB_FORGEJO_TOKEN", "FORGES_FORGEJO_TOKEN"],
|
|
406
|
+
secret: true
|
|
407
|
+
},
|
|
408
|
+
webhookSecret: {
|
|
409
|
+
names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
|
|
410
|
+
secret: true
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
/**
|
|
415
|
+
* The first value of `field` that is set, in its lookup order.
|
|
416
|
+
* `env` is a record, such as `process.env`, or a reader, such as a Cloudflare binding lookup. Default: `process.env`.
|
|
417
|
+
*/
|
|
418
|
+
function readForgeEnv(field, env = globalThis.process?.env ?? {}) {
|
|
419
|
+
for (const name of field.names) {
|
|
420
|
+
const value = typeof env === "function" ? env(name) : env[name];
|
|
421
|
+
if (typeof value !== "string") continue;
|
|
422
|
+
const trimmed = value.trim();
|
|
423
|
+
if (trimmed) return trimmed;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/** The HTTP status of a failed Forge request, or undefined for other errors. */
|
|
427
|
+
function forgeErrorStatus(error) {
|
|
428
|
+
if (!(error instanceof Error) || !("status" in error)) return void 0;
|
|
429
|
+
return typeof error.status === "number" ? error.status : void 0;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* The error for a failed `import("@vite-hub/forge")`, an optional peer of Channels, Workspaces, and Sources. When the
|
|
433
|
+
* app did not install Forge, it is a coded error that names the install command. Otherwise it is the load error itself.
|
|
434
|
+
* `feature` names what needs Forge, such as `A GitHub Workspace`.
|
|
435
|
+
*
|
|
436
|
+
* Call it in the `catch` of a `try` that holds the import itself, in the calling package. esbuild, and so Wrangler and
|
|
437
|
+
* Netlify, then keep an import that does not resolve for run time instead of failing the build.
|
|
438
|
+
*/
|
|
439
|
+
function forgeImportError(error, feature) {
|
|
440
|
+
if (!isMissingForge(error)) return error;
|
|
441
|
+
return internalErrorDiagnostics.INTERNAL_FORGE_NOT_INSTALLED({
|
|
442
|
+
cause: error,
|
|
443
|
+
feature
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
function isMissingForge(error) {
|
|
447
|
+
return error instanceof Error && /(?:cannot find (?:package|module)|no such module|could not resolve) ['"]@vite-hub\/forge['"]/i.test(error.message);
|
|
448
|
+
}
|
|
449
|
+
//#endregion
|
|
450
|
+
//#region src/sources/github/client.ts
|
|
451
|
+
/** `@vite-hub/forge`, an optional peer. A GitHub Source loads it on its first request. */
|
|
452
|
+
async function loadForge() {
|
|
453
|
+
try {
|
|
454
|
+
return await import("@vite-hub/forge");
|
|
455
|
+
} catch (error) {
|
|
456
|
+
throw forgeImportError(error, "A GitHub Source");
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** GitHub lists at most this many files in a compare response. */
|
|
460
|
+
const compareFileLimit = 300;
|
|
461
|
+
/** GitHub lists at most 3,000 files of a pull request, 100 on each page. */
|
|
462
|
+
const pullFilePages = 30;
|
|
463
|
+
/**
|
|
464
|
+
* `changedPaths()` reads the files of each commit between the two commits, up to this many commits. More commits read
|
|
465
|
+
* every page again.
|
|
466
|
+
*/
|
|
467
|
+
const compareCommitLimit = 20;
|
|
468
|
+
/** Commit requests of `changedPaths()` that run at once. */
|
|
469
|
+
const compareCommitConcurrency = 4;
|
|
470
|
+
/** The Server Env token: `VITEHUB_GITHUB_TOKEN`, then `FORGES_GITHUB_TOKEN`. */
|
|
471
|
+
function githubEnvToken() {
|
|
472
|
+
return readForgeEnv(forgeEnv.github.token);
|
|
473
|
+
}
|
|
474
|
+
/** The HTTP status of the Forge request behind a GitHub Source error. */
|
|
475
|
+
function githubErrorStatus(error) {
|
|
476
|
+
return error instanceof Error ? forgeErrorStatus(error.cause) : void 0;
|
|
477
|
+
}
|
|
478
|
+
function isNonEmptyString(value) {
|
|
479
|
+
return typeof value === "string" && value.length > 0;
|
|
480
|
+
}
|
|
481
|
+
function fileCommit(repo, item) {
|
|
482
|
+
const commit = isRecord(item) ? item.commit : void 0;
|
|
483
|
+
const author = isRecord(commit) ? commit.author : void 0;
|
|
484
|
+
const login = isRecord(item) && isRecord(item.author) ? item.author.login : void 0;
|
|
485
|
+
const name = isRecord(author) ? author.name : void 0;
|
|
486
|
+
const date = isRecord(author) ? author.date : void 0;
|
|
487
|
+
const message = isRecord(commit) ? commit.message : void 0;
|
|
488
|
+
if (!isRecord(item) || !isNonEmptyString(item.sha) || !isNonEmptyString(item.html_url) || !isNonEmptyString(date) || typeof message !== "string") throw malformed(repo, "commits");
|
|
489
|
+
return {
|
|
490
|
+
sha: item.sha,
|
|
491
|
+
date: new Date(date).toISOString(),
|
|
492
|
+
author: isNonEmptyString(login) ? login : isNonEmptyString(name) ? name : null,
|
|
493
|
+
message: message.split("\n", 1)[0].trim(),
|
|
494
|
+
url: item.html_url
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
/** Undefined when GitHub answers that the ref does not exist: 404, or 422 for an unknown commit SHA. */
|
|
498
|
+
async function missingAsUndefined(load) {
|
|
499
|
+
try {
|
|
500
|
+
return await load();
|
|
501
|
+
} catch (error) {
|
|
502
|
+
const status = githubErrorStatus(error);
|
|
503
|
+
if (status === 404 || status === 422) return;
|
|
504
|
+
throw error;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
function malformed(repo, description) {
|
|
508
|
+
return sourceError(`[vitehub] github(${JSON.stringify(repo)}) returned a malformed ${description} response.`);
|
|
509
|
+
}
|
|
510
|
+
function createGitHubClient(repo) {
|
|
511
|
+
const [owner, name, ...rest] = repo.split("/");
|
|
512
|
+
let cached;
|
|
513
|
+
function provider(token) {
|
|
514
|
+
if (!cached || cached.token !== token) cached = {
|
|
515
|
+
provider: loadForge().then(async ({ forgeProvider }) => await forgeProvider({
|
|
516
|
+
forge: "github",
|
|
517
|
+
readOnly: true,
|
|
518
|
+
token,
|
|
519
|
+
userAgent: "vitehub-source"
|
|
520
|
+
})),
|
|
521
|
+
token
|
|
522
|
+
};
|
|
523
|
+
return cached.provider;
|
|
524
|
+
}
|
|
525
|
+
async function request(ref, description, token, signal, load) {
|
|
526
|
+
if (!owner || !name || rest.length) throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) supports GitHub.com repositories only and expects repo as "owner/name".`);
|
|
527
|
+
const client = await provider(token);
|
|
528
|
+
try {
|
|
529
|
+
return await load(client, {
|
|
530
|
+
forge: client.forge,
|
|
531
|
+
instance: client.instance,
|
|
532
|
+
name,
|
|
533
|
+
owner
|
|
534
|
+
});
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (signal?.aborted) throw error;
|
|
537
|
+
const status = forgeErrorStatus(error);
|
|
538
|
+
if (status === void 0) throw error;
|
|
539
|
+
if (status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) could not access the repository or ref ${JSON.stringify(ref)}. Check that the repo exists, the ref exists, and auth can access it.`, { cause: error });
|
|
540
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) ${description} request failed with ${status}.`, { cause: error });
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
function repoPath(repoRef) {
|
|
544
|
+
return `/repos/${encodeURIComponent(repoRef.owner)}/${encodeURIComponent(repoRef.name)}`;
|
|
545
|
+
}
|
|
546
|
+
function repoName(value) {
|
|
547
|
+
return isRecord(value) && isNonEmptyString(value.full_name) ? value.full_name : null;
|
|
548
|
+
}
|
|
549
|
+
/** A pull request from `/pulls/<number>` or `/commits/<sha>/pulls`. The list has `merged_at` but no `merged`. */
|
|
550
|
+
function pullRequest(data, number) {
|
|
551
|
+
if (!isRecord(data) || !Number.isSafeInteger(number) || !isRecord(data.head) || !isRecord(data.base) || !isNonEmptyString(data.head.sha) || !isNonEmptyString(data.head.ref) || !isNonEmptyString(data.base.ref)) throw malformed(repo, "pull request");
|
|
552
|
+
const headRepo = repoName(data.head.repo);
|
|
553
|
+
const baseRepo = repoName(data.base.repo) ?? repo;
|
|
554
|
+
const labels = Array.isArray(data.labels) ? data.labels.flatMap((label) => isRecord(label) && isNonEmptyString(label.name) ? [label.name] : []) : [];
|
|
555
|
+
return {
|
|
556
|
+
sha: data.head.sha,
|
|
557
|
+
pull: {
|
|
558
|
+
number,
|
|
559
|
+
state: data.state === "open" ? "open" : "closed",
|
|
560
|
+
merged: data.merged === true || isNonEmptyString(data.merged_at),
|
|
561
|
+
head: data.head.ref,
|
|
562
|
+
headRepo,
|
|
563
|
+
base: data.base.ref,
|
|
564
|
+
fork: headRepo?.toLowerCase() !== baseRepo.toLowerCase(),
|
|
565
|
+
labels
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
async branch(branch, token, signal) {
|
|
571
|
+
const data = await missingAsUndefined(() => request(branch, "branch", token, signal, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/git/ref/heads/${branch.split("/").map(encodeURIComponent).join("/")}`, { signal })).data));
|
|
572
|
+
if (data === void 0) return;
|
|
573
|
+
if (Array.isArray(data)) return;
|
|
574
|
+
if (!isRecord(data) || !isRecord(data.object) || !isNonEmptyString(data.object.sha)) throw malformed(repo, "branch");
|
|
575
|
+
return data.object.sha;
|
|
576
|
+
},
|
|
577
|
+
async commit(sha, token, signal) {
|
|
578
|
+
const data = await missingAsUndefined(() => request(sha, "commit", token, signal, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/commits/${encodeURIComponent(sha)}`, { signal })).data));
|
|
579
|
+
if (data === void 0) return;
|
|
580
|
+
if (!isRecord(data) || !isNonEmptyString(data.sha)) throw malformed(repo, "commit");
|
|
581
|
+
return data.sha;
|
|
582
|
+
},
|
|
583
|
+
async pull(number, token, signal) {
|
|
584
|
+
const data = await missingAsUndefined(() => request(`pull/${number}`, "pull request", token, signal, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/pulls/${number}`, { signal })).data));
|
|
585
|
+
if (data === void 0) return;
|
|
586
|
+
return pullRequest(data, number);
|
|
587
|
+
},
|
|
588
|
+
async compare(base, head, token, signal) {
|
|
589
|
+
const data = await missingAsUndefined(() => request(`${base}...${head}`, "compare", token, signal, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`, { signal })).data));
|
|
590
|
+
if (data === void 0) return;
|
|
591
|
+
if (!isRecord(data) || data.status !== "identical" && data.status !== "behind" && data.status !== "ahead" && data.status !== "diverged") throw malformed(repo, "compare");
|
|
592
|
+
return data.status;
|
|
593
|
+
},
|
|
594
|
+
async commitPulls(sha, token, signal) {
|
|
595
|
+
const data = await missingAsUndefined(() => request(sha, "commit pull requests", token, signal, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/commits/${encodeURIComponent(sha)}/pulls?per_page=100`, { signal })).data));
|
|
596
|
+
if (data === void 0) return [];
|
|
597
|
+
if (!Array.isArray(data)) throw malformed(repo, "commit pull requests");
|
|
598
|
+
return data.map((item) => pullRequest(item, isRecord(item) && typeof item.number === "number" ? item.number : NaN));
|
|
599
|
+
},
|
|
600
|
+
async openPulls(token, signal) {
|
|
601
|
+
const data = await request("open", "pull requests", token, signal, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/pulls?state=open&sort=updated&direction=desc&per_page=100`, { signal })).data);
|
|
602
|
+
if (!Array.isArray(data)) throw malformed(repo, "pull requests");
|
|
603
|
+
return data.map((item) => pullRequest(item, isRecord(item) && typeof item.number === "number" ? item.number : NaN));
|
|
604
|
+
},
|
|
605
|
+
async archive(ref, token, signal) {
|
|
606
|
+
const download = (archiveToken) => request(ref, "archive", archiveToken, signal, async (client, repoRef) => {
|
|
607
|
+
const { forgeArchive } = await loadForge();
|
|
608
|
+
const stream = await forgeArchive(client, repoRef, {
|
|
609
|
+
ref,
|
|
610
|
+
signal
|
|
611
|
+
});
|
|
612
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
613
|
+
});
|
|
614
|
+
try {
|
|
615
|
+
return await download(token);
|
|
616
|
+
} catch (error) {
|
|
617
|
+
const status = githubErrorStatus(error);
|
|
618
|
+
if (!token || status !== 403 && status !== 429) throw error;
|
|
619
|
+
return await download(void 0);
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
async defaultBranch(token, signal) {
|
|
623
|
+
const branch = await request("default", "repository", token, signal, async (client, repoRef) => (await client.repos.get(repoRef, { signal })).defaultBranch);
|
|
624
|
+
if (!branch) throw malformed(repo, "repository");
|
|
625
|
+
return branch;
|
|
626
|
+
},
|
|
627
|
+
async file(path, ref, token, signal) {
|
|
628
|
+
try {
|
|
629
|
+
const file = await request(ref, "content", token, signal, async (client, repoRef) => await client.contents.getFile(repoRef, path, {
|
|
630
|
+
ref,
|
|
631
|
+
signal
|
|
632
|
+
}));
|
|
633
|
+
if (file.encoding !== "binary") throw malformed(repo, "content");
|
|
634
|
+
return {
|
|
635
|
+
content: file.content,
|
|
636
|
+
sha: file.sha
|
|
637
|
+
};
|
|
638
|
+
} catch (error) {
|
|
639
|
+
if (githubErrorStatus(error) !== 422) throw error;
|
|
640
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) expected ${JSON.stringify(path)} to be a file, but GitHub returned a directory or another entry type.`, { cause: error });
|
|
641
|
+
}
|
|
642
|
+
},
|
|
643
|
+
async metadata(path, ref, token, signal) {
|
|
644
|
+
const entry = await request(ref, "content", token, signal, async (client, repoRef) => (await client.request("GET", `/repos/${encodeURIComponent(repoRef.owner)}/${encodeURIComponent(repoRef.name)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, {
|
|
645
|
+
query: { ref },
|
|
646
|
+
signal
|
|
647
|
+
})).data);
|
|
648
|
+
if (Array.isArray(entry)) return;
|
|
649
|
+
if (!isRecord(entry) || !isNonEmptyString(entry.type) || !isNonEmptyString(entry.sha)) throw malformed(repo, "content");
|
|
650
|
+
return entry.type === "file" ? { sha: entry.sha } : void 0;
|
|
651
|
+
},
|
|
652
|
+
async commits(path, { sha, page, perPage }, token) {
|
|
653
|
+
const response = await request(sha, "commits", token, void 0, async (client, repoRef) => await client.request("GET", `/repos/${encodeURIComponent(repoRef.owner)}/${encodeURIComponent(repoRef.name)}/commits`, { query: {
|
|
654
|
+
path,
|
|
655
|
+
sha,
|
|
656
|
+
page,
|
|
657
|
+
per_page: perPage
|
|
658
|
+
} }));
|
|
659
|
+
if (!Array.isArray(response.data)) throw malformed(repo, "commits");
|
|
660
|
+
return {
|
|
661
|
+
commits: response.data.map((item) => fileCommit(repo, item)),
|
|
662
|
+
more: /rel="next"/.test(response.headers.get("link") ?? "")
|
|
663
|
+
};
|
|
664
|
+
},
|
|
665
|
+
async latestCommits(paths, sha, token) {
|
|
666
|
+
const fields = "oid authoredDate message url author { name user { login } }";
|
|
667
|
+
const query = [
|
|
668
|
+
`query FileHistory($owner: String!, $name: String!, $sha: GitObjectID!${paths.map((_, index) => `, $p${index}: String!`).join("")}) {`,
|
|
669
|
+
" repository(owner: $owner, name: $name) { object(oid: $sha) { ... on Commit {",
|
|
670
|
+
...paths.map((_, index) => ` p${index}: history(first: 1, path: $p${index}) { nodes { ${fields} } }`),
|
|
671
|
+
" } } }",
|
|
672
|
+
"}"
|
|
673
|
+
].join("\n");
|
|
674
|
+
const data = await request(sha, "file history", token, void 0, async (client, repoRef) => (await client.request("POST", "/graphql", {
|
|
675
|
+
body: {
|
|
676
|
+
query,
|
|
677
|
+
operationName: "FileHistory",
|
|
678
|
+
variables: {
|
|
679
|
+
owner: repoRef.owner,
|
|
680
|
+
name: repoRef.name,
|
|
681
|
+
sha,
|
|
682
|
+
...Object.fromEntries(paths.map((path, index) => [`p${index}`, path]))
|
|
683
|
+
}
|
|
684
|
+
},
|
|
685
|
+
mutates: false
|
|
686
|
+
})).data);
|
|
687
|
+
if (!isRecord(data) || Array.isArray(data.errors) && data.errors.length) {
|
|
688
|
+
const message = isRecord(data) && Array.isArray(data.errors) && isRecord(data.errors[0]) ? data.errors[0].message : void 0;
|
|
689
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) file history request failed${typeof message === "string" ? `: ${message}` : "."}`);
|
|
690
|
+
}
|
|
691
|
+
const commit = isRecord(data.data) && isRecord(data.data.repository) ? data.data.repository.object : void 0;
|
|
692
|
+
if (!isRecord(commit)) throw malformed(repo, "file history");
|
|
693
|
+
return paths.map((_, index) => {
|
|
694
|
+
const history = commit[`p${index}`];
|
|
695
|
+
const node = isRecord(history) && Array.isArray(history.nodes) ? history.nodes[0] : void 0;
|
|
696
|
+
if (!isRecord(history) || !Array.isArray(history.nodes)) throw malformed(repo, "file history");
|
|
697
|
+
if (node === void 0) return null;
|
|
698
|
+
const author = isRecord(node) ? node.author : void 0;
|
|
699
|
+
const login = isRecord(author) && isRecord(author.user) ? author.user.login : void 0;
|
|
700
|
+
const name = isRecord(author) ? author.name : void 0;
|
|
701
|
+
if (!isRecord(node) || !isNonEmptyString(node.oid) || !isNonEmptyString(node.authoredDate) || !isNonEmptyString(node.url) || typeof node.message !== "string") throw malformed(repo, "file history");
|
|
702
|
+
return {
|
|
703
|
+
sha: node.oid,
|
|
704
|
+
date: new Date(node.authoredDate).toISOString(),
|
|
705
|
+
author: isNonEmptyString(login) ? login : isNonEmptyString(name) ? name : null,
|
|
706
|
+
message: node.message.split("\n", 1)[0].trim(),
|
|
707
|
+
url: node.url
|
|
708
|
+
};
|
|
709
|
+
});
|
|
710
|
+
},
|
|
711
|
+
async changedPaths(base, head, token) {
|
|
712
|
+
const data = await missingAsUndefined(() => request(`${base}...${head}`, "compare", token, void 0, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`, { query: { per_page: compareCommitLimit } })).data));
|
|
713
|
+
if (data === void 0) return;
|
|
714
|
+
if (!isRecord(data) || typeof data.status !== "string") throw malformed(repo, "compare");
|
|
715
|
+
if (data.status !== "ahead" && data.status !== "identical") return;
|
|
716
|
+
const paths = (files, what) => {
|
|
717
|
+
if (!Array.isArray(files)) throw malformed(repo, what);
|
|
718
|
+
if (files.length >= compareFileLimit) return;
|
|
719
|
+
return files.flatMap((file) => {
|
|
720
|
+
if (!isRecord(file) || !isNonEmptyString(file.filename)) throw malformed(repo, what);
|
|
721
|
+
return isNonEmptyString(file.previous_filename) ? [file.filename, file.previous_filename] : [file.filename];
|
|
722
|
+
});
|
|
723
|
+
};
|
|
724
|
+
const changed = paths(data.files ?? [], "compare");
|
|
725
|
+
if (!changed) return;
|
|
726
|
+
const commits = data.commits ?? [];
|
|
727
|
+
const total = data.total_commits ?? 0;
|
|
728
|
+
if (!Array.isArray(commits) || typeof total !== "number") throw malformed(repo, "compare");
|
|
729
|
+
if (total <= 1) return changed;
|
|
730
|
+
if (total > compareCommitLimit || commits.length < total) return;
|
|
731
|
+
const touched = new Set(changed);
|
|
732
|
+
for (let start = 0; start < commits.length; start += compareCommitConcurrency) {
|
|
733
|
+
const lists = await Promise.all(commits.slice(start, start + compareCommitConcurrency).map(async (commit) => {
|
|
734
|
+
if (!isRecord(commit) || !isNonEmptyString(commit.sha)) throw malformed(repo, "compare");
|
|
735
|
+
const sha = commit.sha;
|
|
736
|
+
const detail = await request(sha, "commit", token, void 0, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/commits/${encodeURIComponent(sha)}`, { query: { per_page: compareFileLimit } })).data);
|
|
737
|
+
if (!isRecord(detail)) throw malformed(repo, "commit");
|
|
738
|
+
return paths(detail.files ?? [], "commit");
|
|
739
|
+
}));
|
|
740
|
+
for (const list of lists) {
|
|
741
|
+
if (!list) return;
|
|
742
|
+
for (const path of list) touched.add(path);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
return [...touched];
|
|
746
|
+
},
|
|
747
|
+
async pullPaths(number, token) {
|
|
748
|
+
const paths = [];
|
|
749
|
+
for (let page = 1; page <= pullFilePages; page++) {
|
|
750
|
+
const data = await missingAsUndefined(() => request(`pull/${number}`, "pull request files", token, void 0, async (client, repoRef) => (await client.request("GET", `${repoPath(repoRef)}/pulls/${number}/files`, { query: {
|
|
751
|
+
per_page: 100,
|
|
752
|
+
page
|
|
753
|
+
} })).data));
|
|
754
|
+
if (data === void 0) return;
|
|
755
|
+
if (!Array.isArray(data)) throw malformed(repo, "pull request files");
|
|
756
|
+
for (const file of data) {
|
|
757
|
+
if (!isRecord(file) || !isNonEmptyString(file.filename) || !isNonEmptyString(file.status)) throw malformed(repo, "pull request files");
|
|
758
|
+
if (file.status !== "removed") paths.push(file.filename);
|
|
759
|
+
}
|
|
760
|
+
if (data.length < 100) break;
|
|
761
|
+
}
|
|
762
|
+
return paths;
|
|
763
|
+
},
|
|
764
|
+
async resolveCommit(ref, token, signal) {
|
|
765
|
+
const sha = await request(ref, "commit", token, signal, async (client, repoRef) => await client.contents.resolveRef(repoRef, ref, { signal }));
|
|
766
|
+
if (typeof sha !== "string" || !sha) throw malformed(repo, "commit");
|
|
767
|
+
return sha;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
//#endregion
|
|
772
|
+
//#region src/sources/github/git.ts
|
|
773
|
+
function createGitEnv(home, authHeader, baseEnv = process.env) {
|
|
774
|
+
const env = { ...baseEnv };
|
|
775
|
+
for (const key of [
|
|
776
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
777
|
+
"GIT_COMMON_DIR",
|
|
778
|
+
"GIT_CONFIG",
|
|
779
|
+
"GIT_CONFIG_COUNT",
|
|
780
|
+
"GIT_CONFIG_PARAMETERS",
|
|
781
|
+
"GIT_DIR",
|
|
782
|
+
"GIT_GRAFT_FILE",
|
|
783
|
+
"GIT_IMPLICIT_WORK_TREE",
|
|
784
|
+
"GIT_INDEX_FILE",
|
|
785
|
+
"GIT_NO_REPLACE_OBJECTS",
|
|
786
|
+
"GIT_OBJECT_DIRECTORY",
|
|
787
|
+
"GIT_PREFIX",
|
|
788
|
+
"GIT_REPLACE_REF_BASE",
|
|
789
|
+
"GIT_SHALLOW_FILE",
|
|
790
|
+
"GIT_WORK_TREE"
|
|
791
|
+
]) delete env[key];
|
|
792
|
+
for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(key)) delete env[key];
|
|
793
|
+
Object.assign(env, {
|
|
794
|
+
GCM_INTERACTIVE: "Never",
|
|
795
|
+
GIT_ASKPASS: "",
|
|
796
|
+
GIT_CONFIG_COUNT: authHeader ? "1" : "0",
|
|
797
|
+
GIT_CONFIG_GLOBAL: devNull,
|
|
798
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
799
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
800
|
+
HOME: home,
|
|
801
|
+
SSH_ASKPASS: "",
|
|
802
|
+
USERPROFILE: home,
|
|
803
|
+
XDG_CONFIG_HOME: home
|
|
804
|
+
});
|
|
805
|
+
if (!authHeader) return env;
|
|
806
|
+
env.GIT_CONFIG_KEY_0 = authHeader.key;
|
|
807
|
+
env.GIT_CONFIG_VALUE_0 = authHeader.value;
|
|
808
|
+
return env;
|
|
809
|
+
}
|
|
810
|
+
async function runGit(args, options = {}) {
|
|
811
|
+
const { spawn } = await import("node:child_process");
|
|
812
|
+
return await new Promise((resolve, reject) => {
|
|
813
|
+
const child = spawn("git", args, {
|
|
814
|
+
env: options.env,
|
|
815
|
+
signal: options.signal,
|
|
816
|
+
stdio: [
|
|
817
|
+
"pipe",
|
|
818
|
+
"pipe",
|
|
819
|
+
"pipe"
|
|
820
|
+
]
|
|
821
|
+
});
|
|
822
|
+
const stdout = [];
|
|
823
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
824
|
+
child.stderr.resume();
|
|
825
|
+
child.stdin.on("error", () => {});
|
|
826
|
+
child.stdin.end();
|
|
827
|
+
child.on("error", reject);
|
|
828
|
+
child.on("close", (code) => {
|
|
829
|
+
if (code === 0) {
|
|
830
|
+
resolve(Buffer.concat(stdout));
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const command = args[0] === "-C" ? args[2] : args[0];
|
|
834
|
+
reject(invariantError(`github() reads the GitHub archive when git fails, and git ${command || "command"} exited with ${code ?? "an unknown status"}`));
|
|
835
|
+
});
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
function isGitSparsePattern(pattern) {
|
|
839
|
+
if (pattern.includes("\0") || pattern.includes("\r") || pattern.includes("\n")) return false;
|
|
840
|
+
if (pattern.split("/").some((segment) => segment === "." || segment === "..")) return false;
|
|
841
|
+
if (!pattern.includes("*")) return !/[?[\]{}()!+@]/.test(pattern);
|
|
842
|
+
if (!pattern.endsWith("/**")) return false;
|
|
843
|
+
return !/[*?[\]{}()!+@]/.test(pattern.slice(0, -3));
|
|
844
|
+
}
|
|
845
|
+
function getGitSparsePatterns(root, include) {
|
|
846
|
+
const patterns = (include ? Array.isArray(include) ? include : [include] : []).map((pattern) => [root, normalizeSourcePath(pattern)].filter(Boolean).join("/")).filter(Boolean);
|
|
847
|
+
if (patterns.some((pattern) => !isGitSparsePattern(pattern))) return;
|
|
848
|
+
if (patterns.length) return [...new Set(patterns)];
|
|
849
|
+
return root && isGitSparsePattern(root) ? [`${root}/**`] : void 0;
|
|
850
|
+
}
|
|
851
|
+
function isGitLfsPointer(content) {
|
|
852
|
+
if (content.byteLength > 65536) return false;
|
|
853
|
+
const lines = Buffer.from(content).toString("utf8").split(/\r?\n/);
|
|
854
|
+
return lines[0] === "version https://git-lfs.github.com/spec/v1" && lines.some((line) => /^oid sha256:[0-9a-f]{64}$/.test(line)) && lines.some((line) => /^size \d+$/.test(line));
|
|
855
|
+
}
|
|
856
|
+
async function readGitArchiveFiles(dir, input, executeGit, options) {
|
|
857
|
+
input.signal?.throwIfAborted();
|
|
858
|
+
const archive = await executeGit([
|
|
859
|
+
"-C",
|
|
860
|
+
dir,
|
|
861
|
+
"archive",
|
|
862
|
+
"--format=tar.gz",
|
|
863
|
+
"--prefix=archive/",
|
|
864
|
+
input.sha,
|
|
865
|
+
"--",
|
|
866
|
+
...input.sparsePatterns.map((pattern) => {
|
|
867
|
+
return `:(literal)${pattern.endsWith("/**") ? pattern.slice(0, -3) : pattern}`;
|
|
868
|
+
})
|
|
869
|
+
], options);
|
|
870
|
+
return parseGitHubArchive(Buffer.from(archive)).map((entry) => {
|
|
871
|
+
const key = input.keyForRepoPath(entry.path);
|
|
872
|
+
if (!key || !input.shouldInclude(key)) return;
|
|
873
|
+
if (isGitLfsPointer(entry.content)) throw invariantError("github() reads the GitHub archive when git archive has a Git LFS pointer");
|
|
874
|
+
return {
|
|
875
|
+
content: entry.content,
|
|
876
|
+
key,
|
|
877
|
+
path: key,
|
|
878
|
+
ref: input.ref,
|
|
879
|
+
sha: input.sha
|
|
880
|
+
};
|
|
881
|
+
}).filter((file) => Boolean(file));
|
|
882
|
+
}
|
|
883
|
+
async function loadGitArchiveFiles(input, executeGit = runGit) {
|
|
884
|
+
const [{ mkdtemp, rm }, { tmpdir }, { join }] = await Promise.all([
|
|
885
|
+
import("node:fs/promises"),
|
|
886
|
+
import("node:os"),
|
|
887
|
+
import("node:path")
|
|
888
|
+
]);
|
|
889
|
+
const dir = await mkdtemp(join(tmpdir(), "vitehub-github-"));
|
|
890
|
+
try {
|
|
891
|
+
const options = {
|
|
892
|
+
env: createGitEnv(dir, (await loadForge()).forgeGitAuthHeader(input.credentials), input.env),
|
|
893
|
+
signal: input.signal
|
|
894
|
+
};
|
|
895
|
+
await executeGit([
|
|
896
|
+
"init",
|
|
897
|
+
"--quiet",
|
|
898
|
+
dir
|
|
899
|
+
], options);
|
|
900
|
+
await executeGit([
|
|
901
|
+
"-C",
|
|
902
|
+
dir,
|
|
903
|
+
"remote",
|
|
904
|
+
"add",
|
|
905
|
+
"origin",
|
|
906
|
+
input.credentials.url
|
|
907
|
+
], options);
|
|
908
|
+
await executeGit([
|
|
909
|
+
"-C",
|
|
910
|
+
dir,
|
|
911
|
+
"config",
|
|
912
|
+
"remote.origin.promisor",
|
|
913
|
+
"true"
|
|
914
|
+
], options);
|
|
915
|
+
await executeGit([
|
|
916
|
+
"-C",
|
|
917
|
+
dir,
|
|
918
|
+
"config",
|
|
919
|
+
"remote.origin.partialclonefilter",
|
|
920
|
+
"blob:none"
|
|
921
|
+
], options);
|
|
922
|
+
await executeGit([
|
|
923
|
+
"-C",
|
|
924
|
+
dir,
|
|
925
|
+
"fetch",
|
|
926
|
+
"--depth=1",
|
|
927
|
+
"--filter=blob:none",
|
|
928
|
+
"--no-tags",
|
|
929
|
+
"--",
|
|
930
|
+
"origin",
|
|
931
|
+
`+${input.ref}`
|
|
932
|
+
], options);
|
|
933
|
+
const sha = Buffer.from(await executeGit([
|
|
934
|
+
"-C",
|
|
935
|
+
dir,
|
|
936
|
+
"rev-parse",
|
|
937
|
+
"FETCH_HEAD"
|
|
938
|
+
], options)).toString("utf8").trim();
|
|
939
|
+
return await readGitArchiveFiles(dir, {
|
|
940
|
+
...input,
|
|
941
|
+
sha
|
|
942
|
+
}, executeGit, options);
|
|
943
|
+
} finally {
|
|
944
|
+
await rm(dir, {
|
|
945
|
+
force: true,
|
|
946
|
+
recursive: true
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
//#endregion
|
|
951
|
+
//#region src/sources/github/index.ts
|
|
952
|
+
/** Files per GraphQL request of `latest()`. GitHub answers 150 in about 4 seconds, and stops a request at 10. */
|
|
953
|
+
const historyBatch = 150;
|
|
954
|
+
/** `latest()` splits a request that GitHub stopped down to this many files, then gives up. */
|
|
955
|
+
const historyBatchMin = 20;
|
|
956
|
+
/** GraphQL requests of `latest()` that run at once. */
|
|
957
|
+
const historyConcurrency = 4;
|
|
958
|
+
function dedupeProviderPromise(promises, key, load) {
|
|
959
|
+
const promise = promises.get(key);
|
|
960
|
+
if (promise) return promise;
|
|
961
|
+
const nextPromise = load().finally(() => {
|
|
962
|
+
promises.delete(key);
|
|
963
|
+
});
|
|
964
|
+
promises.set(key, nextPromise);
|
|
965
|
+
return nextPromise;
|
|
966
|
+
}
|
|
967
|
+
async function waitForCachedGitHubResult(load, signal) {
|
|
968
|
+
signal?.throwIfAborted();
|
|
969
|
+
const result = load();
|
|
970
|
+
if (!signal) return await result;
|
|
971
|
+
return await new Promise((resolve, reject) => {
|
|
972
|
+
const abort = () => reject(signal.reason);
|
|
973
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
974
|
+
result.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
function github(options) {
|
|
978
|
+
const configuredRef = options.ref;
|
|
979
|
+
const root = normalizeGitHubRoot(options.root || "");
|
|
980
|
+
const sparsePatterns = getGitSparsePatterns(root, options.include);
|
|
981
|
+
const authByContext = /* @__PURE__ */ new WeakMap();
|
|
982
|
+
const providerCache = normalizeGitHubCache(options);
|
|
983
|
+
const client = createGitHubClient(options.repo);
|
|
984
|
+
async function resolveAuth() {
|
|
985
|
+
if (options.auth === void 0) return githubEnvToken();
|
|
986
|
+
const token = typeof options.auth === "function" ? await options.auth() : options.auth;
|
|
987
|
+
return typeof token === "string" && token.length > 0 ? token : void 0;
|
|
988
|
+
}
|
|
989
|
+
async function contextAuth(ctx) {
|
|
990
|
+
let auth = authByContext.get(ctx);
|
|
991
|
+
if (!auth) {
|
|
992
|
+
auth = resolveAuth();
|
|
993
|
+
authByContext.set(ctx, auth);
|
|
994
|
+
}
|
|
995
|
+
return await auth;
|
|
996
|
+
}
|
|
997
|
+
function keyForRepoPath(path) {
|
|
998
|
+
let normalized;
|
|
999
|
+
try {
|
|
1000
|
+
normalized = normalizeSafeSourcePath(path);
|
|
1001
|
+
} catch {
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
if (!root) return normalized;
|
|
1005
|
+
if (!normalized.startsWith(`${root}/`)) return void 0;
|
|
1006
|
+
const key = normalized.slice(root.length + 1);
|
|
1007
|
+
if (!key || key.startsWith("/")) return void 0;
|
|
1008
|
+
return normalizeSafeSourcePath(key);
|
|
1009
|
+
}
|
|
1010
|
+
function repoPathForKey(key) {
|
|
1011
|
+
const normalized = normalizeSourcePath(key);
|
|
1012
|
+
return root ? `${root}/${normalized}` : normalized;
|
|
1013
|
+
}
|
|
1014
|
+
function shouldInclude(key) {
|
|
1015
|
+
if (options.include && !matchesAny(key, options.include)) return false;
|
|
1016
|
+
if (options.ignore && matchesAny(key, options.ignore)) return false;
|
|
1017
|
+
return true;
|
|
1018
|
+
}
|
|
1019
|
+
async function resolveRef(token) {
|
|
1020
|
+
if (configuredRef) return configuredRef;
|
|
1021
|
+
return (await resolveSourceRevision(token)).id;
|
|
1022
|
+
}
|
|
1023
|
+
async function resolveSourceRevision(token, signal) {
|
|
1024
|
+
if (!configuredRef) try {
|
|
1025
|
+
const ref = await client.defaultBranch(token, signal);
|
|
1026
|
+
return {
|
|
1027
|
+
id: await client.resolveCommit(ref, token, signal),
|
|
1028
|
+
immutable: true,
|
|
1029
|
+
ref
|
|
1030
|
+
};
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
if (shouldResolveMainFallback(error)) return {
|
|
1033
|
+
id: "main",
|
|
1034
|
+
immutable: false,
|
|
1035
|
+
ref: "main"
|
|
1036
|
+
};
|
|
1037
|
+
throw error;
|
|
1038
|
+
}
|
|
1039
|
+
try {
|
|
1040
|
+
return {
|
|
1041
|
+
id: await client.resolveCommit(configuredRef, token, signal),
|
|
1042
|
+
immutable: true,
|
|
1043
|
+
ref: configuredRef
|
|
1044
|
+
};
|
|
1045
|
+
} catch (error) {
|
|
1046
|
+
if (shouldResolveMainFallback(error)) return {
|
|
1047
|
+
id: configuredRef,
|
|
1048
|
+
immutable: false,
|
|
1049
|
+
ref: configuredRef
|
|
1050
|
+
};
|
|
1051
|
+
throw error;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
function shouldResolveMainFallback(error) {
|
|
1055
|
+
const status = githubErrorStatus(error);
|
|
1056
|
+
return status === 403 || status === 429;
|
|
1057
|
+
}
|
|
1058
|
+
const resolvedRefs = /* @__PURE__ */ new Map();
|
|
1059
|
+
const cachedResolveRef = providerCache ? defineCachedFunction(async (token) => await resolveRef(token), {
|
|
1060
|
+
...providerCache,
|
|
1061
|
+
getKey: (token) => cacheKey("ref", token || ""),
|
|
1062
|
+
name: "github-source-ref"
|
|
1063
|
+
}) : (token) => dedupeProviderPromise(resolvedRefs, cacheKey("ref", token || ""), () => resolveRef(token));
|
|
1064
|
+
async function getRef(token, signal) {
|
|
1065
|
+
return await waitForCachedGitHubResult(() => cachedResolveRef(token), signal);
|
|
1066
|
+
}
|
|
1067
|
+
async function validateConfiguredRef(token) {
|
|
1068
|
+
if (!configuredRef) return;
|
|
1069
|
+
await client.resolveCommit(configuredRef, token);
|
|
1070
|
+
}
|
|
1071
|
+
async function loadArchiveFiles(token, resolvedRef) {
|
|
1072
|
+
const ref = resolvedRef ?? await getRef(token);
|
|
1073
|
+
return parseGitHubArchive(await client.archive(ref, token)).map((entry) => {
|
|
1074
|
+
const key = keyForRepoPath(entry.path);
|
|
1075
|
+
if (!key || !shouldInclude(key)) return void 0;
|
|
1076
|
+
return {
|
|
1077
|
+
content: entry.content,
|
|
1078
|
+
key,
|
|
1079
|
+
path: key,
|
|
1080
|
+
ref,
|
|
1081
|
+
sha: ref
|
|
1082
|
+
};
|
|
1083
|
+
}).filter((file) => Boolean(file));
|
|
1084
|
+
}
|
|
1085
|
+
async function loadFiles(token, resolvedRef) {
|
|
1086
|
+
const ref = resolvedRef ?? await getRef(token);
|
|
1087
|
+
if (sparsePatterns) try {
|
|
1088
|
+
return await loadGitArchiveFiles({
|
|
1089
|
+
credentials: (await loadForge()).forgeGitCredentials({
|
|
1090
|
+
forge: "github",
|
|
1091
|
+
repository: options.repo,
|
|
1092
|
+
token
|
|
1093
|
+
}),
|
|
1094
|
+
keyForRepoPath,
|
|
1095
|
+
ref,
|
|
1096
|
+
shouldInclude,
|
|
1097
|
+
signal: void 0,
|
|
1098
|
+
sparsePatterns
|
|
1099
|
+
});
|
|
1100
|
+
} catch {}
|
|
1101
|
+
return await loadArchiveFiles(token, ref);
|
|
1102
|
+
}
|
|
1103
|
+
const loadedFiles = /* @__PURE__ */ new Map();
|
|
1104
|
+
const cachedLoadFiles = providerCache ? defineCachedFunction(async (resolvedRef, token) => await loadFiles(token, resolvedRef), {
|
|
1105
|
+
...providerCache,
|
|
1106
|
+
getKey: (resolvedRef, token) => cacheKey("archive", token, "", resolvedRef),
|
|
1107
|
+
name: "github-source-archive"
|
|
1108
|
+
}) : (resolvedRef, token) => dedupeProviderPromise(loadedFiles, cacheKey("archive", token, "", resolvedRef), () => loadFiles(token, resolvedRef));
|
|
1109
|
+
function getFiles(token, signal, resolvedRef) {
|
|
1110
|
+
return waitForCachedGitHubResult(() => cachedLoadFiles(resolvedRef, token), signal);
|
|
1111
|
+
}
|
|
1112
|
+
async function loadFileMetadata(key, token, resolvedRef) {
|
|
1113
|
+
let normalizedKey;
|
|
1114
|
+
try {
|
|
1115
|
+
normalizedKey = normalizeSafeSourcePath(key);
|
|
1116
|
+
} catch {
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
if (!normalizedKey || !shouldInclude(normalizedKey)) return;
|
|
1120
|
+
const ref = resolvedRef ?? await getRef(token);
|
|
1121
|
+
const repoPath = repoPathForKey(normalizedKey);
|
|
1122
|
+
let file;
|
|
1123
|
+
try {
|
|
1124
|
+
file = await client.metadata(repoPath, ref, token);
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
if (isGitHubAccessError(error)) {
|
|
1127
|
+
await validateConfiguredRef(token);
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (shouldResolveMainFallback(error)) return (await getFiles(token, void 0, ref)).find((file) => file.key === normalizedKey);
|
|
1131
|
+
throw error;
|
|
1132
|
+
}
|
|
1133
|
+
if (!file) return;
|
|
1134
|
+
return {
|
|
1135
|
+
key: normalizedKey,
|
|
1136
|
+
path: normalizedKey,
|
|
1137
|
+
ref,
|
|
1138
|
+
sha: file.sha
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
const loadedFileMetadata = /* @__PURE__ */ new Map();
|
|
1142
|
+
const cachedLoadFileMetadata = providerCache ? defineCachedFunction(async (key, resolvedRef, token) => await loadFileMetadata(key, token, resolvedRef), {
|
|
1143
|
+
...providerCache,
|
|
1144
|
+
getKey: (key, resolvedRef, token) => cacheKey("metadata", token, key, resolvedRef),
|
|
1145
|
+
name: "github-source-metadata"
|
|
1146
|
+
}) : (key, resolvedRef, token) => dedupeProviderPromise(loadedFileMetadata, cacheKey("metadata", token, key, resolvedRef), () => loadFileMetadata(key, token, resolvedRef));
|
|
1147
|
+
function isGitHubAccessError(error) {
|
|
1148
|
+
return githubErrorStatus(error) === 404;
|
|
1149
|
+
}
|
|
1150
|
+
async function loadFile(key, token, signal, resolvedRef) {
|
|
1151
|
+
let normalizedKey;
|
|
1152
|
+
try {
|
|
1153
|
+
normalizedKey = normalizeSafeSourcePath(key);
|
|
1154
|
+
} catch {
|
|
1155
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
1156
|
+
}
|
|
1157
|
+
if (!normalizedKey || !shouldInclude(normalizedKey)) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
1158
|
+
const ref = resolvedRef ?? await getRef(token, signal);
|
|
1159
|
+
const repoPath = repoPathForKey(normalizedKey);
|
|
1160
|
+
const file = await client.file(repoPath, ref, token, signal);
|
|
1161
|
+
return {
|
|
1162
|
+
content: file.content,
|
|
1163
|
+
key: normalizedKey,
|
|
1164
|
+
path: normalizedKey,
|
|
1165
|
+
ref,
|
|
1166
|
+
sha: file.sha || ref
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
async function getFile(key, ctx, token) {
|
|
1170
|
+
if (ctx?.abortSignal) return await loadFile(key, token, ctx.abortSignal, ctx.revision?.id);
|
|
1171
|
+
const file = (await getFiles(token, void 0, ctx?.revision?.id)).find((file) => file.key === key);
|
|
1172
|
+
if (!file) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
1173
|
+
return file;
|
|
1174
|
+
}
|
|
1175
|
+
function fetchContent(key, file) {
|
|
1176
|
+
if (file.content) return file.content;
|
|
1177
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include archive content for ${JSON.stringify(key)}.`);
|
|
1178
|
+
}
|
|
1179
|
+
function cacheKey(kind, token, key = "", resolvedRef) {
|
|
1180
|
+
return createGitHubCacheKey({
|
|
1181
|
+
authScope: githubAuthenticationScope(token),
|
|
1182
|
+
ignore: options.ignore,
|
|
1183
|
+
include: options.include,
|
|
1184
|
+
key,
|
|
1185
|
+
kind,
|
|
1186
|
+
ref: resolvedRef || configuredRef || "default",
|
|
1187
|
+
repo: options.repo,
|
|
1188
|
+
root
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
return {
|
|
1192
|
+
cache: options.cache,
|
|
1193
|
+
fingerprint: {
|
|
1194
|
+
ignore: options.ignore,
|
|
1195
|
+
include: options.include,
|
|
1196
|
+
ref: configuredRef || "default",
|
|
1197
|
+
repo: options.repo,
|
|
1198
|
+
root
|
|
1199
|
+
},
|
|
1200
|
+
name: "github",
|
|
1201
|
+
async authenticated() {
|
|
1202
|
+
return Boolean(await resolveAuth());
|
|
1203
|
+
},
|
|
1204
|
+
async history(key, historyOptions) {
|
|
1205
|
+
return await client.commits(repoPathForKey(normalizeSafeSourcePath(key)), historyOptions, await resolveAuth());
|
|
1206
|
+
},
|
|
1207
|
+
async latest(keys, latestOptions) {
|
|
1208
|
+
const token = await resolveAuth();
|
|
1209
|
+
const paths = keys.map((key) => repoPathForKey(normalizeSafeSourcePath(key)));
|
|
1210
|
+
const found = /* @__PURE__ */ new Map();
|
|
1211
|
+
async function read(start, end) {
|
|
1212
|
+
try {
|
|
1213
|
+
(await client.latestCommits(paths.slice(start, end), latestOptions.sha, token)).forEach((commit, index) => commit && found.set(keys[start + index], commit));
|
|
1214
|
+
} catch (error) {
|
|
1215
|
+
const status = githubErrorStatus(error);
|
|
1216
|
+
if (status !== 502 && status !== 504 || end - start <= historyBatchMin) throw error;
|
|
1217
|
+
const middle = start + Math.ceil((end - start) / 2);
|
|
1218
|
+
await Promise.all([read(start, middle), read(middle, end)]);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
const batches = Array.from({ length: Math.ceil(paths.length / historyBatch) }, (_, index) => index * historyBatch);
|
|
1222
|
+
let next = 0;
|
|
1223
|
+
await Promise.all(Array.from({ length: Math.min(historyConcurrency, batches.length) }, async () => {
|
|
1224
|
+
while (next < batches.length) {
|
|
1225
|
+
const start = batches[next++];
|
|
1226
|
+
await read(start, Math.min(start + historyBatch, paths.length));
|
|
1227
|
+
}
|
|
1228
|
+
}));
|
|
1229
|
+
return found;
|
|
1230
|
+
},
|
|
1231
|
+
async changes(base, head) {
|
|
1232
|
+
const paths = await client.changedPaths(base, head, await resolveAuth());
|
|
1233
|
+
if (!paths) return;
|
|
1234
|
+
const prefix = root ? `${root}/` : "";
|
|
1235
|
+
return [...new Set(paths.filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length)))];
|
|
1236
|
+
},
|
|
1237
|
+
async pullChanges(number) {
|
|
1238
|
+
const paths = await client.pullPaths(number, await resolveAuth());
|
|
1239
|
+
if (!paths) return;
|
|
1240
|
+
const prefix = root ? `${root}/` : "";
|
|
1241
|
+
return [...new Set(paths.filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length)))];
|
|
1242
|
+
},
|
|
1243
|
+
async resolveRef(ref, refOptions) {
|
|
1244
|
+
const token = await resolveAuth();
|
|
1245
|
+
const signal = refOptions?.signal;
|
|
1246
|
+
if ("pull" in ref) {
|
|
1247
|
+
const pull = await client.pull(ref.pull, token, signal);
|
|
1248
|
+
return pull && {
|
|
1249
|
+
sha: pull.sha,
|
|
1250
|
+
pull: pull.pull
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
const sha = "branch" in ref ? await client.branch(ref.branch, token, signal) : await client.commit(ref.sha, token, signal);
|
|
1254
|
+
return sha === void 0 ? void 0 : { sha };
|
|
1255
|
+
},
|
|
1256
|
+
async contains(sha, refOptions) {
|
|
1257
|
+
const token = await resolveAuth();
|
|
1258
|
+
const signal = refOptions?.signal;
|
|
1259
|
+
const base = configuredRef ?? await client.defaultBranch(token, signal);
|
|
1260
|
+
const status = await client.compare(base, sha, token, signal);
|
|
1261
|
+
return status === "identical" || status === "behind";
|
|
1262
|
+
},
|
|
1263
|
+
async pullsAt(sha, refOptions) {
|
|
1264
|
+
const token = await resolveAuth();
|
|
1265
|
+
const signal = refOptions?.signal;
|
|
1266
|
+
const at = (entries) => entries.filter((entry) => entry.sha.toLowerCase() === sha.toLowerCase()).map((entry) => entry.pull);
|
|
1267
|
+
const pulls = at(await client.commitPulls(sha, token, signal));
|
|
1268
|
+
if (pulls.length) return pulls;
|
|
1269
|
+
return at(await client.openPulls(token, signal));
|
|
1270
|
+
},
|
|
1271
|
+
async resolveRevision(ctx) {
|
|
1272
|
+
return await resolveSourceRevision(await contextAuth(ctx), ctx.abortSignal);
|
|
1273
|
+
},
|
|
1274
|
+
async getKeys(ctx) {
|
|
1275
|
+
return (await getFiles(await contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => file.key);
|
|
1276
|
+
},
|
|
1277
|
+
async getItems(ctx) {
|
|
1278
|
+
return (await getFiles(await contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => ({
|
|
1279
|
+
key: file.key,
|
|
1280
|
+
path: file.path,
|
|
1281
|
+
content: fetchContent(file.key, file),
|
|
1282
|
+
metadata: {
|
|
1283
|
+
ref: file.ref,
|
|
1284
|
+
sha: file.sha
|
|
1285
|
+
}
|
|
1286
|
+
}));
|
|
1287
|
+
},
|
|
1288
|
+
async getMeta(key, ctx) {
|
|
1289
|
+
const token = await contextAuth(ctx);
|
|
1290
|
+
const file = await waitForCachedGitHubResult(() => cachedLoadFileMetadata(key, ctx.revision?.id, token), ctx?.abortSignal);
|
|
1291
|
+
if (!file) return;
|
|
1292
|
+
return {
|
|
1293
|
+
ref: file.ref,
|
|
1294
|
+
sha: file.sha
|
|
1295
|
+
};
|
|
1296
|
+
},
|
|
1297
|
+
async getItem(key, ctx) {
|
|
1298
|
+
const file = await getFile(key, ctx, await contextAuth(ctx));
|
|
1299
|
+
return {
|
|
1300
|
+
key: file.key,
|
|
1301
|
+
path: file.path,
|
|
1302
|
+
content: fetchContent(key, file),
|
|
1303
|
+
metadata: {
|
|
1304
|
+
ref: file.ref,
|
|
1305
|
+
sha: file.sha
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
//#endregion
|
|
1312
|
+
export { github };
|