@vite-hub/source 0.0.4 → 0.1.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 +219 -82
- package/dist/{auth-Ddw55OUG.js → auth-B-tX_rp0.js} +255 -90
- package/dist/{client-CDfTmtQu.js → client-BwstxtdY.js} +584 -207
- package/dist/client.d.ts +27 -10
- package/dist/client.js +71 -13
- package/dist/collection-B_4w_J8h.d.ts +257 -0
- package/dist/{collection-B8pXGM2d.js → collection-cursor-WzV1Jd6v.js} +37 -54
- package/dist/collection-route-BplWPxHR.js +10 -0
- package/dist/drizzle.d.ts +41 -0
- package/dist/drizzle.js +89 -0
- package/dist/error-diagnostics-X0kuFjBT.js +51 -0
- package/dist/file-BX0FSvgE.js +60 -0
- package/dist/{file-EQ3AjVM6.d.ts → file-DadN9dbN.d.ts} +2 -3
- package/dist/file.d.ts +1 -1
- package/dist/file.js +1 -1
- package/dist/files.d.ts +15 -0
- package/dist/files.js +38 -0
- package/dist/github.d.ts +8 -5
- package/dist/github.js +725 -426
- package/dist/glob-BmFqTvJY.js +993 -0
- package/dist/glob.d.ts +12 -4
- package/dist/glob.js +1 -894
- package/dist/index.d.ts +118 -27
- package/dist/index.js +623 -14
- package/dist/markdown.d.ts +4 -6
- package/dist/markdown.js +2 -2
- package/dist/mcp.d.ts +3 -4
- package/dist/mcp.js +302 -5920
- package/dist/{file-BSWQg9Qv.js → mrmime-40h5OOIp.js} +1 -56
- package/dist/{path-CUhvUREm.js → path-BS8rYm0n.js} +60 -40
- package/dist/{path-BzmU4Eni.js → path-DOBpV8ol.js} +3 -7
- package/dist/server.d.ts +256 -6
- package/dist/server.js +90 -12
- package/dist/{sse-CE9Q2JqM.js → sse-D9gqqNPj.js} +50 -9
- package/dist/{streamableHttp-BszaXLmg.js → streamableHttp-BL-E7pl5.js} +40 -22
- package/dist/types-BigOktIj.d.ts +93 -0
- package/dist/{types-AIBmt_m6.js → types-CoWcW8oz.js} +2502 -1187
- package/dist/vite.d.ts +134 -13
- package/dist/vite.js +1734 -79
- package/package.json +55 -36
- package/dist/collection-CF2ON__k.d.ts +0 -92
- package/dist/collection-route-Dw7QLFyx.js +0 -6
- package/dist/content/client.d.ts +0 -3
- package/dist/content/client.js +0 -2
- package/dist/content.d.ts +0 -44
- package/dist/content.js +0 -157
- package/dist/registry-C8skfCSV.js +0 -120
- package/dist/types-Bu3WvNX9.d.ts +0 -71
package/dist/github.js
CHANGED
|
@@ -1,250 +1,346 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { n as matchesAny } from "./path-BS8rYm0n.js";
|
|
2
|
+
import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
|
|
3
|
+
import { i as sourceError, n as normalizeSafeSourcePath, r as normalizeSourcePath } from "./path-DOBpV8ol.js";
|
|
4
|
+
import { forgeArchive, forgeEnv, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeProvider, readForgeEnv } from "@vite-hub/forge";
|
|
5
|
+
import crypto, { createHash } from "node:crypto";
|
|
3
6
|
import { Buffer } from "node:buffer";
|
|
4
|
-
import { createHash } from "node:crypto";
|
|
5
7
|
import { gunzipSync } from "node:zlib";
|
|
6
8
|
import { devNull } from "node:os";
|
|
7
|
-
//#region ../../node_modules/.pnpm/
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const weights = /* @__PURE__ */ new Uint8Array(128);
|
|
15
|
-
for (let i = 0; i < 69; i++) weights[asciiOrder.charCodeAt(i)] = i + 1;
|
|
16
|
-
for (let code = 65; code <= 90; code++) weights[code] = weights[code + 32];
|
|
17
|
-
return weights;
|
|
18
|
-
})();
|
|
19
|
-
function compareStrings(a, b) {
|
|
20
|
-
if (a === b) return 0;
|
|
21
|
-
const length = Math.min(a.length, b.length);
|
|
22
|
-
let tieBreaker = 0;
|
|
23
|
-
for (let i = 0; i < length; i++) {
|
|
24
|
-
const codeA = a.charCodeAt(i);
|
|
25
|
-
const codeB = b.charCodeAt(i);
|
|
26
|
-
if (codeA === codeB) continue;
|
|
27
|
-
const weightA = codeA < 128 && asciiWeights[codeA] ? asciiWeights[codeA] : codeA + 128;
|
|
28
|
-
const weightB = codeB < 128 && asciiWeights[codeB] ? asciiWeights[codeB] : codeB + 128;
|
|
29
|
-
if (weightA !== weightB) return weightA < weightB ? -1 : 1;
|
|
30
|
-
if (tieBreaker === 0) tieBreaker = codeA > codeB ? -1 : 1;
|
|
31
|
-
}
|
|
32
|
-
if (a.length !== b.length) return a.length < b.length ? -1 : 1;
|
|
33
|
-
return tieBreaker;
|
|
34
|
-
}
|
|
35
|
-
const Serializer = /*@__PURE__*/ (function() {
|
|
36
|
-
class Serializer {
|
|
37
|
-
#context = /* @__PURE__ */ new Map();
|
|
38
|
-
compare(a, b) {
|
|
39
|
-
const typeA = typeof a;
|
|
40
|
-
const typeB = typeof b;
|
|
41
|
-
if (typeA === "string" && typeB === "string") return compareStrings(a, b);
|
|
42
|
-
if (typeA === "number" && typeB === "number") return a - b;
|
|
43
|
-
return compareStrings(this.serialize(a, true), this.serialize(b, true));
|
|
44
|
-
}
|
|
45
|
-
serialize(value, noQuotes) {
|
|
46
|
-
if (value === null) return "null";
|
|
47
|
-
switch (typeof value) {
|
|
48
|
-
case "string": return noQuotes ? value : `'${value}'`;
|
|
49
|
-
case "bigint": return `${value}n`;
|
|
50
|
-
case "object": return this.$object(value);
|
|
51
|
-
case "function": return this.$function(value);
|
|
52
|
-
}
|
|
53
|
-
return String(value);
|
|
54
|
-
}
|
|
55
|
-
serializeObject(object) {
|
|
56
|
-
const objString = Object.prototype.toString.call(object);
|
|
57
|
-
if (objString !== "[object Object]") return this.serializeBuiltInType(objString.length < 10 ? `unknown:${objString}` : objString.slice(8, -1), object);
|
|
58
|
-
const constructor = object.constructor;
|
|
59
|
-
const objName = constructor === Object || constructor === void 0 ? "" : constructor.name;
|
|
60
|
-
if (objName !== "" && globalThis[objName] === constructor) return this.serializeBuiltInType(objName, object);
|
|
61
|
-
if ("toJSON" in object && typeof object.toJSON === "function") {
|
|
62
|
-
const json = object.toJSON();
|
|
63
|
-
return objName + (json !== null && typeof json === "object" ? this.$object(json) : `(${this.serialize(json)})`);
|
|
64
|
-
}
|
|
65
|
-
const keys = Object.keys(object).sort(compareStrings);
|
|
66
|
-
let content = `${objName}{`;
|
|
67
|
-
for (let i = 0; i < keys.length; i++) {
|
|
68
|
-
const key = keys[i];
|
|
69
|
-
content += `${key}:${this.serialize(object[key])}`;
|
|
70
|
-
if (i < keys.length - 1) content += ",";
|
|
71
|
-
}
|
|
72
|
-
return content + "}";
|
|
73
|
-
}
|
|
74
|
-
serializeBuiltInType(type, object) {
|
|
75
|
-
const handler = this["$" + type];
|
|
76
|
-
if (handler) return handler.call(this, object);
|
|
77
|
-
if (typeof object.entries === "function") return this.serializeObjectEntries(type, object.entries());
|
|
78
|
-
throw new Error(`Cannot serialize ${type}`);
|
|
79
|
-
}
|
|
80
|
-
serializeObjectEntries(type, entries) {
|
|
81
|
-
const sortedEntries = Array.from(entries).sort((a, b) => this.compare(a[0], b[0]));
|
|
82
|
-
let content = `${type}{`;
|
|
83
|
-
for (let i = 0; i < sortedEntries.length; i++) {
|
|
84
|
-
const [key, value] = sortedEntries[i];
|
|
85
|
-
content += `${this.serialize(key, true)}:${this.serialize(value)}`;
|
|
86
|
-
if (i < sortedEntries.length - 1) content += ",";
|
|
87
|
-
}
|
|
88
|
-
return content + "}";
|
|
89
|
-
}
|
|
90
|
-
$object(object) {
|
|
91
|
-
let content = this.#context.get(object);
|
|
92
|
-
if (content === void 0) {
|
|
93
|
-
this.#context.set(object, `#${this.#context.size}`);
|
|
94
|
-
content = this.serializeObject(object);
|
|
95
|
-
this.#context.set(object, content);
|
|
96
|
-
}
|
|
97
|
-
return content;
|
|
98
|
-
}
|
|
99
|
-
$function(fn) {
|
|
100
|
-
const fnStr = Function.prototype.toString.call(fn);
|
|
101
|
-
if (fnStr.slice(-15) === "[native code] }") return `${fn.name || ""}()[native]`;
|
|
102
|
-
return `${fn.name}(${fn.length})${fnStr.replace(/\s*\n\s*/g, "")}`;
|
|
103
|
-
}
|
|
104
|
-
$Array(arr) {
|
|
105
|
-
let content = "[";
|
|
106
|
-
for (let i = 0; i < arr.length; i++) {
|
|
107
|
-
content += this.serialize(arr[i]);
|
|
108
|
-
if (i < arr.length - 1) content += ",";
|
|
109
|
-
}
|
|
110
|
-
return content + "]";
|
|
111
|
-
}
|
|
112
|
-
$Date(date) {
|
|
113
|
-
try {
|
|
114
|
-
return `Date(${date.toISOString()})`;
|
|
115
|
-
} catch {
|
|
116
|
-
return `Date(null)`;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
$ArrayBuffer(arr) {
|
|
120
|
-
return `ArrayBuffer[${new Uint8Array(arr).join(",")}]`;
|
|
121
|
-
}
|
|
122
|
-
$Set(set) {
|
|
123
|
-
return `Set${this.$Array(Array.from(set).sort((a, b) => this.compare(a, b)))}`;
|
|
124
|
-
}
|
|
125
|
-
$Map(map) {
|
|
126
|
-
return this.serializeObjectEntries("Map", map.entries());
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
for (const type of [
|
|
130
|
-
"Error",
|
|
131
|
-
"RegExp",
|
|
132
|
-
"URL"
|
|
133
|
-
]) Serializer.prototype["$" + type] = function(val) {
|
|
134
|
-
return `${type}(${val})`;
|
|
135
|
-
};
|
|
136
|
-
for (const type of [
|
|
137
|
-
"Int8Array",
|
|
138
|
-
"Uint8Array",
|
|
139
|
-
"Uint8ClampedArray",
|
|
140
|
-
"Int16Array",
|
|
141
|
-
"Uint16Array",
|
|
142
|
-
"Int32Array",
|
|
143
|
-
"Uint32Array",
|
|
144
|
-
"Float32Array",
|
|
145
|
-
"Float64Array"
|
|
146
|
-
]) Serializer.prototype["$" + type] = function(arr) {
|
|
147
|
-
return `${type}[${arr.join(",")}]`;
|
|
148
|
-
};
|
|
149
|
-
for (const type of ["BigInt64Array", "BigUint64Array"]) Serializer.prototype["$" + type] = function(arr) {
|
|
150
|
-
return `${type}[${arr.join("n,")}${arr.length > 0 ? "n" : ""}]`;
|
|
151
|
-
};
|
|
152
|
-
return Serializer;
|
|
153
|
-
})();
|
|
154
|
-
//#endregion
|
|
155
|
-
//#region ../../node_modules/.pnpm/ohash@2.0.12/node_modules/ohash/dist/crypto/node/index.mjs
|
|
156
|
-
const fastHash = /*@__PURE__*/ (() => globalThis.process?.getBuiltinModule?.("crypto")?.hash)();
|
|
157
|
-
const algorithm = "sha256";
|
|
158
|
-
const encoding = "base64url";
|
|
9
|
+
//#region ../../node_modules/.pnpm/ocache@0.3.0/node_modules/ocache/lib/digest.node.mjs
|
|
10
|
+
/**
|
|
11
|
+
* Both forms hash the same bytes: a string is UTF-8 encoded, a `Uint8Array` is hashed as given.
|
|
12
|
+
*
|
|
13
|
+
* @param {string | Uint8Array} data
|
|
14
|
+
* @returns {string} sha256 of `data`, base64url, unpadded.
|
|
15
|
+
*/
|
|
159
16
|
function digest(data) {
|
|
160
|
-
|
|
161
|
-
const h = createHash(algorithm).update(data);
|
|
162
|
-
return globalThis.process?.versions?.webcontainer ? h.digest().toString(encoding) : h.digest(encoding);
|
|
17
|
+
return crypto.hash ? crypto.hash("sha256", data, "base64url") : crypto.createHash("sha256").update(data).digest("base64url");
|
|
163
18
|
}
|
|
164
19
|
//#endregion
|
|
165
|
-
//#region ../../node_modules/.pnpm/
|
|
20
|
+
//#region ../../node_modules/.pnpm/ocache@0.3.0/node_modules/ocache/dist/index.mjs
|
|
21
|
+
const NodeBuffer = globalThis.Buffer;
|
|
22
|
+
const hasNativeCodec = typeof Uint8Array.prototype.toBase64 === "function" && typeof Uint8Array.fromBase64 === "function";
|
|
23
|
+
const bytesToBase64 = NodeBuffer ? bufferToBase64 : hasNativeCodec ? nativeToBase64 : portableToBase64;
|
|
24
|
+
const base64ToBytes = NodeBuffer ? bufferFromBase64 : hasNativeCodec ? nativeFromBase64 : portableFromBase64;
|
|
25
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
26
|
+
function bufferToBase64(bytes) {
|
|
27
|
+
return NodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
28
|
+
}
|
|
29
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
30
|
+
function bufferFromBase64(base64) {
|
|
31
|
+
const buffer = NodeBuffer.from(base64, "base64");
|
|
32
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
33
|
+
}
|
|
34
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
35
|
+
function nativeToBase64(bytes) {
|
|
36
|
+
return bytes.toBase64();
|
|
37
|
+
}
|
|
38
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
39
|
+
function nativeFromBase64(base64) {
|
|
40
|
+
return Uint8Array.fromBase64(base64);
|
|
41
|
+
}
|
|
42
|
+
const CHUNK = 32766;
|
|
43
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
44
|
+
function portableToBase64(bytes) {
|
|
45
|
+
let base64 = "";
|
|
46
|
+
for (let start = 0; start < bytes.length; start += CHUNK) {
|
|
47
|
+
const end = Math.min(start + CHUNK, bytes.length);
|
|
48
|
+
let binary = "";
|
|
49
|
+
for (let i = start; i < end; i++) binary += String.fromCharCode(bytes[i]);
|
|
50
|
+
base64 += btoa(binary);
|
|
51
|
+
}
|
|
52
|
+
return base64;
|
|
53
|
+
}
|
|
54
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
55
|
+
function portableFromBase64(base64) {
|
|
56
|
+
const binary = atob(base64);
|
|
57
|
+
const bytes = new Uint8Array(binary.length);
|
|
58
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
59
|
+
return bytes;
|
|
60
|
+
}
|
|
61
|
+
const PREFIX = "[ocache]";
|
|
62
|
+
function error(name, message, options) {
|
|
63
|
+
const err = new Error(`${PREFIX} ${message}`, options);
|
|
64
|
+
err.name = name;
|
|
65
|
+
return err;
|
|
66
|
+
}
|
|
67
|
+
function timeoutError(seconds) {
|
|
68
|
+
return error("TimeoutError", `Resolver timed out after ${seconds}s.`);
|
|
69
|
+
}
|
|
70
|
+
function storageRequiredError(caller) {
|
|
71
|
+
return error("StorageRequiredError", `${caller}() requires \`options.storage\`.`);
|
|
72
|
+
}
|
|
73
|
+
function malformedEntryError() {
|
|
74
|
+
return error("MalformedEntryError", "Malformed data read from cache.");
|
|
75
|
+
}
|
|
76
|
+
function tooDeepError(maxDepth) {
|
|
77
|
+
return /* @__PURE__ */ new RangeError(`${PREFIX} Cannot hash a value nested deeper than ${maxDepth} levels. Pass an explicit \`getKey\`.`);
|
|
78
|
+
}
|
|
79
|
+
const SharedBuffer$1 = globalThis.SharedArrayBuffer;
|
|
80
|
+
const MAX_DEPTH = 128;
|
|
166
81
|
function hash(input) {
|
|
167
82
|
return digest(serialize(input));
|
|
168
83
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
84
|
+
function serialize(input) {
|
|
85
|
+
return typeof input === "string" ? serString(input) : ser(input, /* @__PURE__ */ new Map(), 0);
|
|
86
|
+
}
|
|
87
|
+
function serString(value) {
|
|
88
|
+
return `'${value.length}:${value}`;
|
|
89
|
+
}
|
|
90
|
+
function serTag(ctor) {
|
|
91
|
+
return serString(typeof ctor.name === "string" ? ctor.name : "");
|
|
92
|
+
}
|
|
93
|
+
function serBytes(bytes) {
|
|
94
|
+
return serString(bytesToBase64(bytes));
|
|
95
|
+
}
|
|
96
|
+
function ser(value, seen, depth) {
|
|
97
|
+
if (value === null) return "null";
|
|
98
|
+
switch (typeof value) {
|
|
99
|
+
case "string": return serString(value);
|
|
100
|
+
case "bigint": return `${value}n`;
|
|
101
|
+
case "symbol": return value.description === void 0 ? "Symbol()" : `Symbol${serString(value.description)}`;
|
|
102
|
+
case "function": return `Function${serString(`${value.name}(${value.length})${Function.prototype.toString.call(value).replace(/\s*\n\s*/g, " ")}`)}`;
|
|
103
|
+
case "object": {
|
|
104
|
+
const ref = seen.get(value);
|
|
105
|
+
if (ref !== void 0) return ref;
|
|
106
|
+
if (depth >= MAX_DEPTH) throw tooDeepError(MAX_DEPTH);
|
|
107
|
+
seen.set(value, `#${seen.size}`);
|
|
108
|
+
const serialized = serObject(value, seen, depth + 1);
|
|
109
|
+
seen.set(value, serialized);
|
|
110
|
+
return serialized;
|
|
111
|
+
}
|
|
112
|
+
default: return String(value);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function serObject(value, seen, depth) {
|
|
116
|
+
if (Array.isArray(value)) {
|
|
117
|
+
let items = "";
|
|
118
|
+
for (let index = 0; index < value.length; index++) items += index === 0 ? ser(value[index], seen, depth) : `,${ser(value[index], seen, depth)}`;
|
|
119
|
+
return `[${items}]`;
|
|
120
|
+
}
|
|
121
|
+
const ctor = value.constructor;
|
|
122
|
+
if (ctor === Object || ctor == null) return serProperties("", value, seen, depth);
|
|
123
|
+
if (value instanceof Date) return `Date(${Number.isNaN(value.getTime()) ? "null" : value.toISOString()})`;
|
|
124
|
+
if (value instanceof RegExp || value instanceof URL || value instanceof URLSearchParams || value instanceof Error) return `${serTag(ctor)}${serString(String(value))}`;
|
|
125
|
+
if (value instanceof Headers) {
|
|
126
|
+
let items = "";
|
|
127
|
+
for (const [name, item] of value) items += `,${serString(name)}:${serString(item)}`;
|
|
128
|
+
return `Headers{${items.slice(1)}}`;
|
|
129
|
+
}
|
|
130
|
+
if (value instanceof Set) {
|
|
131
|
+
const parts = [];
|
|
132
|
+
for (const item of value) parts.push(ser(item, seen, depth));
|
|
133
|
+
return `Set[${parts.sort().join(",")}]`;
|
|
134
|
+
}
|
|
135
|
+
if (value instanceof Map) {
|
|
136
|
+
const parts = [];
|
|
137
|
+
for (const [key, item] of value) parts.push(`${ser(key, seen, depth)}:${ser(item, seen, depth)}`);
|
|
138
|
+
return `Map{${parts.sort().join(",")}}`;
|
|
139
|
+
}
|
|
140
|
+
if (value instanceof ArrayBuffer || SharedBuffer$1 && value instanceof SharedBuffer$1) return `${serTag(ctor)}[${serBytes(new Uint8Array(value))}]`;
|
|
141
|
+
if (ArrayBuffer.isView(value)) {
|
|
142
|
+
const perElement = value.BYTES_PER_ELEMENT;
|
|
143
|
+
const items = perElement === void 0 || perElement === 1 ? serBytes(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) : value.join(",");
|
|
144
|
+
return `${serTag(ctor)}[${items}]`;
|
|
145
|
+
}
|
|
146
|
+
return serProperties(serTag(ctor), value, seen, depth);
|
|
147
|
+
}
|
|
148
|
+
function serProperties(tag, value, seen, depth) {
|
|
149
|
+
const toJSON = value.toJSON;
|
|
150
|
+
if (typeof toJSON === "function") return `${tag}(${ser(toJSON.call(value), seen, depth)})`;
|
|
151
|
+
const keys = Object.keys(value).sort();
|
|
152
|
+
let parts = "";
|
|
153
|
+
for (let index = 0; index < keys.length; index++) {
|
|
154
|
+
const key = keys[index];
|
|
155
|
+
parts += index === 0 ? `${serString(key)}:` : `,${serString(key)}:`;
|
|
156
|
+
parts += ser(value[key], seen, depth);
|
|
157
|
+
}
|
|
158
|
+
return `${tag}{${parts}}`;
|
|
159
|
+
}
|
|
160
|
+
const SharedBuffer = globalThis.SharedArrayBuffer;
|
|
161
|
+
const DEFAULT_MEMORY_MAX_SIZE = 1e4;
|
|
162
|
+
const DEFAULT_MEMORY_MAX_BYTES = 104857600;
|
|
163
|
+
function createMemoryStorage(opts = {}) {
|
|
164
|
+
const rawMaxSize = opts.maxSize ?? DEFAULT_MEMORY_MAX_SIZE;
|
|
165
|
+
const rawMaxBytes = opts.maxBytes ?? DEFAULT_MEMORY_MAX_BYTES;
|
|
166
|
+
const maxSize = Number.isFinite(rawMaxSize) && rawMaxSize > 0 ? rawMaxSize : void 0;
|
|
167
|
+
const maxBytes = Number.isFinite(rawMaxBytes) && rawMaxBytes > 0 ? rawMaxBytes : void 0;
|
|
168
|
+
const sizeOf = opts.sizeOf;
|
|
172
169
|
const map = /* @__PURE__ */ new Map();
|
|
173
170
|
const timers = /* @__PURE__ */ new Map();
|
|
171
|
+
let totalBytes = 0;
|
|
172
|
+
function deleteEntry(key) {
|
|
173
|
+
const entry = map.get(key);
|
|
174
|
+
if (entry) {
|
|
175
|
+
totalBytes -= entry.bytes;
|
|
176
|
+
map.delete(key);
|
|
177
|
+
}
|
|
178
|
+
clearTimer(timers, key);
|
|
179
|
+
}
|
|
174
180
|
return {
|
|
181
|
+
maxEntryBytes: maxBytes,
|
|
182
|
+
binary: true,
|
|
175
183
|
get(key) {
|
|
176
184
|
const entry = map.get(key);
|
|
177
185
|
if (!entry) return null;
|
|
178
186
|
if (entry.expires && Date.now() > entry.expires) {
|
|
179
|
-
|
|
180
|
-
_clearTimer(timers, key);
|
|
187
|
+
deleteEntry(key);
|
|
181
188
|
return null;
|
|
182
189
|
}
|
|
190
|
+
if (maxSize || maxBytes) {
|
|
191
|
+
map.delete(key);
|
|
192
|
+
map.set(key, entry);
|
|
193
|
+
}
|
|
183
194
|
return entry.value;
|
|
184
195
|
},
|
|
185
196
|
set(key, value, opts) {
|
|
186
|
-
|
|
187
|
-
if (value === null || value === void 0)
|
|
188
|
-
|
|
189
|
-
|
|
197
|
+
deleteEntry(key);
|
|
198
|
+
if (value === null || value === void 0) return;
|
|
199
|
+
let bytes = 0;
|
|
200
|
+
if (maxBytes) {
|
|
201
|
+
const measured = entryBytes(key, value, sizeOf);
|
|
202
|
+
if (measured === void 0 || measured > maxBytes) return;
|
|
203
|
+
bytes = measured;
|
|
190
204
|
}
|
|
191
205
|
const ttlMs = opts?.ttl ? opts.ttl * 1e3 : void 0;
|
|
192
206
|
map.set(key, {
|
|
193
207
|
value,
|
|
194
|
-
expires: ttlMs ? Date.now() + ttlMs : void 0
|
|
208
|
+
expires: ttlMs ? Date.now() + ttlMs : void 0,
|
|
209
|
+
bytes
|
|
195
210
|
});
|
|
211
|
+
totalBytes += bytes;
|
|
196
212
|
if (ttlMs) {
|
|
197
213
|
const timer = setTimeout(() => {
|
|
198
|
-
|
|
199
|
-
timers.delete(key);
|
|
214
|
+
deleteEntry(key);
|
|
200
215
|
}, ttlMs);
|
|
201
216
|
if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
|
|
202
217
|
timers.set(key, timer);
|
|
203
218
|
}
|
|
219
|
+
if (maxSize || maxBytes) while (maxSize && map.size > maxSize || maxBytes && totalBytes > maxBytes) {
|
|
220
|
+
const oldest = map.keys().next().value;
|
|
221
|
+
if (oldest === void 0) break;
|
|
222
|
+
deleteEntry(oldest);
|
|
223
|
+
}
|
|
204
224
|
}
|
|
205
225
|
};
|
|
206
226
|
}
|
|
207
|
-
|
|
227
|
+
const ENTRY_OVERHEAD = 64;
|
|
228
|
+
const PROPERTY_OVERHEAD = 8;
|
|
229
|
+
const MAX_ESTIMATE_DEPTH = 8;
|
|
230
|
+
function entryBytes(key, value, sizeOf) {
|
|
231
|
+
if (sizeOf) try {
|
|
232
|
+
const size = sizeOf(value, key);
|
|
233
|
+
if (Number.isFinite(size) && size >= 0) return size;
|
|
234
|
+
} catch {}
|
|
235
|
+
try {
|
|
236
|
+
return estimateBytes(key) + ENTRY_OVERHEAD + estimateValue(value, 0, /* @__PURE__ */ new Set());
|
|
237
|
+
} catch {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function estimateBytes(str) {
|
|
242
|
+
return str.length * 2;
|
|
243
|
+
}
|
|
244
|
+
function estimateValue(value, depth, seen) {
|
|
245
|
+
switch (typeof value) {
|
|
246
|
+
case "string": return estimateBytes(value);
|
|
247
|
+
case "number":
|
|
248
|
+
case "bigint": return 8;
|
|
249
|
+
case "boolean": return 4;
|
|
250
|
+
case "object": break;
|
|
251
|
+
default: return 0;
|
|
252
|
+
}
|
|
253
|
+
if (value === null || seen.has(value) || depth >= MAX_ESTIMATE_DEPTH) return 0;
|
|
254
|
+
seen.add(value);
|
|
255
|
+
if (ArrayBuffer.isView(value)) {
|
|
256
|
+
const buffer = value.buffer;
|
|
257
|
+
if (seen.has(buffer)) return 0;
|
|
258
|
+
seen.add(buffer);
|
|
259
|
+
return buffer.byteLength;
|
|
260
|
+
}
|
|
261
|
+
if (isBuffer(value)) return value.byteLength;
|
|
262
|
+
const next = depth + 1;
|
|
263
|
+
let total = 0;
|
|
264
|
+
if (Array.isArray(value) || value instanceof Set) for (const item of value) total += PROPERTY_OVERHEAD + estimateValue(item, next, seen);
|
|
265
|
+
else if (value instanceof Map) for (const [k, v] of value) total += PROPERTY_OVERHEAD + estimateValue(k, next, seen) + estimateValue(v, next, seen);
|
|
266
|
+
else for (const key of Object.keys(value)) total += PROPERTY_OVERHEAD + estimateBytes(key) + estimateValue(value[key], next, seen);
|
|
267
|
+
return total;
|
|
268
|
+
}
|
|
269
|
+
function isBuffer(value) {
|
|
270
|
+
return value instanceof ArrayBuffer || SharedBuffer !== void 0 && value instanceof SharedBuffer;
|
|
271
|
+
}
|
|
272
|
+
function clearTimer(timers, key) {
|
|
208
273
|
const existing = timers.get(key);
|
|
209
274
|
if (existing !== void 0) {
|
|
210
275
|
clearTimeout(existing);
|
|
211
276
|
timers.delete(key);
|
|
212
277
|
}
|
|
213
278
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
279
|
+
function resolveStorage(...optsList) {
|
|
280
|
+
const configured = optsList[0]?.storage;
|
|
281
|
+
const storage = (typeof configured === "function" ? configured() : configured) ?? createMemoryStorage();
|
|
282
|
+
for (const opts of optsList) if (opts) opts.storage = storage;
|
|
283
|
+
return storage;
|
|
218
284
|
}
|
|
219
|
-
function defaultCacheOptions
|
|
285
|
+
function defaultCacheOptions() {
|
|
220
286
|
return {
|
|
221
287
|
name: "_",
|
|
222
288
|
base: "/cache",
|
|
223
|
-
swr:
|
|
289
|
+
swr: false,
|
|
224
290
|
maxAge: 1
|
|
225
291
|
};
|
|
226
292
|
}
|
|
293
|
+
const DEFAULT_MAX_RESOLVE_TIME = 30;
|
|
294
|
+
let fences;
|
|
295
|
+
let resolveSignals;
|
|
296
|
+
let resolveStatuses;
|
|
297
|
+
function fencePending(cachedFn, key) {
|
|
298
|
+
return fences?.get(cachedFn)?.(key);
|
|
299
|
+
}
|
|
227
300
|
function defineCachedFunction(fn, opts = {}) {
|
|
301
|
+
const name = resolveName(opts.name, fn);
|
|
302
|
+
const _optsRef = opts;
|
|
228
303
|
opts = {
|
|
229
|
-
...defaultCacheOptions
|
|
230
|
-
...opts
|
|
304
|
+
...defaultCacheOptions(),
|
|
305
|
+
...definedOptions(opts),
|
|
306
|
+
name
|
|
307
|
+
};
|
|
308
|
+
const getStorage = () => resolveStorage(_optsRef, opts);
|
|
309
|
+
const pending = /* @__PURE__ */ new Map();
|
|
310
|
+
const releasePending = (key, current) => {
|
|
311
|
+
if (pending.get(key) === current) pending.delete(key);
|
|
312
|
+
};
|
|
313
|
+
const writes = /* @__PURE__ */ new Map();
|
|
314
|
+
const trackWrite = (key, write) => {
|
|
315
|
+
const earlier = writes.get(key);
|
|
316
|
+
const tracked = earlier ? earlier.then(() => write) : write;
|
|
317
|
+
writes.set(key, tracked);
|
|
318
|
+
tracked.then(() => {
|
|
319
|
+
if (writes.get(key) === tracked) writes.delete(key);
|
|
320
|
+
});
|
|
321
|
+
return tracked;
|
|
231
322
|
};
|
|
232
|
-
const pending = {};
|
|
233
323
|
const group = opts.group || "functions";
|
|
234
|
-
const
|
|
235
|
-
const integrity = opts.integrity || hash([fn, _integrityOpts$1(opts)]);
|
|
324
|
+
const integrity = opts.integrity || hash([fn, integrityOpts$1(opts)]);
|
|
236
325
|
const validate = opts.validate || ((entry) => entry.value !== void 0);
|
|
237
|
-
const
|
|
326
|
+
const rawMaxResolveTime = opts.maxResolveTime ?? DEFAULT_MAX_RESOLVE_TIME;
|
|
327
|
+
const maxResolveTime = Number.isFinite(rawMaxResolveTime) && rawMaxResolveTime > 0 ? rawMaxResolveTime : void 0;
|
|
328
|
+
const onError = (context, error) => {
|
|
238
329
|
if (opts.onError) opts.onError(error);
|
|
239
330
|
else console.error(context, error);
|
|
240
331
|
};
|
|
241
|
-
async function get(key, resolver, shouldInvalidateCache, event) {
|
|
242
|
-
const
|
|
332
|
+
async function get(key, resolver, args, shouldInvalidateCache, event) {
|
|
333
|
+
const validateCtx = { args };
|
|
334
|
+
const waitUntil = (promise) => {
|
|
335
|
+
if (opts.waitUntil) opts.waitUntil(promise);
|
|
336
|
+
else event?.req.waitUntil?.(promise);
|
|
337
|
+
};
|
|
338
|
+
const bases = normalizeBases(opts.base);
|
|
243
339
|
let entry = {};
|
|
244
340
|
let hitIndex = -1;
|
|
245
341
|
try {
|
|
246
342
|
for (let i = 0; i < bases.length; i++) {
|
|
247
|
-
const result = await
|
|
343
|
+
const result = await getStorage().get(buildCacheKey(key, {
|
|
248
344
|
group,
|
|
249
345
|
name
|
|
250
346
|
}, bases[i]));
|
|
@@ -255,82 +351,144 @@ function defineCachedFunction(fn, opts = {}) {
|
|
|
255
351
|
}
|
|
256
352
|
}
|
|
257
353
|
} catch (error) {
|
|
258
|
-
|
|
354
|
+
onError("[cache] Cache read error.", error);
|
|
259
355
|
}
|
|
260
356
|
if (typeof entry !== "object") {
|
|
261
357
|
entry = {};
|
|
262
|
-
|
|
358
|
+
const error = malformedEntryError();
|
|
359
|
+
onError("[cache]", error);
|
|
360
|
+
} else {
|
|
361
|
+
entry = { ...entry };
|
|
362
|
+
decodeBinary(entry);
|
|
363
|
+
entry.payload = void 0;
|
|
263
364
|
}
|
|
264
|
-
const
|
|
365
|
+
const readMaxAge = entry.maxAge ?? opts.maxAge;
|
|
366
|
+
const readStaleMaxAge = entry.staleMaxAge ?? opts.staleMaxAge;
|
|
367
|
+
const ttl = (readMaxAge ?? 0) * 1e3;
|
|
265
368
|
if (ttl > 0) entry.expires = Date.now() + ttl;
|
|
266
|
-
const staleTtl = opts.swr &&
|
|
267
|
-
const
|
|
268
|
-
const
|
|
369
|
+
const staleTtl = opts.swr && readStaleMaxAge != null && readStaleMaxAge >= 0 ? readStaleMaxAge * 1e3 : void 0;
|
|
370
|
+
const swr = opts.swr && staleTtl !== 0;
|
|
371
|
+
const isFullyExpired = staleTtl !== void 0 && readMaxAge != null && Date.now() - (entry.mtime || 0) > ttl + staleTtl;
|
|
372
|
+
const _isValid = await validate(entry, validateCtx) !== false;
|
|
373
|
+
const isMatched = entry.integrity === integrity;
|
|
374
|
+
const expired = shouldInvalidateCache || entry.stale === true || !isMatched || readMaxAge === 0 || ttl > 0 && Date.now() - (entry.mtime || 0) > ttl || !_isValid;
|
|
269
375
|
if (isFullyExpired) {
|
|
270
376
|
entry.value = void 0;
|
|
271
377
|
entry.integrity = void 0;
|
|
272
378
|
entry.mtime = void 0;
|
|
273
379
|
entry.expires = void 0;
|
|
274
380
|
}
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
381
|
+
const status = entry.value === void 0 ? "miss" : !expired ? "hit" : swr && _isValid && isMatched ? "stale" : "revalidated";
|
|
382
|
+
const resolveEntry = async () => {
|
|
383
|
+
let current = pending.get(key);
|
|
384
|
+
const isPending = current !== void 0;
|
|
385
|
+
if (!current) {
|
|
278
386
|
if (entry.value !== void 0 && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
|
|
279
387
|
entry.value = void 0;
|
|
280
388
|
entry.integrity = void 0;
|
|
281
389
|
entry.mtime = void 0;
|
|
282
390
|
entry.expires = void 0;
|
|
283
391
|
}
|
|
284
|
-
|
|
392
|
+
const controller = maxResolveTime ? new AbortController() : void 0;
|
|
393
|
+
if (controller && event) (resolveSignals ??= /* @__PURE__ */ new WeakMap()).set(event, controller.signal);
|
|
394
|
+
if (event && status !== "stale") (resolveStatuses ??= /* @__PURE__ */ new WeakMap()).set(event, status);
|
|
395
|
+
const resolution = (async () => {
|
|
396
|
+
const value = await resolver();
|
|
397
|
+
const resolvedEntry = {
|
|
398
|
+
value,
|
|
399
|
+
mtime: Date.now(),
|
|
400
|
+
integrity
|
|
401
|
+
};
|
|
402
|
+
let maxAge;
|
|
403
|
+
let staleMaxAge;
|
|
404
|
+
if (opts.getMaxAge) try {
|
|
405
|
+
const resolved = await opts.getMaxAge(resolvedEntry);
|
|
406
|
+
const dynamic = typeof resolved === "number" ? { maxAge: resolved } : resolved;
|
|
407
|
+
maxAge = clampTtl(dynamic?.maxAge);
|
|
408
|
+
staleMaxAge = clampTtl(dynamic?.staleMaxAge);
|
|
409
|
+
resolvedEntry.maxAge = maxAge;
|
|
410
|
+
resolvedEntry.staleMaxAge = staleMaxAge;
|
|
411
|
+
} catch (error) {
|
|
412
|
+
onError("[cache] getMaxAge hook error.", error);
|
|
413
|
+
}
|
|
414
|
+
return {
|
|
415
|
+
value: normalizeBinary(opts.serialize ? await opts.serialize(resolvedEntry, validateCtx) : value),
|
|
416
|
+
maxAge,
|
|
417
|
+
staleMaxAge
|
|
418
|
+
};
|
|
419
|
+
})();
|
|
420
|
+
current = { promise: maxResolveTime ? withDeadline(resolution, maxResolveTime, controller) : resolution };
|
|
421
|
+
pending.set(key, current);
|
|
285
422
|
}
|
|
423
|
+
let resolved;
|
|
286
424
|
try {
|
|
287
|
-
|
|
425
|
+
resolved = await current.promise;
|
|
288
426
|
} catch (error) {
|
|
289
427
|
if (!isPending) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
428
|
+
releasePending(key, current);
|
|
429
|
+
if (!current.fenced) {
|
|
430
|
+
const evictPromise = evictFromStorage(getStorage(), key, bases, group, name).catch((error) => {
|
|
431
|
+
onError("[cache] Cache eviction error.", error);
|
|
432
|
+
});
|
|
433
|
+
waitUntil(evictPromise);
|
|
434
|
+
}
|
|
295
435
|
}
|
|
296
436
|
throw error;
|
|
297
437
|
}
|
|
438
|
+
entry.value = resolved.value;
|
|
298
439
|
if (!isPending) {
|
|
299
440
|
entry.mtime = Date.now();
|
|
300
441
|
entry.integrity = integrity;
|
|
301
442
|
entry.stale = void 0;
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
443
|
+
if (opts.getMaxAge) {
|
|
444
|
+
entry.maxAge = resolved.maxAge;
|
|
445
|
+
entry.staleMaxAge = resolved.staleMaxAge;
|
|
446
|
+
}
|
|
447
|
+
const setOpts = storageTtl(entry.maxAge ?? opts.maxAge, entry.staleMaxAge ?? opts.staleMaxAge, opts.swr);
|
|
448
|
+
try {
|
|
449
|
+
const isValid = await validate(entry, validateCtx) !== false;
|
|
450
|
+
if (current.fenced) return;
|
|
451
|
+
if (isValid && setOpts !== false) {
|
|
452
|
+
const writeBases = hitIndex < 0 ? bases : bases.slice(0, hitIndex + 1);
|
|
453
|
+
const { status: _status, ...rest } = entry;
|
|
454
|
+
const toStore = encodeBinary(rest, getStorage());
|
|
455
|
+
const payload = opts.payload ?? (toStore.encoding ? "value" : void 0);
|
|
456
|
+
if (payload) toStore.payload = payload;
|
|
457
|
+
const promise = (async () => {
|
|
458
|
+
try {
|
|
459
|
+
await Promise.all(writeBases.map((b) => getStorage().set(buildCacheKey(key, {
|
|
460
|
+
group,
|
|
461
|
+
name
|
|
462
|
+
}, b), toStore, setOpts)));
|
|
463
|
+
} catch (error) {
|
|
464
|
+
onError("[cache] Cache write error.", error);
|
|
465
|
+
}
|
|
466
|
+
})();
|
|
467
|
+
trackWrite(key, promise);
|
|
468
|
+
waitUntil(promise);
|
|
469
|
+
} else if (hitIndex >= 0) {
|
|
470
|
+
const evictPromise = evictFromStorage(getStorage(), key, bases, group, name).catch((error) => {
|
|
471
|
+
onError("[cache] Cache eviction error.", error);
|
|
472
|
+
});
|
|
473
|
+
waitUntil(evictPromise);
|
|
474
|
+
}
|
|
475
|
+
} finally {
|
|
476
|
+
releasePending(key, current);
|
|
325
477
|
}
|
|
326
478
|
}
|
|
327
479
|
};
|
|
328
|
-
const _resolvePromise = expired ?
|
|
480
|
+
const _resolvePromise = expired ? resolveEntry() : Promise.resolve();
|
|
329
481
|
if (entry.value === void 0) await _resolvePromise;
|
|
330
|
-
else if (expired)
|
|
331
|
-
|
|
482
|
+
else if (expired) waitUntil(_resolvePromise);
|
|
483
|
+
Object.defineProperty(entry, "status", {
|
|
484
|
+
value: status,
|
|
485
|
+
enumerable: false,
|
|
486
|
+
writable: true,
|
|
487
|
+
configurable: true
|
|
488
|
+
});
|
|
489
|
+
if (swr && isMatched && await validate(entry, validateCtx) !== false) {
|
|
332
490
|
_resolvePromise.catch((error) => {
|
|
333
|
-
|
|
491
|
+
onError("[cache] SWR handler error.", error);
|
|
334
492
|
});
|
|
335
493
|
return entry;
|
|
336
494
|
}
|
|
@@ -338,81 +496,170 @@ function defineCachedFunction(fn, opts = {}) {
|
|
|
338
496
|
}
|
|
339
497
|
const cachedFn = async (...args) => {
|
|
340
498
|
if (await opts.shouldBypassCache?.(...args)) return fn(...args);
|
|
341
|
-
const entry = await get(await (opts.getKey || getKey)(...args), () => fn(...args), await opts.shouldInvalidateCache?.(...args), isHTTPEvent(args[0]) ? args[0] : void 0);
|
|
499
|
+
const entry = await get(await (opts.getKey || getKey)(...args), () => fn(...args), args, await opts.shouldInvalidateCache?.(...args), isHTTPEvent(args[0]) ? args[0] : void 0);
|
|
342
500
|
let value = entry.value;
|
|
343
|
-
if (opts.transform) value = await opts.transform(entry, ...args)
|
|
501
|
+
if (opts.transform) value = await opts.transform(entry, ...args) ?? value;
|
|
344
502
|
return value;
|
|
345
503
|
};
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
504
|
+
(fences ??= /* @__PURE__ */ new WeakMap()).set(cachedFn, (key) => {
|
|
505
|
+
const current = pending.get(key);
|
|
506
|
+
if (current) {
|
|
507
|
+
current.fenced = true;
|
|
508
|
+
pending.delete(key);
|
|
509
|
+
}
|
|
510
|
+
return writes.get(key);
|
|
353
511
|
});
|
|
354
|
-
|
|
512
|
+
const purgeOptions = async (args) => {
|
|
513
|
+
getStorage();
|
|
514
|
+
const key = await (opts.getKey || getKey)(...args);
|
|
515
|
+
await fencePending(cachedFn, key);
|
|
516
|
+
return {
|
|
517
|
+
...opts,
|
|
518
|
+
getKey: () => key
|
|
519
|
+
};
|
|
520
|
+
};
|
|
521
|
+
cachedFn.resolveKeys = (...args) => resolveCacheKeys({
|
|
355
522
|
options: opts,
|
|
356
523
|
args
|
|
357
524
|
});
|
|
525
|
+
cachedFn.invalidate = async (...args) => {
|
|
526
|
+
await invalidateCache({ options: await purgeOptions(args) });
|
|
527
|
+
};
|
|
528
|
+
cachedFn.expire = async (...args) => {
|
|
529
|
+
await expireCache({ options: await purgeOptions(args) });
|
|
530
|
+
};
|
|
358
531
|
return cachedFn;
|
|
359
532
|
}
|
|
360
533
|
async function resolveCacheKeys(input = {}) {
|
|
361
534
|
const opts = input.options ?? {};
|
|
362
535
|
const args = input.args ?? [];
|
|
363
536
|
const key = await (opts.getKey || getKey)(...args);
|
|
364
|
-
return
|
|
537
|
+
return normalizeBases(opts.base).map((base) => buildCacheKey(key, opts, base));
|
|
365
538
|
}
|
|
366
539
|
async function invalidateCache(input = {}) {
|
|
367
540
|
const keys = await resolveCacheKeys(input);
|
|
368
|
-
const storage =
|
|
541
|
+
const storage = requireStorage(input.options, "invalidateCache");
|
|
369
542
|
await Promise.all(keys.map((key) => storage.set(key, null)));
|
|
370
543
|
}
|
|
371
544
|
async function expireCache(input = {}) {
|
|
372
545
|
const opts = input.options ?? {};
|
|
373
546
|
const keys = await resolveCacheKeys(input);
|
|
374
|
-
const storage =
|
|
547
|
+
const storage = requireStorage(opts, "expireCache");
|
|
375
548
|
await Promise.all(keys.map(async (key) => {
|
|
376
549
|
const entry = await storage.get(key);
|
|
377
550
|
if (!entry || typeof entry !== "object" || entry.value === void 0) return;
|
|
378
551
|
await storage.set(key, {
|
|
379
552
|
...entry,
|
|
380
553
|
stale: true
|
|
381
|
-
},
|
|
554
|
+
}, remainingTtl(entry, opts));
|
|
382
555
|
}));
|
|
383
556
|
}
|
|
557
|
+
function resolveName(name, fn) {
|
|
558
|
+
return name || fn.name || `anon_${hash(fn).slice(0, 16)}`;
|
|
559
|
+
}
|
|
560
|
+
function definedOptions(opts) {
|
|
561
|
+
const cleaned = { ...opts };
|
|
562
|
+
for (const key of Object.keys(cleaned)) if (cleaned[key] === void 0) delete cleaned[key];
|
|
563
|
+
return cleaned;
|
|
564
|
+
}
|
|
565
|
+
function requireStorage(options, caller) {
|
|
566
|
+
if (!options?.storage) throw storageRequiredError(caller);
|
|
567
|
+
return resolveStorage(options);
|
|
568
|
+
}
|
|
569
|
+
function withDeadline(work, seconds, controller) {
|
|
570
|
+
return new Promise((resolve, reject) => {
|
|
571
|
+
const timer = setTimeout(() => {
|
|
572
|
+
const error = timeoutError(seconds);
|
|
573
|
+
reject(error);
|
|
574
|
+
controller?.abort(error);
|
|
575
|
+
}, seconds * 1e3);
|
|
576
|
+
if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
|
|
577
|
+
work.then((value) => {
|
|
578
|
+
clearTimeout(timer);
|
|
579
|
+
resolve(value);
|
|
580
|
+
}, (error) => {
|
|
581
|
+
clearTimeout(timer);
|
|
582
|
+
reject(error);
|
|
583
|
+
});
|
|
584
|
+
});
|
|
585
|
+
}
|
|
384
586
|
function isHTTPEvent(input) {
|
|
385
587
|
return input?.req instanceof Request;
|
|
386
588
|
}
|
|
589
|
+
function clampTtl(value) {
|
|
590
|
+
return value == null || !Number.isFinite(value) ? void 0 : Math.max(0, value);
|
|
591
|
+
}
|
|
592
|
+
function normalizeBinary(value) {
|
|
593
|
+
if (value instanceof Uint8Array) return value;
|
|
594
|
+
if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
595
|
+
return value instanceof ArrayBuffer ? new Uint8Array(value) : value;
|
|
596
|
+
}
|
|
597
|
+
function encodeBinary(entry, storage) {
|
|
598
|
+
const value = entry.value;
|
|
599
|
+
if (!(value instanceof Uint8Array)) return entry;
|
|
600
|
+
return storage.binary ? {
|
|
601
|
+
...entry,
|
|
602
|
+
encoding: "bytes"
|
|
603
|
+
} : {
|
|
604
|
+
...entry,
|
|
605
|
+
value: bytesToBase64(value),
|
|
606
|
+
encoding: "base64"
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
function decodeBinary(entry) {
|
|
610
|
+
const encoding = entry.encoding;
|
|
611
|
+
if (encoding === void 0) return;
|
|
612
|
+
entry.encoding = void 0;
|
|
613
|
+
if (encoding === "base64" && typeof entry.value === "string") {
|
|
614
|
+
entry.value = base64ToBytes(entry.value);
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
if (encoding === "bytes" && ArrayBuffer.isView(entry.value)) {
|
|
618
|
+
entry.value = normalizeBinary(entry.value);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
entry.value = void 0;
|
|
622
|
+
}
|
|
387
623
|
function getKey(...args) {
|
|
388
624
|
return args.length > 0 ? hash(args) : "";
|
|
389
625
|
}
|
|
390
|
-
function
|
|
626
|
+
function buildCacheKey(key, opts, base) {
|
|
391
627
|
return [
|
|
392
628
|
base,
|
|
393
|
-
opts.group || "functions",
|
|
394
|
-
opts.name || "_",
|
|
629
|
+
escapeKeySegment(opts.group || "functions"),
|
|
630
|
+
escapeKeySegment(opts.name || "_"),
|
|
395
631
|
key + ".json"
|
|
396
632
|
].filter(Boolean).join(":").replace(/:\/$/, ":index");
|
|
397
633
|
}
|
|
398
|
-
function
|
|
634
|
+
function escapeKeySegment(raw) {
|
|
635
|
+
const escaped = escapeKey(raw);
|
|
636
|
+
return escaped === raw ? escaped : `${escaped.slice(0, 64)}.${hash(raw)}`;
|
|
637
|
+
}
|
|
638
|
+
function escapeKey(key) {
|
|
639
|
+
return String(key).replace(/\W/g, "");
|
|
640
|
+
}
|
|
641
|
+
function normalizeBases(base) {
|
|
399
642
|
if (Array.isArray(base)) return base;
|
|
400
643
|
return [base ?? "/cache"];
|
|
401
644
|
}
|
|
402
|
-
async function
|
|
403
|
-
await Promise.all(bases.map((b) =>
|
|
645
|
+
async function evictFromStorage(storage, key, bases, group, name) {
|
|
646
|
+
await Promise.all(bases.map((b) => storage.set(buildCacheKey(key, {
|
|
404
647
|
group,
|
|
405
648
|
name
|
|
406
649
|
}, b), null)));
|
|
407
650
|
}
|
|
408
|
-
function
|
|
409
|
-
if (
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
return { ttl: Math.max(Math.ceil((entry.mtime + ttlWindow * 1e3 - Date.now()) / 1e3), 1) };
|
|
651
|
+
function storageTtl(maxAge, staleMaxAge, swr) {
|
|
652
|
+
if (maxAge == null || maxAge <= 0) return false;
|
|
653
|
+
if (!swr) return { ttl: maxAge };
|
|
654
|
+
return staleMaxAge != null && staleMaxAge >= 0 ? { ttl: maxAge + staleMaxAge } : void 0;
|
|
413
655
|
}
|
|
414
|
-
function
|
|
415
|
-
const
|
|
656
|
+
function remainingTtl(entry, opts) {
|
|
657
|
+
const ttlOpts = storageTtl(entry.maxAge ?? opts.maxAge, entry.staleMaxAge ?? opts.staleMaxAge, opts.swr);
|
|
658
|
+
if (!entry.mtime || !ttlOpts) return;
|
|
659
|
+
return { ttl: Math.max(Math.ceil((entry.mtime + ttlOpts.ttl * 1e3 - Date.now()) / 1e3), 1) };
|
|
660
|
+
}
|
|
661
|
+
function integrityOpts$1(opts) {
|
|
662
|
+
const { base: _, group: _g, name: _n, storage: _s, waitUntil: _w, ...rest } = opts;
|
|
416
663
|
return rest;
|
|
417
664
|
}
|
|
418
665
|
//#endregion
|
|
@@ -428,10 +675,15 @@ function parseGitHubArchive(bytes) {
|
|
|
428
675
|
const name = readTarString(header, 0, 100);
|
|
429
676
|
const prefix = readTarString(header, 345, 155);
|
|
430
677
|
const path = paxPath || [prefix, name].filter(Boolean).join("/");
|
|
431
|
-
const
|
|
678
|
+
const sizeField = readTarString(header, 124, 12).trim();
|
|
679
|
+
if (sizeField && !/^[0-7]+$/.test(sizeField)) throw new Error("Invalid GitHub archive entry size.");
|
|
680
|
+
const size = sizeField ? Number.parseInt(sizeField, 8) : 0;
|
|
681
|
+
if (!Number.isSafeInteger(size) || size < 0) throw new Error("Invalid GitHub archive entry size.");
|
|
432
682
|
const type = String.fromCharCode(header[156] || 0);
|
|
433
683
|
const contentStart = offset + 512;
|
|
434
684
|
const contentEnd = contentStart + size;
|
|
685
|
+
const entryEnd = contentStart + Math.ceil(size / 512) * 512;
|
|
686
|
+
if (entryEnd > tar.length) throw new Error("Invalid GitHub archive entry size.");
|
|
435
687
|
const content = tar.subarray(contentStart, contentEnd);
|
|
436
688
|
if (type === "x") paxPath = readPaxPath(content);
|
|
437
689
|
else {
|
|
@@ -444,7 +696,7 @@ function parseGitHubArchive(bytes) {
|
|
|
444
696
|
}
|
|
445
697
|
paxPath = void 0;
|
|
446
698
|
}
|
|
447
|
-
offset =
|
|
699
|
+
offset = entryEnd;
|
|
448
700
|
}
|
|
449
701
|
return files;
|
|
450
702
|
}
|
|
@@ -468,9 +720,14 @@ function readPaxPath(content) {
|
|
|
468
720
|
}
|
|
469
721
|
}
|
|
470
722
|
function stripArchiveRoot(path) {
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
723
|
+
try {
|
|
724
|
+
normalizeSafeSourcePath(path);
|
|
725
|
+
const slash = path.indexOf("/");
|
|
726
|
+
if (slash === -1) return;
|
|
727
|
+
return normalizeSafeSourcePath(path.slice(slash + 1));
|
|
728
|
+
} catch {
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
474
731
|
}
|
|
475
732
|
//#endregion
|
|
476
733
|
//#region src/sources/github/cache.ts
|
|
@@ -479,59 +736,129 @@ function normalizeGitHubCache(options) {
|
|
|
479
736
|
if (options.cache && typeof options.cache === "object") return { maxAge: options.cache.maxAge };
|
|
480
737
|
}
|
|
481
738
|
function createGitHubCacheKey(input) {
|
|
482
|
-
return [
|
|
739
|
+
return JSON.stringify([
|
|
483
740
|
input.kind,
|
|
484
741
|
input.repo,
|
|
485
742
|
input.ref,
|
|
486
743
|
input.root,
|
|
487
|
-
|
|
488
|
-
|
|
744
|
+
input.include ?? null,
|
|
745
|
+
input.ignore ?? null,
|
|
489
746
|
input.authScope,
|
|
490
747
|
input.key || ""
|
|
491
|
-
]
|
|
748
|
+
]);
|
|
492
749
|
}
|
|
493
750
|
function githubAuthenticationScope(token) {
|
|
494
751
|
return token ? createHash("sha256").update(token).digest("hex") : "anonymous";
|
|
495
752
|
}
|
|
496
|
-
function normalizePatternCacheKey(value) {
|
|
497
|
-
if (!value) return "";
|
|
498
|
-
return Array.isArray(value) ? value.join(",") : String(value);
|
|
499
|
-
}
|
|
500
753
|
//#endregion
|
|
501
754
|
//#region src/sources/github/client.ts
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
accept: "application/vnd.github+json",
|
|
506
|
-
...input.token ? { authorization: `Bearer ${input.token}` } : {},
|
|
507
|
-
"user-agent": "vitehub-source",
|
|
508
|
-
"x-github-api-version": "2022-11-28"
|
|
509
|
-
},
|
|
510
|
-
signal: input.signal
|
|
511
|
-
});
|
|
512
|
-
if (!response.ok) {
|
|
513
|
-
if (response.status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) could not access the repository or ref ${JSON.stringify(input.ref)}. Check that the repo exists, the ref exists, and auth can access it.`);
|
|
514
|
-
throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) request failed with ${response.status} for ${input.url}.`);
|
|
515
|
-
}
|
|
516
|
-
return await response.json();
|
|
755
|
+
/** The Server Env token: `VITEHUB_GITHUB_TOKEN`, then `FORGES_GITHUB_TOKEN`. */
|
|
756
|
+
function githubEnvToken() {
|
|
757
|
+
return readForgeEnv(forgeEnv.github.token);
|
|
517
758
|
}
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
759
|
+
/** The HTTP status of the Forge request behind a GitHub Source error. */
|
|
760
|
+
function githubErrorStatus(error) {
|
|
761
|
+
return error instanceof Error ? forgeErrorStatus(error.cause) : void 0;
|
|
762
|
+
}
|
|
763
|
+
function isRecord(value) {
|
|
764
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
765
|
+
}
|
|
766
|
+
function isNonEmptyString(value) {
|
|
767
|
+
return typeof value === "string" && value.length > 0;
|
|
768
|
+
}
|
|
769
|
+
function malformed(repo, description) {
|
|
770
|
+
return sourceError(`[vitehub] github(${JSON.stringify(repo)}) returned a malformed ${description} response.`);
|
|
771
|
+
}
|
|
772
|
+
function createGitHubClient(repo) {
|
|
773
|
+
const [owner, name, ...rest] = repo.split("/");
|
|
774
|
+
let cached;
|
|
775
|
+
function provider(token) {
|
|
776
|
+
if (!cached || cached.token !== token) cached = {
|
|
777
|
+
provider: forgeProvider({
|
|
778
|
+
forge: "github",
|
|
779
|
+
readOnly: true,
|
|
780
|
+
token,
|
|
781
|
+
userAgent: "vitehub-source"
|
|
782
|
+
}),
|
|
783
|
+
token
|
|
784
|
+
};
|
|
785
|
+
return cached.provider;
|
|
529
786
|
}
|
|
530
|
-
|
|
787
|
+
async function request(ref, description, token, signal, load) {
|
|
788
|
+
if (!owner || !name || rest.length) throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) supports GitHub.com repositories only and expects repo as "owner/name".`);
|
|
789
|
+
const client = await provider(token);
|
|
790
|
+
try {
|
|
791
|
+
return await load(client, {
|
|
792
|
+
forge: client.forge,
|
|
793
|
+
instance: client.instance,
|
|
794
|
+
name,
|
|
795
|
+
owner
|
|
796
|
+
});
|
|
797
|
+
} catch (error) {
|
|
798
|
+
if (signal?.aborted) throw error;
|
|
799
|
+
const status = forgeErrorStatus(error);
|
|
800
|
+
if (status === void 0) throw error;
|
|
801
|
+
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 });
|
|
802
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) ${description} request failed with ${status}.`, { cause: error });
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return {
|
|
806
|
+
async archive(ref, token, signal) {
|
|
807
|
+
const download = (archiveToken) => request(ref, "archive", archiveToken, signal, async (client, repoRef) => {
|
|
808
|
+
const stream = await forgeArchive(client, repoRef, {
|
|
809
|
+
ref,
|
|
810
|
+
signal
|
|
811
|
+
});
|
|
812
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
813
|
+
});
|
|
814
|
+
try {
|
|
815
|
+
return await download(token);
|
|
816
|
+
} catch (error) {
|
|
817
|
+
const status = githubErrorStatus(error);
|
|
818
|
+
if (!token || status !== 403 && status !== 429) throw error;
|
|
819
|
+
return await download(void 0);
|
|
820
|
+
}
|
|
821
|
+
},
|
|
822
|
+
async defaultBranch(token, signal) {
|
|
823
|
+
const branch = await request("default", "repository", token, signal, async (client, repoRef) => (await client.repos.get(repoRef, { signal })).defaultBranch);
|
|
824
|
+
if (!branch) throw malformed(repo, "repository");
|
|
825
|
+
return branch;
|
|
826
|
+
},
|
|
827
|
+
async file(path, ref, token, signal) {
|
|
828
|
+
try {
|
|
829
|
+
const file = await request(ref, "content", token, signal, async (client, repoRef) => await client.contents.getFile(repoRef, path, {
|
|
830
|
+
ref,
|
|
831
|
+
signal
|
|
832
|
+
}));
|
|
833
|
+
if (file.encoding !== "binary") throw malformed(repo, "content");
|
|
834
|
+
return {
|
|
835
|
+
content: file.content,
|
|
836
|
+
sha: file.sha
|
|
837
|
+
};
|
|
838
|
+
} catch (error) {
|
|
839
|
+
if (githubErrorStatus(error) !== 422) throw error;
|
|
840
|
+
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 });
|
|
841
|
+
}
|
|
842
|
+
},
|
|
843
|
+
async metadata(path, ref, token, signal) {
|
|
844
|
+
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("/")}`, {
|
|
845
|
+
query: { ref },
|
|
846
|
+
signal
|
|
847
|
+
})).data);
|
|
848
|
+
if (Array.isArray(entry)) return;
|
|
849
|
+
if (!isRecord(entry) || !isNonEmptyString(entry.type) || !isNonEmptyString(entry.sha)) throw malformed(repo, "content");
|
|
850
|
+
return entry.type === "file" ? { sha: entry.sha } : void 0;
|
|
851
|
+
},
|
|
852
|
+
async resolveCommit(ref, token, signal) {
|
|
853
|
+
const sha = await request(ref, "commit", token, signal, async (client, repoRef) => await client.contents.resolveRef(repoRef, ref, { signal }));
|
|
854
|
+
if (typeof sha !== "string" || !sha) throw malformed(repo, "commit");
|
|
855
|
+
return sha;
|
|
856
|
+
}
|
|
857
|
+
};
|
|
531
858
|
}
|
|
532
859
|
//#endregion
|
|
533
860
|
//#region src/sources/github/git.ts
|
|
534
|
-
function createGitEnv(home,
|
|
861
|
+
function createGitEnv(home, credentials, baseEnv = process.env) {
|
|
535
862
|
const env = { ...baseEnv };
|
|
536
863
|
for (const key of [
|
|
537
864
|
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
@@ -551,10 +878,11 @@ function createGitEnv(home, token, baseEnv = process.env) {
|
|
|
551
878
|
"GIT_WORK_TREE"
|
|
552
879
|
]) delete env[key];
|
|
553
880
|
for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(key)) delete env[key];
|
|
881
|
+
const authHeader = forgeGitAuthHeader(credentials);
|
|
554
882
|
Object.assign(env, {
|
|
555
883
|
GCM_INTERACTIVE: "Never",
|
|
556
884
|
GIT_ASKPASS: "",
|
|
557
|
-
GIT_CONFIG_COUNT:
|
|
885
|
+
GIT_CONFIG_COUNT: authHeader ? "1" : "0",
|
|
558
886
|
GIT_CONFIG_GLOBAL: devNull,
|
|
559
887
|
GIT_CONFIG_NOSYSTEM: "1",
|
|
560
888
|
GIT_TERMINAL_PROMPT: "0",
|
|
@@ -563,10 +891,9 @@ function createGitEnv(home, token, baseEnv = process.env) {
|
|
|
563
891
|
USERPROFILE: home,
|
|
564
892
|
XDG_CONFIG_HOME: home
|
|
565
893
|
});
|
|
566
|
-
if (!
|
|
567
|
-
|
|
568
|
-
env.
|
|
569
|
-
env.GIT_CONFIG_VALUE_0 = `AUTHORIZATION: basic ${credential}`;
|
|
894
|
+
if (!authHeader) return env;
|
|
895
|
+
env.GIT_CONFIG_KEY_0 = authHeader.key;
|
|
896
|
+
env.GIT_CONFIG_VALUE_0 = authHeader.value;
|
|
570
897
|
return env;
|
|
571
898
|
}
|
|
572
899
|
async function runGit(args, options = {}) {
|
|
@@ -593,7 +920,7 @@ async function runGit(args, options = {}) {
|
|
|
593
920
|
return;
|
|
594
921
|
}
|
|
595
922
|
const command = args[0] === "-C" ? args[2] : args[0];
|
|
596
|
-
reject(
|
|
923
|
+
reject(sourceErrorDiagnostics.SOURCE_R0019({ message: `git ${command || "command"} exited with ${code ?? "an unknown status"}.` }));
|
|
597
924
|
});
|
|
598
925
|
});
|
|
599
926
|
}
|
|
@@ -611,7 +938,7 @@ function getGitSparsePatterns(root, include) {
|
|
|
611
938
|
return root && isGitSparsePattern(root) ? [`${root}/**`] : void 0;
|
|
612
939
|
}
|
|
613
940
|
function isGitLfsPointer(content) {
|
|
614
|
-
if (content.byteLength >
|
|
941
|
+
if (content.byteLength > 65536) return false;
|
|
615
942
|
const lines = Buffer.from(content).toString("utf8").split(/\r?\n/);
|
|
616
943
|
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));
|
|
617
944
|
}
|
|
@@ -632,7 +959,7 @@ async function readGitArchiveFiles(dir, input, executeGit, options) {
|
|
|
632
959
|
return parseGitHubArchive(Buffer.from(archive)).map((entry) => {
|
|
633
960
|
const key = input.keyForRepoPath(entry.path);
|
|
634
961
|
if (!key || !input.shouldInclude(key)) return;
|
|
635
|
-
if (isGitLfsPointer(entry.content)) throw
|
|
962
|
+
if (isGitLfsPointer(entry.content)) throw sourceErrorDiagnostics.SOURCE_R0020({ message: "git archive contained a Git LFS pointer; use the GitHub archive instead." });
|
|
636
963
|
return {
|
|
637
964
|
content: entry.content,
|
|
638
965
|
key,
|
|
@@ -651,7 +978,7 @@ async function loadGitArchiveFiles(input, executeGit = runGit) {
|
|
|
651
978
|
const dir = await mkdtemp(join(tmpdir(), "vitehub-github-"));
|
|
652
979
|
try {
|
|
653
980
|
const options = {
|
|
654
|
-
env: createGitEnv(dir, input.
|
|
981
|
+
env: createGitEnv(dir, input.credentials, input.env),
|
|
655
982
|
signal: input.signal
|
|
656
983
|
};
|
|
657
984
|
await executeGit([
|
|
@@ -665,7 +992,7 @@ async function loadGitArchiveFiles(input, executeGit = runGit) {
|
|
|
665
992
|
"remote",
|
|
666
993
|
"add",
|
|
667
994
|
"origin",
|
|
668
|
-
input.
|
|
995
|
+
input.credentials.url
|
|
669
996
|
], options);
|
|
670
997
|
await executeGit([
|
|
671
998
|
"-C",
|
|
@@ -712,7 +1039,11 @@ async function loadGitArchiveFiles(input, executeGit = runGit) {
|
|
|
712
1039
|
//#endregion
|
|
713
1040
|
//#region src/sources/github/index.ts
|
|
714
1041
|
function normalizeGitHubRoot(path = "") {
|
|
715
|
-
|
|
1042
|
+
const root = path.replace(/\\/g, "/").split("/").filter((part) => part !== ".").join("/");
|
|
1043
|
+
return normalizeSafeSourcePath(root, {
|
|
1044
|
+
allowEmpty: true,
|
|
1045
|
+
allowReserved: true
|
|
1046
|
+
}).split("/").filter(Boolean).join("/");
|
|
716
1047
|
}
|
|
717
1048
|
function dedupeProviderPromise(promises, key, load) {
|
|
718
1049
|
const promise = promises.get(key);
|
|
@@ -737,62 +1068,54 @@ function github(options) {
|
|
|
737
1068
|
const configuredRef = options.ref;
|
|
738
1069
|
const root = normalizeGitHubRoot(options.root || "");
|
|
739
1070
|
const sparsePatterns = getGitSparsePatterns(root, options.include);
|
|
740
|
-
let auth;
|
|
741
1071
|
const authByContext = /* @__PURE__ */ new WeakMap();
|
|
742
1072
|
const providerCache = normalizeGitHubCache(options);
|
|
743
|
-
|
|
744
|
-
|
|
1073
|
+
const client = createGitHubClient(options.repo);
|
|
1074
|
+
async function resolveAuth() {
|
|
1075
|
+
if (options.auth === void 0) return githubEnvToken();
|
|
1076
|
+
const token = typeof options.auth === "function" ? await options.auth() : options.auth;
|
|
745
1077
|
return typeof token === "string" && token.length > 0 ? token : void 0;
|
|
746
1078
|
}
|
|
747
|
-
function
|
|
748
|
-
|
|
749
|
-
if (
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
return
|
|
1079
|
+
async function contextAuth(ctx) {
|
|
1080
|
+
let auth = authByContext.get(ctx);
|
|
1081
|
+
if (!auth) {
|
|
1082
|
+
auth = resolveAuth();
|
|
1083
|
+
authByContext.set(ctx, auth);
|
|
1084
|
+
}
|
|
1085
|
+
return await auth;
|
|
754
1086
|
}
|
|
755
1087
|
function keyForRepoPath(path) {
|
|
756
|
-
|
|
1088
|
+
let normalized;
|
|
1089
|
+
try {
|
|
1090
|
+
normalized = normalizeSafeSourcePath(path);
|
|
1091
|
+
} catch {
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
757
1094
|
if (!root) return normalized;
|
|
758
1095
|
if (!normalized.startsWith(`${root}/`)) return void 0;
|
|
759
|
-
|
|
1096
|
+
const key = normalized.slice(root.length + 1);
|
|
1097
|
+
if (!key || key.startsWith("/")) return void 0;
|
|
1098
|
+
return normalizeSafeSourcePath(key);
|
|
760
1099
|
}
|
|
761
1100
|
function repoPathForKey(key) {
|
|
762
1101
|
const normalized = normalizeSourcePath(key);
|
|
763
1102
|
return root ? `${root}/${normalized}` : normalized;
|
|
764
1103
|
}
|
|
765
|
-
function contentsUrl(repoPath, ref) {
|
|
766
|
-
return `https://api.github.com/repos/${options.repo}/contents/${encodeURIComponent(repoPath).replace(/%2F/g, "/")}?ref=${encodeURIComponent(ref)}`;
|
|
767
|
-
}
|
|
768
1104
|
function shouldInclude(key) {
|
|
769
1105
|
if (options.include && !matchesAny(key, options.include)) return false;
|
|
770
1106
|
if (options.ignore && matchesAny(key, options.ignore)) return false;
|
|
771
1107
|
return true;
|
|
772
1108
|
}
|
|
773
|
-
async function resolveRef(token
|
|
1109
|
+
async function resolveRef(token) {
|
|
774
1110
|
if (configuredRef) return configuredRef;
|
|
775
|
-
return (await resolveSourceRevision(token
|
|
1111
|
+
return (await resolveSourceRevision(token)).id;
|
|
776
1112
|
}
|
|
777
|
-
async function resolveSourceRevision(token
|
|
1113
|
+
async function resolveSourceRevision(token, signal) {
|
|
778
1114
|
if (!configuredRef) try {
|
|
779
|
-
const ref =
|
|
780
|
-
ref: "default",
|
|
781
|
-
repo: options.repo,
|
|
782
|
-
signal,
|
|
783
|
-
token,
|
|
784
|
-
url: `https://api.github.com/repos/${options.repo}`
|
|
785
|
-
})).default_branch || "main";
|
|
786
|
-
const commit = await requestGitHubJson({
|
|
787
|
-
ref,
|
|
788
|
-
repo: options.repo,
|
|
789
|
-
signal,
|
|
790
|
-
token,
|
|
791
|
-
url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(ref)}`
|
|
792
|
-
});
|
|
1115
|
+
const ref = await client.defaultBranch(token, signal);
|
|
793
1116
|
return {
|
|
794
|
-
id:
|
|
795
|
-
immutable:
|
|
1117
|
+
id: await client.resolveCommit(ref, token, signal),
|
|
1118
|
+
immutable: true,
|
|
796
1119
|
ref
|
|
797
1120
|
};
|
|
798
1121
|
} catch (error) {
|
|
@@ -804,16 +1127,9 @@ function github(options) {
|
|
|
804
1127
|
throw error;
|
|
805
1128
|
}
|
|
806
1129
|
try {
|
|
807
|
-
const commit = await requestGitHubJson({
|
|
808
|
-
ref: configuredRef,
|
|
809
|
-
repo: options.repo,
|
|
810
|
-
signal,
|
|
811
|
-
token,
|
|
812
|
-
url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(configuredRef)}`
|
|
813
|
-
});
|
|
814
1130
|
return {
|
|
815
|
-
id:
|
|
816
|
-
immutable:
|
|
1131
|
+
id: await client.resolveCommit(configuredRef, token, signal),
|
|
1132
|
+
immutable: true,
|
|
817
1133
|
ref: configuredRef
|
|
818
1134
|
};
|
|
819
1135
|
} catch (error) {
|
|
@@ -826,7 +1142,8 @@ function github(options) {
|
|
|
826
1142
|
}
|
|
827
1143
|
}
|
|
828
1144
|
function shouldResolveMainFallback(error) {
|
|
829
|
-
|
|
1145
|
+
const status = githubErrorStatus(error);
|
|
1146
|
+
return status === 403 || status === 429;
|
|
830
1147
|
}
|
|
831
1148
|
const resolvedRefs = /* @__PURE__ */ new Map();
|
|
832
1149
|
const cachedResolveRef = providerCache ? defineCachedFunction(async (token) => await resolveRef(token), {
|
|
@@ -834,27 +1151,16 @@ function github(options) {
|
|
|
834
1151
|
getKey: (token) => cacheKey("ref", token || ""),
|
|
835
1152
|
name: "github-source-ref"
|
|
836
1153
|
}) : (token) => dedupeProviderPromise(resolvedRefs, cacheKey("ref", token || ""), () => resolveRef(token));
|
|
837
|
-
async function getRef(token
|
|
1154
|
+
async function getRef(token, signal) {
|
|
838
1155
|
return await waitForCachedGitHubResult(() => cachedResolveRef(token), signal);
|
|
839
1156
|
}
|
|
840
|
-
async function validateConfiguredRef(token
|
|
1157
|
+
async function validateConfiguredRef(token) {
|
|
841
1158
|
if (!configuredRef) return;
|
|
842
|
-
await
|
|
843
|
-
ref: configuredRef,
|
|
844
|
-
repo: options.repo,
|
|
845
|
-
signal,
|
|
846
|
-
token,
|
|
847
|
-
url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(configuredRef)}`
|
|
848
|
-
});
|
|
1159
|
+
await client.resolveCommit(configuredRef, token);
|
|
849
1160
|
}
|
|
850
|
-
async function loadArchiveFiles(token
|
|
851
|
-
const ref = resolvedRef ?? await getRef(token
|
|
852
|
-
return parseGitHubArchive(await
|
|
853
|
-
ref,
|
|
854
|
-
repo: options.repo,
|
|
855
|
-
signal,
|
|
856
|
-
token
|
|
857
|
-
})).map((entry) => {
|
|
1161
|
+
async function loadArchiveFiles(token, resolvedRef) {
|
|
1162
|
+
const ref = resolvedRef ?? await getRef(token);
|
|
1163
|
+
return parseGitHubArchive(await client.archive(ref, token)).map((entry) => {
|
|
858
1164
|
const key = keyForRepoPath(entry.path);
|
|
859
1165
|
if (!key || !shouldInclude(key)) return void 0;
|
|
860
1166
|
return {
|
|
@@ -866,102 +1172,98 @@ function github(options) {
|
|
|
866
1172
|
};
|
|
867
1173
|
}).filter((file) => Boolean(file));
|
|
868
1174
|
}
|
|
869
|
-
async function loadFiles(token
|
|
870
|
-
const ref = resolvedRef ?? await getRef(token
|
|
1175
|
+
async function loadFiles(token, resolvedRef) {
|
|
1176
|
+
const ref = resolvedRef ?? await getRef(token);
|
|
871
1177
|
if (sparsePatterns) try {
|
|
872
1178
|
return await loadGitArchiveFiles({
|
|
1179
|
+
credentials: forgeGitCredentials({
|
|
1180
|
+
forge: "github",
|
|
1181
|
+
repository: options.repo,
|
|
1182
|
+
token
|
|
1183
|
+
}),
|
|
873
1184
|
keyForRepoPath,
|
|
874
1185
|
ref,
|
|
875
|
-
repo: options.repo,
|
|
876
1186
|
shouldInclude,
|
|
877
|
-
signal,
|
|
878
|
-
sparsePatterns
|
|
879
|
-
token
|
|
1187
|
+
signal: void 0,
|
|
1188
|
+
sparsePatterns
|
|
880
1189
|
});
|
|
881
|
-
} catch
|
|
882
|
-
|
|
883
|
-
}
|
|
884
|
-
return await loadArchiveFiles(token, signal, ref);
|
|
1190
|
+
} catch {}
|
|
1191
|
+
return await loadArchiveFiles(token, ref);
|
|
885
1192
|
}
|
|
886
1193
|
const loadedFiles = /* @__PURE__ */ new Map();
|
|
887
|
-
const cachedLoadFiles = providerCache ? defineCachedFunction(async (resolvedRef, token) => await loadFiles(token,
|
|
1194
|
+
const cachedLoadFiles = providerCache ? defineCachedFunction(async (resolvedRef, token) => await loadFiles(token, resolvedRef), {
|
|
888
1195
|
...providerCache,
|
|
889
1196
|
getKey: (resolvedRef, token) => cacheKey("archive", token, "", resolvedRef),
|
|
890
1197
|
name: "github-source-archive"
|
|
891
|
-
}) : (resolvedRef, token) => dedupeProviderPromise(loadedFiles, cacheKey("archive", token, "", resolvedRef), () => loadFiles(token,
|
|
892
|
-
function getFiles(token
|
|
1198
|
+
}) : (resolvedRef, token) => dedupeProviderPromise(loadedFiles, cacheKey("archive", token, "", resolvedRef), () => loadFiles(token, resolvedRef));
|
|
1199
|
+
function getFiles(token, signal, resolvedRef) {
|
|
893
1200
|
return waitForCachedGitHubResult(() => cachedLoadFiles(resolvedRef, token), signal);
|
|
894
1201
|
}
|
|
895
|
-
async function loadFileMetadata(key, token
|
|
896
|
-
|
|
1202
|
+
async function loadFileMetadata(key, token, resolvedRef) {
|
|
1203
|
+
let normalizedKey;
|
|
1204
|
+
try {
|
|
1205
|
+
normalizedKey = normalizeSafeSourcePath(key);
|
|
1206
|
+
} catch {
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
897
1209
|
if (!normalizedKey || !shouldInclude(normalizedKey)) return;
|
|
898
|
-
const ref = resolvedRef ?? await getRef(token
|
|
1210
|
+
const ref = resolvedRef ?? await getRef(token);
|
|
899
1211
|
const repoPath = repoPathForKey(normalizedKey);
|
|
900
1212
|
let file;
|
|
901
1213
|
try {
|
|
902
|
-
file = await
|
|
903
|
-
ref,
|
|
904
|
-
repo: options.repo,
|
|
905
|
-
signal,
|
|
906
|
-
token,
|
|
907
|
-
url: contentsUrl(repoPath, ref)
|
|
908
|
-
});
|
|
1214
|
+
file = await client.metadata(repoPath, ref, token);
|
|
909
1215
|
} catch (error) {
|
|
910
1216
|
if (isGitHubAccessError(error)) {
|
|
911
|
-
await validateConfiguredRef(token
|
|
1217
|
+
await validateConfiguredRef(token);
|
|
912
1218
|
return;
|
|
913
1219
|
}
|
|
914
|
-
if (shouldResolveMainFallback(error)) return (
|
|
1220
|
+
if (shouldResolveMainFallback(error)) return (await getFiles(token, void 0, ref)).find((file) => file.key === normalizedKey);
|
|
915
1221
|
throw error;
|
|
916
1222
|
}
|
|
917
|
-
if (!file
|
|
918
|
-
if (file.type === "dir") return;
|
|
1223
|
+
if (!file) return;
|
|
919
1224
|
return {
|
|
920
1225
|
key: normalizedKey,
|
|
921
1226
|
path: normalizedKey,
|
|
922
1227
|
ref,
|
|
923
|
-
sha: file.sha
|
|
1228
|
+
sha: file.sha
|
|
924
1229
|
};
|
|
925
1230
|
}
|
|
926
1231
|
const loadedFileMetadata = /* @__PURE__ */ new Map();
|
|
927
|
-
const cachedLoadFileMetadata = providerCache ? defineCachedFunction(async (key, resolvedRef, token) => await loadFileMetadata(key, token,
|
|
1232
|
+
const cachedLoadFileMetadata = providerCache ? defineCachedFunction(async (key, resolvedRef, token) => await loadFileMetadata(key, token, resolvedRef), {
|
|
928
1233
|
...providerCache,
|
|
929
1234
|
getKey: (key, resolvedRef, token) => cacheKey("metadata", token, key, resolvedRef),
|
|
930
1235
|
name: "github-source-metadata"
|
|
931
|
-
}) : (key, resolvedRef, token) => dedupeProviderPromise(loadedFileMetadata, cacheKey("metadata", token, key, resolvedRef), () => loadFileMetadata(key, token,
|
|
1236
|
+
}) : (key, resolvedRef, token) => dedupeProviderPromise(loadedFileMetadata, cacheKey("metadata", token, key, resolvedRef), () => loadFileMetadata(key, token, resolvedRef));
|
|
932
1237
|
function isGitHubAccessError(error) {
|
|
933
|
-
return
|
|
1238
|
+
return githubErrorStatus(error) === 404;
|
|
934
1239
|
}
|
|
935
|
-
async function loadFile(key, token
|
|
936
|
-
|
|
1240
|
+
async function loadFile(key, token, signal, resolvedRef) {
|
|
1241
|
+
let normalizedKey;
|
|
1242
|
+
try {
|
|
1243
|
+
normalizedKey = normalizeSafeSourcePath(key);
|
|
1244
|
+
} catch {
|
|
1245
|
+
throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
1246
|
+
}
|
|
937
1247
|
if (!normalizedKey || !shouldInclude(normalizedKey)) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
938
1248
|
const ref = resolvedRef ?? await getRef(token, signal);
|
|
939
1249
|
const repoPath = repoPathForKey(normalizedKey);
|
|
940
|
-
const file = await
|
|
941
|
-
ref,
|
|
942
|
-
repo: options.repo,
|
|
943
|
-
signal,
|
|
944
|
-
token,
|
|
945
|
-
url: contentsUrl(repoPath, ref)
|
|
946
|
-
});
|
|
947
|
-
if (Array.isArray(file) || file.type === "dir") throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) expected ${JSON.stringify(key)} to be a file, but it is a directory.`);
|
|
948
|
-
if (file.encoding !== "base64" || typeof file.content !== "string") throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include file content for ${JSON.stringify(key)}.`);
|
|
1250
|
+
const file = await client.file(repoPath, ref, token, signal);
|
|
949
1251
|
return {
|
|
950
|
-
content:
|
|
1252
|
+
content: file.content,
|
|
951
1253
|
key: normalizedKey,
|
|
952
1254
|
path: normalizedKey,
|
|
953
1255
|
ref,
|
|
954
1256
|
sha: file.sha || ref
|
|
955
1257
|
};
|
|
956
1258
|
}
|
|
957
|
-
async function getFile(key, ctx, token
|
|
1259
|
+
async function getFile(key, ctx, token) {
|
|
958
1260
|
if (ctx?.abortSignal) return await loadFile(key, token, ctx.abortSignal, ctx.revision?.id);
|
|
959
1261
|
const file = (await getFiles(token, void 0, ctx?.revision?.id)).find((file) => file.key === key);
|
|
960
1262
|
if (!file) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
961
1263
|
return file;
|
|
962
1264
|
}
|
|
963
1265
|
function fetchContent(key, file) {
|
|
964
|
-
if (file.content) return
|
|
1266
|
+
if (file.content) return file.content;
|
|
965
1267
|
throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include archive content for ${JSON.stringify(key)}.`);
|
|
966
1268
|
}
|
|
967
1269
|
function cacheKey(kind, token, key = "", resolvedRef) {
|
|
@@ -987,27 +1289,24 @@ function github(options) {
|
|
|
987
1289
|
},
|
|
988
1290
|
name: "github",
|
|
989
1291
|
async resolveRevision(ctx) {
|
|
990
|
-
|
|
991
|
-
authByContext.set(ctx, token);
|
|
992
|
-
return await resolveSourceRevision(token, ctx.abortSignal);
|
|
1292
|
+
return await resolveSourceRevision(await contextAuth(ctx), ctx.abortSignal);
|
|
993
1293
|
},
|
|
994
1294
|
async getKeys(ctx) {
|
|
995
|
-
return (await getFiles(contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => file.key);
|
|
1295
|
+
return (await getFiles(await contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => file.key);
|
|
996
1296
|
},
|
|
997
1297
|
async getItems(ctx) {
|
|
998
|
-
|
|
999
|
-
return await Promise.all((await getFiles(token, ctx.abortSignal, ctx.revision?.id)).map(async (file) => ({
|
|
1298
|
+
return (await getFiles(await contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => ({
|
|
1000
1299
|
key: file.key,
|
|
1001
1300
|
path: file.path,
|
|
1002
|
-
content:
|
|
1301
|
+
content: fetchContent(file.key, file),
|
|
1003
1302
|
metadata: {
|
|
1004
1303
|
ref: file.ref,
|
|
1005
1304
|
sha: file.sha
|
|
1006
1305
|
}
|
|
1007
|
-
}))
|
|
1306
|
+
}));
|
|
1008
1307
|
},
|
|
1009
1308
|
async getMeta(key, ctx) {
|
|
1010
|
-
const token = contextAuth(ctx);
|
|
1309
|
+
const token = await contextAuth(ctx);
|
|
1011
1310
|
const file = await waitForCachedGitHubResult(() => cachedLoadFileMetadata(key, ctx.revision?.id, token), ctx?.abortSignal);
|
|
1012
1311
|
if (!file) return;
|
|
1013
1312
|
return {
|
|
@@ -1016,11 +1315,11 @@ function github(options) {
|
|
|
1016
1315
|
};
|
|
1017
1316
|
},
|
|
1018
1317
|
async getItem(key, ctx) {
|
|
1019
|
-
const file = await getFile(key, ctx, contextAuth(ctx));
|
|
1318
|
+
const file = await getFile(key, ctx, await contextAuth(ctx));
|
|
1020
1319
|
return {
|
|
1021
1320
|
key: file.key,
|
|
1022
1321
|
path: file.path,
|
|
1023
|
-
content:
|
|
1322
|
+
content: fetchContent(key, file),
|
|
1024
1323
|
metadata: {
|
|
1025
1324
|
ref: file.ref,
|
|
1026
1325
|
sha: file.sha
|