@vite-hub/workspace 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +339 -115
  2. package/dist/abort-BCwpdrN0.js +32 -0
  3. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  4. package/dist/blob-database.d.ts +474 -0
  5. package/dist/blob-database.js +608 -0
  6. package/dist/checkout.d.ts +128 -0
  7. package/dist/checkout.js +849 -0
  8. package/dist/cloudflare.d.ts +6 -7
  9. package/dist/cloudflare.js +1 -1
  10. package/dist/config-B-863EgC.js +15 -0
  11. package/dist/config-BAgL2dtB.js +1076 -0
  12. package/dist/{config-DE9xlaIw.d.ts → config-BQKcPawI.d.ts} +1 -2
  13. package/dist/discard-CNNtCozM.js +8 -0
  14. package/dist/durability.d.ts +22 -0
  15. package/dist/durability.js +70 -0
  16. package/dist/error-diagnostics-CtKjGtGb.js +188 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/file-2pFYNtsU.js +22 -0
  19. package/dist/{files-Q6xZjDHA.js → files-BOo4SbwE.js} +3 -3
  20. package/dist/files.d.ts +38 -0
  21. package/dist/files.js +6 -0
  22. package/dist/{github-DHnjxQIX.js → github-CrYp4v8k.js} +44 -24
  23. package/dist/glob-B8YGvTrZ.js +21 -0
  24. package/dist/glob-Cjxms1t7.js +30 -0
  25. package/dist/{host-DJH8cuoU.js → host-BFBpXn0N.js} +144 -77
  26. package/dist/{hosted-RPeJOCFz.js → hosted-KcUR_jPv.js} +303 -97
  27. package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
  28. package/dist/hosted-vercel-blob.d.ts +6 -7
  29. package/dist/hosted-vercel-blob.js +1 -1
  30. package/dist/hosted.d.ts +10 -9
  31. package/dist/hosted.js +2 -2
  32. package/dist/index.d.ts +26 -47
  33. package/dist/index.js +30 -100
  34. package/dist/internal/path.d.ts +2 -0
  35. package/dist/internal/path.js +2 -0
  36. package/dist/lifecycle-B-enk_4A.js +596 -0
  37. package/dist/lineage.d.ts +26 -0
  38. package/dist/lineage.js +76 -0
  39. package/dist/loader.d.ts +5 -6
  40. package/dist/loader.js +3 -2
  41. package/dist/mcp-resources-DF0F5rcL.js +39 -0
  42. package/dist/memory-BOexthyW.js +247 -0
  43. package/dist/metadata-target-CWz6KHKq.js +1589 -0
  44. package/dist/object-Da1zyPCR.js +11 -0
  45. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  46. package/dist/operations-C6FpR8Rr.js +389 -0
  47. package/dist/operations-CE2drFih.js +1234 -0
  48. package/dist/operations.d.ts +90 -0
  49. package/dist/operations.js +3 -0
  50. package/dist/path--wrT_Azm.js +113 -0
  51. package/dist/path-AxMho1wo.d.ts +7 -0
  52. package/dist/path-DrSIenjj.js +59 -0
  53. package/dist/path-zHxQUbqa.d.ts +9 -0
  54. package/dist/plugins-C8C0auoW.d.ts +10 -0
  55. package/dist/provider-9s4Ufkm5.js +1479 -0
  56. package/dist/providers/github/store.d.ts +3 -5
  57. package/dist/providers/github/store.js +1 -1
  58. package/dist/registry-B3BBm4Ts.d.ts +19 -0
  59. package/dist/{registry-D3yzt8HQ.js → registry-CNphafBx.js} +60 -23
  60. package/dist/registry-CYNN623b.d.ts +9 -0
  61. package/dist/request-scope-Dw5n8bMC.js +83 -0
  62. package/dist/results-DgkZUmTL.js +8 -0
  63. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-rQ84J-ij.js} +3 -4
  64. package/dist/runtime/assets.d.ts +3 -5
  65. package/dist/runtime/assets.js +7 -6
  66. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  67. package/dist/runtime/empty-registry.d.ts +2 -2
  68. package/dist/runtime/registry.d.ts +2 -0
  69. package/dist/runtime/registry.js +23 -0
  70. package/dist/runtime/request.d.ts +4 -0
  71. package/dist/runtime/request.js +8 -0
  72. package/dist/runtime/state.d.ts +5 -4
  73. package/dist/runtime/state.js +8 -18
  74. package/dist/runtime/workspace.d.ts +1 -1
  75. package/dist/runtime/workspace.js +1 -1
  76. package/dist/runtime.d.ts +52 -17
  77. package/dist/runtime.js +324 -67
  78. package/dist/{search-BpiCF2Tw.js → search-C_RfoM2j.js} +10 -9
  79. package/dist/server-8tGltlGz.js +303 -0
  80. package/dist/server.d.ts +36 -39
  81. package/dist/server.js +2 -328
  82. package/dist/shared-B3_EUk89.js +848 -0
  83. package/dist/source-metadata.d.ts +10 -7
  84. package/dist/source-metadata.js +12 -12
  85. package/dist/state-BISnUf1s.d.ts +35 -0
  86. package/dist/{ai-BqCC8BpY.js → state-DbrW-njQ.js} +237 -114
  87. package/dist/store-ybhyD38Z.js +1873 -0
  88. package/dist/{sync-DnTQwt8r.js → sync-CCD_VYC8.js} +61 -41
  89. package/dist/target-jWhTdIuF.js +89 -0
  90. package/dist/test.d.ts +1 -1
  91. package/dist/test.js +1 -1
  92. package/dist/{types-CYuwjJ4V.d.ts → types-BbtwmBZ5.d.ts} +321 -35
  93. package/dist/use-C6lV3-wC.d.ts +321 -0
  94. package/dist/{use-BTNDR5Rd.js → use-CSpT5W87.js} +141 -107
  95. package/dist/utils-CgMZCHsX.js +616 -0
  96. package/dist/vite.d.ts +585 -2
  97. package/dist/vite.js +21369 -2
  98. package/dist/workspace-CYB2xZ1T.d.ts +7 -0
  99. package/dist/{workspace-Dq08Yn72.js → workspace-sPWn2Jxj.js} +441 -225
  100. package/package.json +97 -72
  101. package/dist/ai-CjxvGqM0.d.ts +0 -162
  102. package/dist/ai.d.ts +0 -3
  103. package/dist/ai.js +0 -2
  104. package/dist/collections/client.d.ts +0 -39
  105. package/dist/collections/client.js +0 -137
  106. package/dist/collections.d.ts +0 -59
  107. package/dist/collections.js +0 -159
  108. package/dist/config-Bc3c4Su1.js +0 -7904
  109. package/dist/config-CHLLWklZ.js +0 -36
  110. package/dist/file-Bc1X7pco.js +0 -23
  111. package/dist/glob-CEZKeZFC.js +0 -18
  112. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  113. package/dist/lifecycle-LrL3sA4n.js +0 -316
  114. package/dist/metadata-target-B0tOmVW7.js +0 -717
  115. package/dist/mountx.d.ts +0 -10
  116. package/dist/mountx.js +0 -143
  117. package/dist/nitro.d.ts +0 -2
  118. package/dist/nitro.js +0 -2
  119. package/dist/nuxt.d.ts +0 -26
  120. package/dist/nuxt.js +0 -42
  121. package/dist/path-Cp59koVz.js +0 -139
  122. package/dist/provider-B1yLjCJJ.js +0 -746
  123. package/dist/publish.d.ts +0 -35
  124. package/dist/publish.js +0 -112
  125. package/dist/registry-Uj6IVxes.d.ts +0 -11
  126. package/dist/request-execution-B-dSFlGB.js +0 -84
  127. package/dist/runtime-options-BsPSv5O7.js +0 -13
  128. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  129. package/dist/shared-DTR1Hhma.js +0 -331
  130. package/dist/state-tYcRWEh2.d.ts +0 -26
  131. package/dist/store-Dt_Jyys3.js +0 -608
  132. package/dist/target-D4Bqb1eH.js +0 -11
  133. package/dist/token-CVzURBxC.js +0 -61
  134. package/dist/use-BiHzt0xA.d.ts +0 -103
  135. package/dist/vite-BptCrpv2.js +0 -4526
  136. package/dist/vite-CtA9guIM.d.ts +0 -66
  137. package/dist/workspace-Xddf4G1B.d.ts +0 -6
@@ -0,0 +1,1076 @@
1
+ import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { i as decodeFile, o as isWorkspaceBytes } from "./path--wrT_Azm.js";
3
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
4
+ import { t as isRecord } from "./object-Da1zyPCR.js";
5
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
6
+ import { t as abortable } from "./abort-BCwpdrN0.js";
7
+ import { posix } from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { sourceIgnores } from "@vite-hub/source";
10
+ const maximumHttpMaxResponseBytes = 26214400;
11
+ function primitiveRuntimeTag(value) {
12
+ return value !== null && value !== void 0 && Object(value) !== value ? Object.prototype.toString.call(value) : void 0;
13
+ }
14
+ const blobPrototype = Blob.prototype;
15
+ const blobSizeGetter = Object.getOwnPropertyDescriptor(blobPrototype, "size")?.get;
16
+ const blobTypeGetter = Object.getOwnPropertyDescriptor(blobPrototype, "type")?.get;
17
+ const blobSliceMethod = Object.getOwnPropertyDescriptor(blobPrototype, "slice")?.value;
18
+ function isBlobLike(value) {
19
+ if (value === null || typeof value !== "object" || !blobSizeGetter || !blobTypeGetter) return false;
20
+ try {
21
+ Reflect.apply(blobSizeGetter, value, []);
22
+ Reflect.apply(blobTypeGetter, value, []);
23
+ return true;
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+ const arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get;
29
+ function isArrayBuffer(value) {
30
+ try {
31
+ if (!arrayBufferByteLengthGetter) return false;
32
+ arrayBufferByteLengthGetter.call(value);
33
+ return true;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+ function normalizeForeignBlob(value) {
39
+ if (!blobSizeGetter || !blobTypeGetter || !blobSliceMethod) return void 0;
40
+ try {
41
+ const type = Reflect.apply(blobTypeGetter, value, []);
42
+ Reflect.apply(blobSizeGetter, value, []);
43
+ return Reflect.apply(blobSliceMethod, value, [
44
+ 0,
45
+ void 0,
46
+ type
47
+ ]);
48
+ } catch {
49
+ return;
50
+ }
51
+ }
52
+ const httpInterruptedMessage = "[vitehub] HTTP request was interrupted.";
53
+ /** `INTERNAL_R0012` with the HTTP status of the failed response. */
54
+ function httpStatusError(status) {
55
+ return Object.assign(internalErrorDiagnostics.INTERNAL_R0012({ message: `[vitehub] HTTP request failed with status ${status}.` }), { status });
56
+ }
57
+ async function executeHttpRequest(definition, options = {}) {
58
+ const normalized = normalizeHttpRequest(definition);
59
+ const responseType = options.responseType || "json";
60
+ const { data, response } = await fetchWithRetry(normalized, responseType, options.schema, options.fetch ?? ((input, init) => fetch(input, init)), options.retryFetchError ?? (() => true), options.signal);
61
+ return {
62
+ data,
63
+ mediaType: response.headers.get("content-type") || void 0,
64
+ status: response.status,
65
+ summary: redactedHttpRequestSummary(normalized, responseType)
66
+ };
67
+ }
68
+ async function fetchWithRetry(definition, responseType, schema, send, retryFetchError, signal) {
69
+ const attempts = definition.method === "GET" || definition.method === "HEAD" ? 2 : 1;
70
+ for (let attempt = 1;; attempt++) {
71
+ const result = await fetchOnce(definition, responseType, send, retryFetchError, signal);
72
+ if (result.failure) {
73
+ if (result.failure.retryable && attempt < attempts) continue;
74
+ throw result.failure.cause;
75
+ }
76
+ if (!schema) return result;
77
+ const { response } = result;
78
+ return await abortable(signal, httpInterruptedMessage, async () => ({
79
+ data: await parseStandardSchema(schema, result.data, "HTTP response"),
80
+ response
81
+ }));
82
+ }
83
+ }
84
+ /**
85
+ * Sends one request and reads its body inside the request timeout.
86
+ * A timeout or a caller abort stops the attempt at once, aborts the fetch, and cancels the body.
87
+ */
88
+ async function fetchOnce(definition, responseType, send, retryFetchError, signal) {
89
+ const controller = new AbortController();
90
+ const timeout = new AbortController();
91
+ const timedOut = { failure: {
92
+ cause: new DOMException("This operation was aborted", "AbortError"),
93
+ retryable: true
94
+ } };
95
+ const timer = setTimeout(() => timeout.abort(timedOut), definition.timeout);
96
+ const stop = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal;
97
+ let response;
98
+ try {
99
+ return await abortable(stop, httpInterruptedMessage, async () => {
100
+ try {
101
+ const headers = new Headers(definition.headers);
102
+ applyCookies(headers, definition.cookies);
103
+ const body = serializeRequestBody(definition.body, headers);
104
+ response = await send(urlWithQuery(definition).toString(), {
105
+ body,
106
+ ...body instanceof ReadableStream ? { duplex: "half" } : {},
107
+ headers,
108
+ method: definition.method,
109
+ signal: controller.signal
110
+ });
111
+ if (controller.signal.aborted) {
112
+ cancelResponseBody(response);
113
+ controller.signal.throwIfAborted();
114
+ }
115
+ } catch (cause) {
116
+ return { failure: {
117
+ cause,
118
+ retryable: retryFetchError(cause)
119
+ } };
120
+ }
121
+ if (!response.ok) {
122
+ const cause = httpStatusError(response.status);
123
+ cancelResponseBody(response);
124
+ return { failure: {
125
+ cause,
126
+ retryable: cause.status === 408 || cause.status === 429 || cause.status >= 500
127
+ } };
128
+ }
129
+ try {
130
+ return {
131
+ data: await decodeResponse(response, responseType, definition.maxResponseBytes, controller.signal),
132
+ response
133
+ };
134
+ } catch (cause) {
135
+ return { failure: {
136
+ cause,
137
+ retryable: false
138
+ } };
139
+ }
140
+ });
141
+ } catch (error) {
142
+ if (response) cancelResponseBody(response);
143
+ if (error === timedOut) return timedOut;
144
+ throw error;
145
+ } finally {
146
+ clearTimeout(timer);
147
+ controller.abort();
148
+ }
149
+ }
150
+ function cancelResponseBody(response) {
151
+ response.body?.cancel().catch(() => {});
152
+ }
153
+ function applyCookies(headers, cookies) {
154
+ if (!cookies || !Object.keys(cookies).length) return;
155
+ const value = Object.entries(cookies).map(([name, cookieValue]) => `${name}=${cookieValue}`).join("; ");
156
+ const existing = headers.get("cookie");
157
+ headers.set("cookie", existing ? `${existing}; ${value}` : value);
158
+ }
159
+ function serializeRequestBody(body, headers) {
160
+ if (body === void 0) return void 0;
161
+ if (isBlobLike(body) && !(body instanceof Blob)) {
162
+ const normalized = normalizeForeignBlob(body);
163
+ if (normalized) return normalized;
164
+ }
165
+ if (primitiveRuntimeTag(body) === "[object String]" || body instanceof Uint8Array || isArrayBuffer(body) || ArrayBuffer.isView(body) || body instanceof Blob || body instanceof FormData || body instanceof URLSearchParams || body instanceof ReadableStream) return body;
166
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
167
+ return JSON.stringify(body);
168
+ }
169
+ function urlWithQuery(definition) {
170
+ const url = new URL(definition.url);
171
+ if (!definition.query) return url;
172
+ for (const [key, value] of Object.entries(definition.query)) {
173
+ if (value === void 0) continue;
174
+ if (Array.isArray(value)) {
175
+ for (const item of value) if (item !== void 0) url.searchParams.append(key, queryValue(item));
176
+ continue;
177
+ }
178
+ url.searchParams.set(key, queryValue(value));
179
+ }
180
+ return url;
181
+ }
182
+ function queryValue(value) {
183
+ if (value === null) return "";
184
+ const tag = primitiveRuntimeTag(value);
185
+ if (tag === "[object String]" || tag === "[object Number]" || tag === "[object Boolean]" || tag === "[object BigInt]") return String(value);
186
+ return JSON.stringify(value);
187
+ }
188
+ async function decodeResponse(response, responseType, maxResponseBytes, signal) {
189
+ const bytes = await readResponseBytes(response, maxResponseBytes, signal);
190
+ if (responseType === "arrayBuffer") return bytes.slice().buffer;
191
+ if (responseType === "blob") return new Blob([bytes.slice()], { type: response.headers.get("content-type") || "" });
192
+ const text = new TextDecoder().decode(bytes);
193
+ if (responseType === "text") return text;
194
+ return text ? JSON.parse(text) : void 0;
195
+ }
196
+ async function readResponseBytes(response, maxResponseBytes, signal) {
197
+ const declaredLength = response.headers.get("content-length")?.trim();
198
+ if (response.body && !response.headers.has("content-encoding") && declaredLength && /^\d+$/.test(declaredLength) && BigInt(declaredLength) > BigInt(maxResponseBytes)) {
199
+ const error = responseSizeError(maxResponseBytes);
200
+ response.body.cancel(error).catch(() => {});
201
+ throw error;
202
+ }
203
+ const body = response.body;
204
+ if (!body) return /* @__PURE__ */ new Uint8Array();
205
+ const reader = body.getReader();
206
+ const cancelReader = () => {
207
+ reader.cancel(signal.reason).catch(() => {});
208
+ };
209
+ signal.addEventListener("abort", cancelReader, { once: true });
210
+ const chunks = [];
211
+ let totalBytes = 0;
212
+ try {
213
+ while (true) {
214
+ const chunk = await reader.read();
215
+ if (chunk.done) break;
216
+ totalBytes += chunk.value.byteLength;
217
+ if (totalBytes > maxResponseBytes) {
218
+ const error = responseSizeError(maxResponseBytes);
219
+ reader.cancel(error).catch(() => {});
220
+ throw error;
221
+ }
222
+ chunks.push(chunk.value);
223
+ }
224
+ } finally {
225
+ signal.removeEventListener("abort", cancelReader);
226
+ reader.releaseLock();
227
+ }
228
+ const bytes = new Uint8Array(totalBytes);
229
+ let offset = 0;
230
+ for (const chunk of chunks) {
231
+ bytes.set(chunk, offset);
232
+ offset += chunk.byteLength;
233
+ }
234
+ return bytes;
235
+ }
236
+ function responseSizeError(maxResponseBytes) {
237
+ return internalErrorDiagnostics.INTERNAL_R0004({ message: `[vitehub] HTTP response exceeds the configured ${maxResponseBytes}-byte limit.` });
238
+ }
239
+ function normalizeHttpRequest(definition) {
240
+ const method = ((Object.hasOwn(definition, "method") ? definition.method : void 0) || "GET").toUpperCase();
241
+ if (method !== "GET" && method !== "HEAD" && method !== "POST") throw internalErrorDiagnostics.INTERNAL_R0005({ message: `[vitehub] HTTP request method "${method}" is not supported. Use GET, HEAD, or POST.` });
242
+ const timeout = Object.hasOwn(definition, "timeout") ? definition.timeout : void 0;
243
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647)) throw internalErrorDiagnostics.INTERNAL_R0006({ message: "[vitehub] HTTP request timeout must be a positive finite number no greater than 2147483647." });
244
+ const maxResponseBytes = Object.hasOwn(definition, "maxResponseBytes") ? definition.maxResponseBytes : void 0;
245
+ if (maxResponseBytes !== void 0 && (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes <= 0 || maxResponseBytes > 26214400)) throw internalErrorDiagnostics.INTERNAL_R0007({ message: `[vitehub] HTTP request maxResponseBytes must be a positive safe integer no greater than ${maximumHttpMaxResponseBytes}.` });
246
+ return {
247
+ ...definition,
248
+ maxResponseBytes: maxResponseBytes ?? 5242880,
249
+ method,
250
+ timeout: timeout ?? 3e4,
251
+ url: definition.url instanceof URL ? definition.url : new URL(definition.url)
252
+ };
253
+ }
254
+ async function parseStandardSchema(schema, value, label) {
255
+ const result = await schema["~standard"].validate(value);
256
+ if ("issues" in result && result.issues && result.issues.length > 0) throw internalErrorDiagnostics.INTERNAL_R0008({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.issues)}` });
257
+ if (!("value" in result)) throw internalErrorDiagnostics.INTERNAL_R0009({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.issues)}` });
258
+ return result.value;
259
+ }
260
+ function redactedHttpRequestSummary(definition, responseType) {
261
+ return {
262
+ cookies: definition.cookies && Object.keys(definition.cookies).length ? "redacted" : "none",
263
+ hasBody: definition.body !== void 0,
264
+ hasQuery: Boolean(definition.query && Object.keys(definition.query).length),
265
+ headers: definition.headers && Object.keys(definition.headers).length ? "redacted" : "none",
266
+ method: definition.method,
267
+ responseType,
268
+ url: `${definition.url.origin}${definition.url.pathname}`
269
+ };
270
+ }
271
+ function formatIssues(issues) {
272
+ if (Array.isArray(issues)) return issues.map((issue) => primitiveRuntimeTag(issue) === "[object String]" ? String(issue) : JSON.stringify(issue)).join("; ");
273
+ return primitiveRuntimeTag(issues) === "[object String]" ? String(issues) : JSON.stringify(issues);
274
+ }
275
+ //#endregion
276
+ //#region src/sources/live.ts
277
+ const liveSourcePaths = /* @__PURE__ */ new WeakMap();
278
+ function markLiveWorkspaceSource(source, paths) {
279
+ liveSourcePaths.set(source, paths);
280
+ return source;
281
+ }
282
+ function getLiveWorkspaceSourcePaths(source) {
283
+ return liveSourcePaths.get(source);
284
+ }
285
+ //#endregion
286
+ //#region src/sources/request-json.ts
287
+ function requestJsonEqual(left, right) {
288
+ return JSON.stringify(sortJson(left)) === JSON.stringify(sortJson(right));
289
+ }
290
+ function sortJson(value) {
291
+ if (Array.isArray(value)) return value.map(sortJson);
292
+ if (!value || typeof value !== "object") return value;
293
+ const prototype = Object.getPrototypeOf(value);
294
+ if (prototype !== Object.prototype && prototype !== null) return value;
295
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, item]) => [key, sortJson(item)]));
296
+ }
297
+ //#endregion
298
+ //#region src/sources/request-metadata.ts
299
+ const requestSourceDescriptors = /* @__PURE__ */ new WeakMap();
300
+ const requestSourceExecutors = /* @__PURE__ */ new WeakMap();
301
+ const requestOnlySources = /* @__PURE__ */ new WeakSet();
302
+ function markWorkspaceSourceRequestDescriptor(source, descriptor, options = {}) {
303
+ requestSourceDescriptors.set(source, descriptor);
304
+ if (options.requestOnly) requestOnlySources.add(source);
305
+ return source;
306
+ }
307
+ function markWorkspaceSourceRequestExecutor(source, executor) {
308
+ requestSourceExecutors.set(source, executor);
309
+ return source;
310
+ }
311
+ function copyWorkspaceSourceRequestMetadata(source, target) {
312
+ const requestDescriptor = requestSourceDescriptors.get(source);
313
+ if (requestDescriptor) requestSourceDescriptors.set(target, requestDescriptor);
314
+ const requestExecutor = requestSourceExecutors.get(source);
315
+ if (requestExecutor) requestSourceExecutors.set(target, requestExecutor);
316
+ if (requestOnlySources.has(source)) requestOnlySources.add(target);
317
+ }
318
+ function getWorkspaceSourceRequestDescriptor(source) {
319
+ return requestSourceDescriptors.get(source);
320
+ }
321
+ function getWorkspaceSourceRequestExecutor(source) {
322
+ return requestSourceExecutors.get(source);
323
+ }
324
+ function isWorkspaceSourceRequestOnly(source) {
325
+ return requestOnlySources.has(source);
326
+ }
327
+ function assertWorkspaceSourceRequestDescriptorKey(sourceKey) {
328
+ const normalized = sourceKey.replace(/\\/g, "/");
329
+ if (!normalized || normalized.includes("/") || normalized === "." || normalized === ".." || normalized === ".git" || normalized === ".vitehub" || normalized.endsWith(".json")) throw workspaceError(`[vitehub] Workspace Source Request descriptor key must be a single safe file stem: ${sourceKey}.`);
330
+ }
331
+ function workspaceSourceRequestDescriptorPath(sourceKey) {
332
+ assertWorkspaceSourceRequestDescriptorKey(sourceKey);
333
+ return `.vitehub/sources/${sourceKey}.json`;
334
+ }
335
+ //#endregion
336
+ //#region src/sources/fetch.ts
337
+ function fetch$1(input) {
338
+ if (typeof input === "function") return resolvableFetchSource(input);
339
+ return createFetchSource(input);
340
+ }
341
+ function createFetchSource(options) {
342
+ const callbackReceiver = options;
343
+ options = normalizeFetchSourceOptions(options);
344
+ const responseType = normalizePublicResponseType(options.responseType || "json");
345
+ const method = normalizeMethod(options.method);
346
+ assertRequestShape(options, method);
347
+ const workspacePath = normalizeFetchWorkspacePath(options);
348
+ const mountPath = workspacePath ? posix.dirname(workspacePath) === "." ? "" : posix.dirname(workspacePath) : "";
349
+ const key = workspacePath ? mountPath ? workspacePath.slice(mountPath.length + 1) : workspacePath : "";
350
+ const descriptor = createFetchRequestDescriptor(options, method, responseType, workspacePath);
351
+ const source = markWorkspaceSourceRequestExecutor(markWorkspaceSourceRequestDescriptor({
352
+ cache: options.cache ?? false,
353
+ fingerprint: {
354
+ body: descriptor.request?.body,
355
+ bodySchema: descriptor.request?.bodySchema,
356
+ credentials: descriptor.credentials,
357
+ method,
358
+ path: workspacePath,
359
+ query: descriptor.request?.query,
360
+ querySchema: descriptor.request?.querySchema,
361
+ responseType,
362
+ url: String(options.url)
363
+ },
364
+ materialize: options.materialize || (options.sync ? "none" : "lazy"),
365
+ mount: mountPath,
366
+ name: "fetch",
367
+ probeKeys: options.probeKeys || (key ? [key] : void 0),
368
+ sync: options.sync,
369
+ async getKeys() {
370
+ if (!workspacePath) return [];
371
+ return [key];
372
+ },
373
+ async getItem(sourcePath, ctx) {
374
+ if (!workspacePath) throw workspaceErrorDiagnostics.WORKSPACE_R0046({ message: "[vitehub] Request-only fetch source does not expose a default Source-Backed Path." });
375
+ if (sourcePath !== key) throw workspaceErrorDiagnostics.WORKSPACE_R0047({ message: `[vitehub] Fetch source item does not exist: ${sourcePath}.` });
376
+ const result = await executeHttpRequest({
377
+ ...await defaultFetchSourceRequest(options, method, ctx, void 0, callbackReceiver),
378
+ method,
379
+ url: requestBaseUrl(options.url)
380
+ }, {
381
+ responseType,
382
+ signal: ctx.abortSignal
383
+ });
384
+ const transformed = options.transform ? await Reflect.apply(options.transform, callbackReceiver, [result.data]) : result.data;
385
+ return {
386
+ key,
387
+ path: key,
388
+ content: serializeFetchSourceContent(transformed, responseType),
389
+ mediaType: result.mediaType ?? mediaTypeFor(responseType),
390
+ metadata: {
391
+ request: result.summary,
392
+ status: result.status
393
+ }
394
+ };
395
+ },
396
+ async getMeta(sourcePath) {
397
+ if (!workspacePath) return void 0;
398
+ if (sourcePath !== key) return void 0;
399
+ return {
400
+ mediaType: mediaTypeFor(responseType),
401
+ request: {
402
+ method,
403
+ responseType,
404
+ url: redactedUrl(options.url)
405
+ }
406
+ };
407
+ }
408
+ }, descriptor, { requestOnly: !workspacePath }), async (input, ctx) => {
409
+ return await executeFetchSourceRequest(options, method, responseType, input, ctx, callbackReceiver);
410
+ });
411
+ return workspacePath ? markLiveWorkspaceSource(source, { [workspacePath]: key }) : source;
412
+ }
413
+ const fetchRuntimeOptionKeys = [
414
+ "cache",
415
+ "materialize",
416
+ "probeKeys",
417
+ "sync"
418
+ ];
419
+ function normalizeFetchSourceOptions(options) {
420
+ const normalized = Object.create(Object.getPrototypeOf(options));
421
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(options))) {
422
+ if ("value" in descriptor) {
423
+ Object.defineProperty(normalized, key, descriptor);
424
+ continue;
425
+ }
426
+ Object.defineProperty(normalized, key, {
427
+ configurable: descriptor.configurable,
428
+ enumerable: descriptor.enumerable,
429
+ get: descriptor.get ? () => Reflect.get(options, key, options) : void 0,
430
+ set: descriptor.set ? (value) => Reflect.set(options, key, value, options) : void 0
431
+ });
432
+ }
433
+ for (const key of fetchRuntimeOptionKeys) if (!Object.hasOwn(options, key)) Object.defineProperty(normalized, key, {
434
+ configurable: true,
435
+ enumerable: true,
436
+ value: void 0,
437
+ writable: true
438
+ });
439
+ return normalized;
440
+ }
441
+ function resolvableFetchSource(resolve) {
442
+ return {
443
+ fingerprint: { sourceResolution: "fetch" },
444
+ materialize: "lazy",
445
+ name: "fetch",
446
+ async getKeys() {
447
+ return [];
448
+ },
449
+ async getItem(key) {
450
+ throw workspaceErrorDiagnostics.WORKSPACE_R0048({ message: `[vitehub] fetch() resolver did not resolve before reading ${JSON.stringify(key)}.` });
451
+ },
452
+ async getItems() {
453
+ return [];
454
+ },
455
+ async resolve(ctx) {
456
+ const options = await resolve(ctx);
457
+ return options ? createFetchSource(options) : false;
458
+ }
459
+ };
460
+ }
461
+ function normalizePublicResponseType(responseType) {
462
+ if (responseType !== "json" && responseType !== "text") throw workspaceErrorDiagnostics.WORKSPACE_R0049({ message: `[vitehub] fetch() responseType "${responseType}" is not supported in v1. Use json or text.` });
463
+ return responseType;
464
+ }
465
+ function normalizeMethod(method) {
466
+ const normalized = method === void 0 ? "GET" : typeof method === "string" ? method.toUpperCase() : "";
467
+ if (normalized !== "GET" && normalized !== "HEAD" && normalized !== "POST") {
468
+ const label = typeof method === "string" ? method : typeof method;
469
+ throw workspaceErrorDiagnostics.WORKSPACE_R0050({ message: `[vitehub] fetch() method "${label}" is not supported in v1. Use GET, HEAD, or POST.` });
470
+ }
471
+ return normalized;
472
+ }
473
+ function normalizeFetchWorkspacePath(options) {
474
+ return options.workspacePath ? normalizeSafeWorkspacePath(options.workspacePath, { allowEmpty: false }) : void 0;
475
+ }
476
+ function assertRequestShape(options, method) {
477
+ if ((options.query !== void 0 || urlHasQuery(options.url)) && options.querySchema !== void 0) throw workspaceErrorDiagnostics.WORKSPACE_R0051({ message: "[vitehub] fetch() accepts either query or querySchema, not both." });
478
+ if (options.body !== void 0 && options.bodySchema !== void 0) throw workspaceErrorDiagnostics.WORKSPACE_R0052({ message: "[vitehub] fetch() accepts either body or bodySchema, not both." });
479
+ if ((method === "GET" || method === "HEAD") && (options.body !== void 0 || options.bodySchema !== void 0)) throw workspaceErrorDiagnostics.WORKSPACE_R0053({ message: `[vitehub] fetch() ${method} requests cannot declare body or bodySchema.` });
480
+ }
481
+ function urlHasQuery(url) {
482
+ const parsed = url instanceof URL ? url : new URL(url);
483
+ return Boolean(parsed.search);
484
+ }
485
+ function createFetchRequestDescriptor(options, method, responseType, workspacePath) {
486
+ const request = {};
487
+ const query = concreteQueryFromOptions(options);
488
+ if (query && Object.keys(query).length) request.query = query;
489
+ if (options.querySchema) request.querySchema = schemaProjection(options.querySchema, "querySchema");
490
+ if (options.body !== void 0) request.body = options.body;
491
+ if (options.bodySchema) request.bodySchema = schemaProjection(options.bodySchema, "bodySchema");
492
+ return {
493
+ cache: options.cache,
494
+ credentials: descriptorCredentials(options),
495
+ method,
496
+ ...Object.keys(request).length ? { request } : {},
497
+ responseType,
498
+ url: redactedUrl(options.url),
499
+ ...workspacePath ? { workspacePath } : {}
500
+ };
501
+ }
502
+ function descriptorCredentials(options) {
503
+ if (typeof options.request === "function") return {
504
+ cookies: "dynamic",
505
+ headers: "dynamic"
506
+ };
507
+ const request = options.request;
508
+ const cookies = {
509
+ ...options.cookies,
510
+ ...request?.cookies
511
+ };
512
+ const headers = {
513
+ ...options.headers,
514
+ ...request?.headers
515
+ };
516
+ const credentials = {
517
+ ...Object.keys(cookies).length ? { cookies: Object.keys(cookies).sort() } : {},
518
+ ...Object.keys(headers).length ? { headers: Object.keys(headers).sort() } : {}
519
+ };
520
+ return Object.keys(credentials).length ? credentials : void 0;
521
+ }
522
+ function schemaProjection(schema, option) {
523
+ const project = schema["~standard"].jsonSchema?.input;
524
+ if (typeof project !== "function") throw workspaceErrorDiagnostics.WORKSPACE_R0054({ message: `[vitehub] fetch() ${option} must expose a Standard JSON Schema-compatible input projection.` });
525
+ return project({ target: "draft-2020-12" });
526
+ }
527
+ function concreteQueryFromOptions(options) {
528
+ const query = queryFromUrl(options.url instanceof URL ? options.url : new URL(options.url));
529
+ return query || options.query ? {
530
+ ...query,
531
+ ...options.query
532
+ } : void 0;
533
+ }
534
+ async function defaultFetchSourceRequest(options, method, ctx, overrides = {}, callbackReceiver = options) {
535
+ const defaultQuery = overrides.query !== void 0 ? void 0 : options.query !== void 0 || concreteQueryFromOptions(options) ? concreteQueryFromOptions(options) : options.querySchema ? await parseStandardSchema(options.querySchema, {}, "fetch() query default") : void 0;
536
+ const defaultBody = overrides.body !== void 0 ? void 0 : options.body !== void 0 ? options.body : options.bodySchema ? await parseStandardSchema(options.bodySchema, {}, "fetch() body default") : void 0;
537
+ const query = overrides.query ?? defaultQuery;
538
+ const body = typeof overrides.body === "undefined" ? defaultBody : overrides.body;
539
+ const context = sourceRequestContext(options, method, {
540
+ body,
541
+ query
542
+ }, ctx);
543
+ const additions = typeof options.request === "function" ? await Reflect.apply(options.request, callbackReceiver, [context]) : options.request;
544
+ return {
545
+ body,
546
+ cookies: {
547
+ ...options.cookies,
548
+ ...additions?.cookies
549
+ },
550
+ headers: {
551
+ ...options.headers,
552
+ ...additions?.headers
553
+ },
554
+ method,
555
+ maxResponseBytes: additions?.maxResponseBytes ?? options.maxResponseBytes,
556
+ query,
557
+ timeout: additions?.timeout ?? options.timeout
558
+ };
559
+ }
560
+ function sourceRequestContext(options, method, request, ctx) {
561
+ return {
562
+ request: {
563
+ body: request.body,
564
+ hasBody: typeof request.body !== "undefined",
565
+ hasQuery: Boolean(request.query && Object.keys(request.query).length),
566
+ method,
567
+ query: request.query,
568
+ url: redactedUrl(options.url)
569
+ },
570
+ selectedWorkspaceScope: ctx.selectedWorkspaceScope,
571
+ source: { key: ctx.source },
572
+ workspace: { name: ctx.workspace }
573
+ };
574
+ }
575
+ async function executeFetchSourceRequest(options, method, responseType, input, ctx, callbackReceiver = options) {
576
+ if (input.method !== method) throw workspaceErrorDiagnostics.WORKSPACE_R0055({ message: `[vitehub] Source request method ${input.method} does not match declared method ${method}.` });
577
+ const query = await validateFetchRequestQuery(options, input.url);
578
+ const result = await executeHttpRequest({
579
+ ...await defaultFetchSourceRequest(options, method, ctx, {
580
+ body: await validateFetchRequestBody(options, input.body),
581
+ query
582
+ }, callbackReceiver),
583
+ method,
584
+ url: requestBaseUrl(options.url)
585
+ }, {
586
+ responseType,
587
+ signal: ctx.abortSignal
588
+ });
589
+ return {
590
+ content: serializeFetchSourceContent(options.transform ? await Reflect.apply(options.transform, callbackReceiver, [result.data]) : result.data, responseType),
591
+ mediaType: result.mediaType ?? mediaTypeFor(responseType),
592
+ metadata: {
593
+ request: result.summary,
594
+ status: result.status
595
+ },
596
+ status: result.status
597
+ };
598
+ }
599
+ async function validateFetchRequestQuery(options, inputUrl) {
600
+ const declared = requestBaseUrl(options.url);
601
+ const requested = new URL(inputUrl);
602
+ if (requested.origin !== declared.origin || requested.pathname !== declared.pathname) throw workspaceErrorDiagnostics.WORKSPACE_R0056({ message: "[vitehub] Source request URL does not match the declared Source target." });
603
+ const requestedQuery = queryFromUrl(requested);
604
+ if (options.querySchema) return await parseStandardSchema(options.querySchema, requestedQuery ?? {}, "HTTP request query");
605
+ const expectedQuery = concreteQueryFromOptions(options);
606
+ if (!requestJsonEqual(requestedQuery || {}, serializedQuery(expectedQuery) || {})) throw workspaceErrorDiagnostics.WORKSPACE_R0057({ message: "[vitehub] Source request query does not match the declared Source request shape." });
607
+ return expectedQuery;
608
+ }
609
+ async function validateFetchRequestBody(options, body) {
610
+ if (options.bodySchema) return await parseStandardSchema(options.bodySchema, typeof body === "undefined" ? {} : body, "HTTP request body");
611
+ if (typeof options.body !== "undefined") {
612
+ if (typeof body !== "undefined" && !requestJsonEqual(body, options.body)) throw workspaceErrorDiagnostics.WORKSPACE_R0058({ message: "[vitehub] Source request body does not match the declared Source request shape." });
613
+ return options.body;
614
+ }
615
+ if (typeof body !== "undefined") throw workspaceErrorDiagnostics.WORKSPACE_R0059({ message: "[vitehub] Source request does not declare a body." });
616
+ }
617
+ function requestBaseUrl(url) {
618
+ const parsed = url instanceof URL ? new URL(url) : new URL(url);
619
+ parsed.search = "";
620
+ parsed.hash = "";
621
+ return parsed;
622
+ }
623
+ function queryFromUrl(url) {
624
+ const query = Object.fromEntries([...new Set(url.searchParams.keys())].map((key) => {
625
+ const values = url.searchParams.getAll(key);
626
+ return [key, values.length > 1 ? values : values[0]];
627
+ }));
628
+ return Object.keys(query).length ? query : void 0;
629
+ }
630
+ function serializedQuery(query) {
631
+ if (!query) return void 0;
632
+ const params = new URLSearchParams();
633
+ for (const [key, value] of Object.entries(query)) {
634
+ const values = Array.isArray(value) ? value : [value];
635
+ for (const item of values) params.append(key, String(item));
636
+ }
637
+ return queryFromUrl(new URL(`https://vitehub.local/?${params}`));
638
+ }
639
+ function serializeFetchSourceContent(value, responseType) {
640
+ if (isWorkspaceBytes(value)) return value instanceof Uint8Array ? value : Uint8Array.from(value);
641
+ if (responseType === "json") return JSON.stringify(value, null, 2) ?? "null";
642
+ if (typeof value === "string") return value;
643
+ return typeof value === "undefined" ? "" : String(value);
644
+ }
645
+ function mediaTypeFor(responseType) {
646
+ return responseType === "json" ? "application/json" : "text/plain";
647
+ }
648
+ function redactedUrl(url) {
649
+ const parsed = url instanceof URL ? url : new URL(url);
650
+ return `${parsed.origin}${parsed.pathname}`;
651
+ }
652
+ //#endregion
653
+ //#region src/sources/github-ignore.ts
654
+ function resolveGitHubIgnore(ignore) {
655
+ if (ignore === false) return;
656
+ if (ignore === void 0) return [...sourceIgnores.defaults];
657
+ const single = runtimeString(ignore);
658
+ if (single !== void 0) return [...sourceIgnores.defaults, single];
659
+ if (!Array.isArray(ignore)) throw invalidGitHubIgnore();
660
+ const parsed = [];
661
+ for (const value of ignore) {
662
+ const item = runtimeString(value);
663
+ if (item === void 0) throw invalidGitHubIgnore();
664
+ parsed.push(item);
665
+ }
666
+ return [...sourceIgnores.defaults, ...parsed];
667
+ }
668
+ function runtimeString(value) {
669
+ return Object.prototype.toString.call(value) === "[object String]" ? String(value) : void 0;
670
+ }
671
+ function invalidGitHubIgnore() {
672
+ return workspaceError("[vitehub] GitHub Source ignore must be false, a string, or an array of strings.");
673
+ }
674
+ //#endregion
675
+ //#region src/sources/preparation.ts
676
+ const revisionResolutionByContext = /* @__PURE__ */ new WeakMap();
677
+ async function prepareWorkspaceSource(source, ctx, options = {}) {
678
+ if (options.refreshRevision) {
679
+ revisionResolutionByContext.delete(ctx);
680
+ ctx.revision = void 0;
681
+ }
682
+ let revisionResolution = revisionResolutionByContext.get(ctx);
683
+ if (!revisionResolution) {
684
+ revisionResolution = ctx.revision ? Promise.resolve() : (async () => {
685
+ const revision = await source.resolveRevision?.(ctx);
686
+ if (revision) ctx.revision = revision;
687
+ })();
688
+ revisionResolutionByContext.set(ctx, revisionResolution);
689
+ }
690
+ await revisionResolution;
691
+ await source.prepare?.(ctx);
692
+ }
693
+ //#endregion
694
+ //#region src/sources/runtime-options.ts
695
+ function ownSourceOption(options, key) {
696
+ return Object.hasOwn(options, key) ? options[key] : void 0;
697
+ }
698
+ function withWorkspaceRuntimeOptions(source, options) {
699
+ return {
700
+ ...source,
701
+ cache: ownSourceOption(options, "cache"),
702
+ materialize: ownSourceOption(options, "materialize"),
703
+ mount: ownSourceOption(options, "mount"),
704
+ sync: ownSourceOption(options, "sync"),
705
+ validate: ownSourceOption(options, "validate")
706
+ };
707
+ }
708
+ //#endregion
709
+ //#region src/sources/config.ts
710
+ function copyWorkspaceSourceMetadata(source, target) {
711
+ const livePaths = getLiveWorkspaceSourcePaths(source);
712
+ if (livePaths) markLiveWorkspaceSource(target, livePaths);
713
+ copyWorkspaceSourceRequestMetadata(source, target);
714
+ return target;
715
+ }
716
+ function createSourceContext(definition, source, store, options = {}) {
717
+ return {
718
+ abortSignal: options.abortSignal,
719
+ mountPath: source?.mountPath,
720
+ rootDir: definition.rootDir || process.cwd(),
721
+ selectedWorkspaceScope: options.selectedWorkspaceScope,
722
+ source: source?.key,
723
+ sourceRootDir: definition.sourceRootDir,
724
+ workspace: definition.name,
725
+ workspaceFiles: store ? createSourceContextWorkspaceFiles(store) : void 0
726
+ };
727
+ }
728
+ function createSourceContextWorkspaceFiles(store) {
729
+ async function readFile(path, options) {
730
+ const workspacePath = normalizeSafeWorkspacePath(path);
731
+ const file = await store.readFile(workspacePath);
732
+ if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
733
+ return decodeFile(file.content, options);
734
+ }
735
+ async function stat(path) {
736
+ return await store.stat(normalizeSafeWorkspacePath(path, { allowEmpty: true }));
737
+ }
738
+ return {
739
+ readFile,
740
+ stat,
741
+ async exists(path) {
742
+ return Boolean(await stat(path));
743
+ }
744
+ };
745
+ }
746
+ function normalizeWorkspaceSources(sources) {
747
+ if (!sources) return [];
748
+ return Object.entries(sources).map(([key, source]) => normalizeWorkspaceSource(key, source)).sort((left, right) => right.mountPath.length - left.mountPath.length || left.key.localeCompare(right.key));
749
+ }
750
+ function normalizeWorkspaceSource(key, input) {
751
+ const source = toWorkspaceSource(input);
752
+ const mount = normalizeSourceMount(source);
753
+ const cache = ownSourceOption(mount, "cache") ?? normalizeSourceCache(source) ?? false;
754
+ const sync = normalizeSourceSync(ownSourceOption(source, "sync"));
755
+ const fileKey = fileSourceKey(source);
756
+ const declaredMountPath = ownSourceOption(mount, "path");
757
+ const mountPath = typeof declaredMountPath === "string" ? declaredMountPath : fileKey === void 0 ? defaultSourceMountPath(key, source) : "";
758
+ const probeKeys = ownSourceOption(source, "probeKeys")?.length ? ownSourceOption(source, "probeKeys") : fileKey === void 0 ? void 0 : [fileKey];
759
+ const requestDescriptor = getWorkspaceSourceRequestDescriptor(source);
760
+ if (requestDescriptor) assertWorkspaceSourceRequestDescriptorKey(key);
761
+ return {
762
+ key,
763
+ source,
764
+ mountPath: normalizeSafeWorkspacePath(mountPath, { allowEmpty: true }),
765
+ materialize: ownSourceOption(mount, "materialize") || ownSourceOption(source, "materialize") || (cache ? "lazy" : sync ? "none" : "build"),
766
+ cache,
767
+ sync,
768
+ validate: ownSourceOption(mount, "validate") ?? ownSourceOption(source, "validate") ?? false,
769
+ livePaths: getLiveWorkspaceSourcePaths(source),
770
+ ...probeKeys ? { probeKeys } : {},
771
+ readonly: true,
772
+ requestDescriptor,
773
+ requestOnly: isWorkspaceSourceRequestOnly(source)
774
+ };
775
+ }
776
+ function normalizeWorkspaceSourcesMetadata(sources) {
777
+ return normalizeWorkspaceSources(sources).map(toWorkspaceSourceMetadata);
778
+ }
779
+ function normalizeWorkspaceSourceMetadata(key, input) {
780
+ return toWorkspaceSourceMetadata(normalizeWorkspaceSource(key, input));
781
+ }
782
+ function workspaceSourceGrantPaths(key, input) {
783
+ const source = normalizeWorkspaceSourceMetadata(key, input);
784
+ const descriptorPath = safeWorkspaceSourceRequestDescriptorPath(key);
785
+ if (source.requestOnly) {
786
+ if (!descriptorPath) throw workspaceErrorDiagnostics.WORKSPACE_C0003({ message: `[vitehub] Workspace Scope source grant "${key}" is request-only without a Source Request descriptor.` });
787
+ return [descriptorPath];
788
+ }
789
+ const probePaths = source.probeKeys?.map((sourcePath) => joinSourcePath(source.mountPath, sourcePath)).filter(Boolean) || [];
790
+ const paths = probePaths.length ? probePaths : source.mountPath ? [source.mountPath] : [];
791
+ if (!paths.length) throw workspaceErrorDiagnostics.WORKSPACE_C0004({ message: `[vitehub] Workspace Scope source grant "${key}" is root-mounted; grant explicit paths instead.` });
792
+ return descriptorPath ? [...paths, descriptorPath] : paths;
793
+ }
794
+ function toWorkspaceSourceMetadata(source) {
795
+ return {
796
+ cache: source.cache,
797
+ key: source.key,
798
+ materialize: source.materialize,
799
+ mountPath: source.mountPath,
800
+ ...source.probeKeys?.length ? { probeKeys: source.probeKeys } : {},
801
+ requestOnly: source.requestOnly,
802
+ source: source.source,
803
+ sync: source.sync
804
+ };
805
+ }
806
+ function safeWorkspaceSourceRequestDescriptorPath(key) {
807
+ try {
808
+ return workspaceSourceRequestDescriptorPath(key);
809
+ } catch {
810
+ return;
811
+ }
812
+ }
813
+ function joinSourcePath(mountPath, sourcePath) {
814
+ return [mountPath, sourcePath].filter(Boolean).join("/");
815
+ }
816
+ function sourceMountContainsPath(source, workspacePath) {
817
+ return workspacePath === source.mountPath || !!source.mountPath && workspacePath.startsWith(`${source.mountPath}/`);
818
+ }
819
+ function sourceMountIntersectsPath(source, workspacePath) {
820
+ return !workspacePath || !source.mountPath || sourceMountContainsPath(source, workspacePath) || source.mountPath.startsWith(`${workspacePath}/`);
821
+ }
822
+ function normalizeSourceMount(source) {
823
+ const mount = ownSourceOption(source, "mount");
824
+ if (typeof mount === "string") return { path: mount };
825
+ return mount || {};
826
+ }
827
+ function normalizeSourceCache(source) {
828
+ const cache = ownSourceOption(source, "cache");
829
+ if (cache === false) return false;
830
+ if (cache) {
831
+ const normalized = {};
832
+ if (Object.hasOwn(cache, "maxAge")) normalized.maxAge = cache.maxAge;
833
+ return normalized;
834
+ }
835
+ }
836
+ function normalizeSourceSync(sync) {
837
+ if (!sync) return false;
838
+ if (sync === true) return { stale: "keep" };
839
+ return {
840
+ concurrency: ownSourceOption(sync, "concurrency"),
841
+ stale: ownSourceOption(sync, "stale") || "keep"
842
+ };
843
+ }
844
+ function toWorkspaceSource(input) {
845
+ if (typeof input === "string") return createInferredWorkspaceSource("file", input);
846
+ if (isExplicitSourceBinding(input)) return applyWorkspaceBinding(toWorkspaceSource(input.source), input);
847
+ const inferred = inferWorkspaceSource(input);
848
+ if (inferred !== input) return applyWorkspaceBinding(inferred, input);
849
+ return input;
850
+ }
851
+ function inferWorkspaceSource(input) {
852
+ if (!isRecord(input)) return input;
853
+ if (hasSourceMethods(input)) return input;
854
+ const providerFamilies = [];
855
+ if (hasOwn(input, "repo")) providerFamilies.push("github");
856
+ if (hasOwn(input, "url")) providerFamilies.push("fetch");
857
+ if (hasOwn(input, "server")) providerFamilies.push("mcpResources");
858
+ if (providerFamilies.length > 1) throw ambiguousSourceConfiguration(providerFamilies);
859
+ if (providerFamilies[0]) {
860
+ if (providerFamilies[0] === "github" && (hasOwn(input, "path") || hasOwn(input, "workspacePath") || hasOwn(input, "content"))) throw ambiguousSourceConfiguration(["github", "file"]);
861
+ if (providerFamilies[0] === "fetch") return createInferredFetchSource(input);
862
+ return createInferredWorkspaceSource(providerFamilies[0], input);
863
+ }
864
+ const localFamilies = [];
865
+ if (hasOwn(input, "include")) localFamilies.push("glob");
866
+ if (hasOwn(input, "path") || hasOwn(input, "workspacePath") || hasOwn(input, "content")) localFamilies.push("file");
867
+ if (localFamilies.length === 0) return input;
868
+ if (localFamilies.length > 1) throw ambiguousSourceConfiguration(localFamilies);
869
+ const family = localFamilies[0];
870
+ if (family) return createInferredWorkspaceSource(family, input);
871
+ return input;
872
+ }
873
+ function ambiguousSourceConfiguration(families) {
874
+ return workspaceErrorDiagnostics.WORKSPACE_C0005({ message: `[vitehub] Workspace source configuration is ambiguous. Matched ${families.join(", ")}. A Source helper call, for example github(...) or custom(...), makes the source kind explicit.` });
875
+ }
876
+ function createInferredFetchSource(input) {
877
+ if (!isRecord(input)) return fetch$1(input);
878
+ const record = input;
879
+ const workspacePath = typeof record.workspacePath === "string" ? record.workspacePath : inferFetchWorkspacePath(record);
880
+ return fetch$1({
881
+ ...input,
882
+ workspacePath
883
+ });
884
+ }
885
+ function createInferredWorkspaceSource(family, input) {
886
+ let sourcePromise;
887
+ const livePaths = inferredLivePaths(family, input);
888
+ async function loadSource() {
889
+ sourcePromise ||= loadInferredWorkspaceSource(family, input).catch((error) => {
890
+ sourcePromise = void 0;
891
+ throw error;
892
+ });
893
+ return await sourcePromise;
894
+ }
895
+ const source = {
896
+ ...inferredSourceDefaults(family, input),
897
+ name: family,
898
+ fingerprint: {
899
+ inferredSource: family,
900
+ options: inferredSourceFingerprintOptions(family, input)
901
+ },
902
+ async prepare(ctx) {
903
+ const loaded = await loadSource();
904
+ await prepareWorkspaceSource(loaded, ctx);
905
+ copyLivePaths(livePaths, getLiveWorkspaceSourcePaths(loaded));
906
+ },
907
+ async getKeys(ctx) {
908
+ return await (await loadSource()).getKeys(ctx);
909
+ },
910
+ async getItem(key, ctx) {
911
+ return await (await loadSource()).getItem(key, ctx);
912
+ },
913
+ async getItems(ctx) {
914
+ const source = await loadSource();
915
+ if (source.getItems) return await source.getItems(ctx);
916
+ return await Promise.all((await source.getKeys(ctx)).map(async (key) => {
917
+ const [item, metadata] = await Promise.all([source.getItem(key, ctx), source.getMeta?.(key, ctx)]);
918
+ return metadata ? {
919
+ ...item,
920
+ metadata: {
921
+ ...metadata,
922
+ ...item.metadata
923
+ }
924
+ } : item;
925
+ }));
926
+ },
927
+ async getMeta(key, ctx) {
928
+ return await (await loadSource()).getMeta?.(key, ctx);
929
+ },
930
+ async resolveRevision(ctx) {
931
+ return await (await loadSource()).resolveRevision?.(ctx);
932
+ },
933
+ async checkAccess(ctx) {
934
+ await (await loadSource()).checkAccess?.(ctx);
935
+ }
936
+ };
937
+ return livePaths ? markLiveWorkspaceSource(source, livePaths) : source;
938
+ }
939
+ function inferredSourceFingerprintOptions(family, input) {
940
+ if (family === "file" && isRecord(input)) {
941
+ const options = input;
942
+ if (hasOwn(options, "content") && isWorkspaceBytes(options.content)) return {
943
+ ...options,
944
+ get content() {
945
+ const content = options.content;
946
+ return isWorkspaceBytes(content) ? { sha256: createHash("sha256").update(content).digest("hex") } : content;
947
+ }
948
+ };
949
+ }
950
+ if (family !== "github" || !isRecord(input)) return input;
951
+ return {
952
+ ...input,
953
+ ignore: resolveGitHubIgnore(input.ignore)
954
+ };
955
+ }
956
+ async function loadInferredWorkspaceSource(family, input) {
957
+ if (family === "fetch" && isRecord(input)) return createInferredFetchSource(input);
958
+ if (family === "fetch") return createInferredFetchSource(input);
959
+ if (family === "file") return (await import("./file-2pFYNtsU.js").then((n) => n.n)).file(input);
960
+ if (family === "github") return (await import("./github-CrYp4v8k.js").then((n) => n.n)).github(input);
961
+ if (family === "glob") return (await import("./glob-B8YGvTrZ.js").then((n) => n.n)).glob(input);
962
+ return (await import("./mcp-resources-DF0F5rcL.js").then((n) => n.n)).mcpResources(input);
963
+ }
964
+ function inferredSourceDefaults(family, input) {
965
+ if (!isRecord(input)) return family === "file" ? { key: inferredFileSourceKey(input) } : {};
966
+ if (family === "file") return copySourceRuntimeOptions(input, { key: inferredFileSourceKey(input) });
967
+ if (family === "fetch") {
968
+ const mountPath = dirname$1(inferFetchWorkspacePath(input));
969
+ return copySourceRuntimeOptions(input, {
970
+ cache: ownSourceOption(input, "cache") ?? false,
971
+ materialize: ownSourceOption(input, "materialize") || (ownSourceOption(input, "sync") ? "none" : "lazy"),
972
+ mount: mountPath
973
+ });
974
+ }
975
+ if (family === "github") return copySourceRuntimeOptions(input);
976
+ if (family === "mcpResources") return copySourceRuntimeOptions(input, { materialize: ownSourceOption(input, "materialize") || (ownSourceOption(input, "sync") ? "none" : "lazy") });
977
+ return copySourceRuntimeOptions(input);
978
+ }
979
+ function copySourceRuntimeOptions(input, defaults = {}) {
980
+ return {
981
+ ...defaults,
982
+ cache: ownSourceOption(input, "cache") ?? defaults.cache,
983
+ materialize: ownSourceOption(input, "materialize") ?? defaults.materialize,
984
+ mount: ownSourceOption(input, "mount") ?? defaults.mount,
985
+ probeKeys: ownSourceOption(input, "probeKeys") ?? defaults.probeKeys,
986
+ sync: ownSourceOption(input, "sync") ?? defaults.sync,
987
+ validate: ownSourceOption(input, "validate") ?? defaults.validate
988
+ };
989
+ }
990
+ function inferredFileSourceKey(input) {
991
+ if (typeof input === "string") return normalizeSafeWorkspacePath(input);
992
+ const options = input;
993
+ if (hasOwn(options, "workspacePath") && typeof options.workspacePath === "string") return normalizeSafeWorkspacePath(options.workspacePath);
994
+ if (hasOwn(options, "path") && typeof options.path === "string") return normalizeSafeWorkspacePath(options.path);
995
+ throw workspaceErrorDiagnostics.WORKSPACE_C0006({ message: "[vitehub] file requires a path or workspacePath." });
996
+ }
997
+ function inferredLivePaths(family, input) {
998
+ if (family === "mcpResources") return {};
999
+ if (family !== "fetch" || !isRecord(input)) return void 0;
1000
+ const workspacePath = inferFetchWorkspacePath(input);
1001
+ const mountPath = dirname$1(workspacePath);
1002
+ const key = mountPath ? workspacePath.slice(mountPath.length + 1) : workspacePath;
1003
+ return { [workspacePath]: key };
1004
+ }
1005
+ function copyLivePaths(target, source) {
1006
+ if (!target || !source) return;
1007
+ for (const key of Object.keys(target)) delete target[key];
1008
+ for (const [key, value] of Object.entries(source)) target[key] = value;
1009
+ }
1010
+ function inferFetchWorkspacePath(input) {
1011
+ const responseType = input.responseType === "text" ? "text" : "json";
1012
+ const explicitPath = typeof input.path === "string" ? input.path : void 0;
1013
+ if (explicitPath) return normalizeSafeWorkspacePath(explicitPath, { allowEmpty: false });
1014
+ const url = input.url instanceof URL ? input.url : new URL(String(input.url));
1015
+ if (url.search) throw workspaceErrorDiagnostics.WORKSPACE_C0007({ message: "[vitehub] fetch() requires an explicit path when the URL includes query parameters." });
1016
+ let path = normalizeSafeWorkspacePath(decodeURI(url.pathname).replace(/^\/+/, ""), { allowEmpty: false });
1017
+ if (!basename$1(path).includes(".")) path = `${path}.${responseType === "json" ? "json" : "txt"}`;
1018
+ return path;
1019
+ }
1020
+ /**
1021
+ * A file Source holds one item. Every file helper and the inferred `"README.md"` or `{ path }` forms set its key, so the
1022
+ * default mount is the same for all of them: the Workspace root, which puts the item at its own path.
1023
+ */
1024
+ function fileSourceKey(source) {
1025
+ const key = ownSourceOption(source, "key");
1026
+ return source.name === "file" && typeof key === "string" ? normalizeSafeWorkspacePath(key) : void 0;
1027
+ }
1028
+ function inferRepositoryMount(repo) {
1029
+ return typeof repo === "string" ? repo.split("/").filter(Boolean).at(-1) : void 0;
1030
+ }
1031
+ function defaultSourceMountPath(key, source) {
1032
+ if (key && !/^\d+$/.test(key)) return key;
1033
+ return inferRepositoryMount(sourceFingerprintRepo(source)) ?? key;
1034
+ }
1035
+ function sourceFingerprintRepo(source) {
1036
+ const fingerprint = source.fingerprint;
1037
+ if (!isRecord(fingerprint)) return;
1038
+ if (typeof fingerprint.repo === "string") return fingerprint.repo;
1039
+ const options = fingerprint.options;
1040
+ if (isRecord(options) && typeof options.repo === "string") return options.repo;
1041
+ }
1042
+ function dirname$1(path) {
1043
+ const parts = path.split("/").filter(Boolean);
1044
+ parts.pop();
1045
+ return parts.join("/");
1046
+ }
1047
+ function basename$1(path) {
1048
+ return path.split("/").filter(Boolean).at(-1) || "";
1049
+ }
1050
+ function applyWorkspaceBinding(source, input) {
1051
+ if (!isRecord(input)) return source;
1052
+ const next = { ...source };
1053
+ copyWorkspaceSourceMetadata(source, next);
1054
+ copyDefinedWorkspaceBindingOption(next, input, "cache");
1055
+ copyDefinedWorkspaceBindingOption(next, input, "materialize");
1056
+ copyDefinedWorkspaceBindingOption(next, input, "mount");
1057
+ copyDefinedWorkspaceBindingOption(next, input, "probeKeys");
1058
+ copyDefinedWorkspaceBindingOption(next, input, "skills");
1059
+ copyDefinedWorkspaceBindingOption(next, input, "sync");
1060
+ copyDefinedWorkspaceBindingOption(next, input, "validate");
1061
+ return next;
1062
+ }
1063
+ function copyDefinedWorkspaceBindingOption(target, input, key) {
1064
+ if (Object.hasOwn(input, key) && input[key] !== void 0) target[key] = input[key];
1065
+ }
1066
+ function isExplicitSourceBinding(input) {
1067
+ return isRecord(input) && hasOwn(input, "source");
1068
+ }
1069
+ function hasSourceMethods(input) {
1070
+ return typeof input.getKeys === "function" && typeof input.getItem === "function";
1071
+ }
1072
+ function hasOwn(input, key) {
1073
+ return Object.prototype.hasOwnProperty.call(input, key);
1074
+ }
1075
+ //#endregion
1076
+ export { isWorkspaceSourceRequestOnly as _, normalizeWorkspaceSources as a, markLiveWorkspaceSource as b, sourceMountIntersectsPath as c, withWorkspaceRuntimeOptions as d, prepareWorkspaceSource as f, getWorkspaceSourceRequestExecutor as g, getWorkspaceSourceRequestDescriptor as h, normalizeWorkspaceSourceMetadata as i, workspaceSourceGrantPaths as l, fetch$1 as m, createSourceContext as n, normalizeWorkspaceSourcesMetadata as o, resolveGitHubIgnore as p, normalizeWorkspaceSource as r, sourceMountContainsPath as s, copyWorkspaceSourceMetadata as t, ownSourceOption as u, workspaceSourceRequestDescriptorPath as v, requestJsonEqual as y };