@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
@@ -1,746 +0,0 @@
1
- import { _ as workspaceError, a as isExcludedWorkspacePath, d as resolveInside, f as sha256, l as normalizeWorkspacePath, o as matchesAny, p as assertWorkspaceDigest, r as contentToBytes, t as contentStreamChunks } from "./path-Cp59koVz.js";
2
- import { t as createGitHubWorkspaceStore } from "./store-Dt_Jyys3.js";
3
- import { r as workspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
- import { resolve } from "node:path";
5
- import { createHash, randomUUID } from "node:crypto";
6
- import { defu } from "defu";
7
- import { createReadStream, createWriteStream } from "node:fs";
8
- import { Readable, Transform } from "node:stream";
9
- import { pipeline } from "node:stream/promises";
10
- import { setTimeout } from "node:timers/promises";
11
- //#region ../internal/src/env.ts
12
- function trimmed(value) {
13
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
14
- }
15
- function readEnv(env, ...names) {
16
- for (const name of names) {
17
- const value = trimmed(env[name]);
18
- if (value) return value;
19
- }
20
- }
21
- //#endregion
22
- //#region src/runtime/config.ts
23
- const workspaceRuntimeConfigKey = Symbol.for("vitehub.workspace.runtimeConfig");
24
- function workspaceRuntimeConfigGlobal() {
25
- const scope = globalThis;
26
- scope[workspaceRuntimeConfigKey] ??= false;
27
- return scope;
28
- }
29
- function setWorkspaceRuntimeConfig(config) {
30
- workspaceRuntimeConfigGlobal()[workspaceRuntimeConfigKey] = config;
31
- }
32
- function getWorkspaceRuntimeConfig() {
33
- return workspaceRuntimeConfigGlobal()[workspaceRuntimeConfigKey] ?? false;
34
- }
35
- //#endregion
36
- //#region src/runtime/hosted-store-loader.ts
37
- const workspaceHostedStoreLoaderKey = Symbol.for("vitehub.workspace.hostedStoreLoader");
38
- function workspaceHostedStoreLoaderGlobal() {
39
- return globalThis;
40
- }
41
- function setWorkspaceHostedStoreLoader(loader) {
42
- workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey] = loader;
43
- }
44
- function getWorkspaceHostedStoreLoader() {
45
- return workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey];
46
- }
47
- //#endregion
48
- //#region src/storage/local.ts
49
- async function withFilesystemLock(lock, description, operation) {
50
- const { mkdir, open, readFile, rename, rm, stat } = await import("node:fs/promises");
51
- const { dirname } = await import("node:path");
52
- const owner = randomUUID();
53
- const ownerPath = `${lock}/owner`;
54
- await mkdir(dirname(lock), { recursive: true });
55
- const deadline = Date.now() + 1e4;
56
- while (true) try {
57
- await mkdir(lock);
58
- const ownerFile = await open(ownerPath, "wx");
59
- await ownerFile.writeFile(owner);
60
- await ownerFile.close();
61
- break;
62
- } catch (error) {
63
- if (Reflect.get(Object(error), "code") !== "EEXIST") throw error;
64
- const info = await stat(lock).catch(() => void 0);
65
- if (info && Date.now() - info.mtimeMs > 3e5) {
66
- const stale = `${lock}.stale-${randomUUID()}`;
67
- if (await rename(lock, stale).then(() => true, (renameError) => {
68
- if (renameError.code === "ENOENT") return false;
69
- throw renameError;
70
- })) await rm(stale, {
71
- force: true,
72
- recursive: true
73
- });
74
- } else if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to write Workspace ${description}.`);
75
- else await setTimeout(25);
76
- }
77
- try {
78
- return await operation();
79
- } finally {
80
- if (await readFile(ownerPath, "utf8").catch(() => void 0) === owner) await rm(lock, {
81
- force: true,
82
- recursive: true
83
- });
84
- }
85
- }
86
- async function withFilesystemReadLock(lock, description, operation) {
87
- const { mkdir, open, rm } = await import("node:fs/promises");
88
- const reader = `${lock}.readers/${randomUUID()}`;
89
- await withFilesystemLock(`${lock}.gate`, description, async () => {
90
- await mkdir(`${lock}.readers`, { recursive: true });
91
- await (await open(reader, "wx")).close();
92
- });
93
- try {
94
- return await operation();
95
- } finally {
96
- await rm(reader, { force: true });
97
- }
98
- }
99
- async function withFilesystemWriteLock(lock, description, operation) {
100
- const { readdir, rm, stat } = await import("node:fs/promises");
101
- return await withFilesystemLock(`${lock}.gate`, description, async () => {
102
- const readers = `${lock}.readers`;
103
- const deadline = Date.now() + 1e4;
104
- while (true) {
105
- const active = await readdir(readers).catch((error) => {
106
- if (error.code === "ENOENT") return [];
107
- throw error;
108
- });
109
- if (active.length === 0) return await operation();
110
- for (const owner of active) {
111
- const path = `${readers}/${owner}`;
112
- const info = await stat(path).catch(() => void 0);
113
- if (info && Date.now() - info.mtimeMs > 3e5) await rm(path, { force: true });
114
- }
115
- if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to write Workspace ${description}.`);
116
- await setTimeout(25);
117
- }
118
- });
119
- }
120
- async function withWorkspacePathLock(root, path, operation) {
121
- const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
122
- const paths = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
123
- const lock = async (index) => {
124
- if (index === paths.length) return await operation();
125
- const lockedPath = paths[index];
126
- const lockPath = `${root}.vitehub-locks/${createHash("sha256").update(lockedPath).digest("hex")}`;
127
- const next = () => lock(index + 1);
128
- return index === paths.length - 1 ? await withFilesystemWriteLock(lockPath, `path: ${lockedPath}.`, next) : await withFilesystemReadLock(lockPath, `path: ${lockedPath}.`, next);
129
- };
130
- return await lock(0);
131
- }
132
- async function walk(root, current = root, excluded = [], recursive = true, includeDigest = false) {
133
- const { readdir } = await import("node:fs/promises");
134
- const { relative } = await import("node:path");
135
- const entries = [];
136
- const dirents = await readdir(current, { withFileTypes: true }).catch((error) => {
137
- if (error.code === "ENOENT" || error.code === "ENOTDIR") return [];
138
- throw error;
139
- });
140
- for (const dirent of dirents) {
141
- const absolute = `${current}/${dirent.name}`;
142
- const path = normalizeWorkspacePath(relative(root, absolute));
143
- if (path === ".vitehub" || path.startsWith(".vitehub/")) continue;
144
- if (isExcludedWorkspacePath(path, excluded)) continue;
145
- const { stat } = await import("node:fs/promises");
146
- const info = await stat(absolute).catch((error) => {
147
- if (error.code === "ENOENT") return void 0;
148
- throw error;
149
- });
150
- if (!info) continue;
151
- if (dirent.isDirectory()) {
152
- entries.push({
153
- path,
154
- type: "directory",
155
- mtime: info.mtimeMs
156
- });
157
- if (recursive) entries.push(...await walk(root, absolute, excluded, true, includeDigest));
158
- continue;
159
- }
160
- if (dirent.isFile()) {
161
- const entry = {
162
- path,
163
- type: "file",
164
- size: info.size,
165
- mtime: info.mtimeMs
166
- };
167
- if (includeDigest) entry.digest = await fileDigest(absolute);
168
- entries.push(entry);
169
- }
170
- }
171
- return entries;
172
- }
173
- async function fileDigest(path) {
174
- return await new Promise((resolve, reject) => {
175
- const hash = createHash("sha256");
176
- const stream = createReadStream(path);
177
- stream.on("data", (chunk) => hash.update(chunk));
178
- stream.on("error", reject);
179
- stream.on("end", () => resolve(hash.digest("hex")));
180
- });
181
- }
182
- var LocalWorkspaceStore = class {
183
- root;
184
- #baseline;
185
- #files = /* @__PURE__ */ new Map();
186
- #meta = /* @__PURE__ */ new Map();
187
- #metaLoaded = false;
188
- #metaPath;
189
- constructor(root) {
190
- this.root = root;
191
- this.#metaPath = `${root}.meta.json`;
192
- }
193
- async readFile(path) {
194
- const { readFile } = await import("node:fs/promises");
195
- const bytes = await readFile(resolveInside(this.root, path)).catch((error) => {
196
- if (error.code === "ENOENT") return void 0;
197
- throw error;
198
- });
199
- if (!bytes) return void 0;
200
- const normalized = normalizeWorkspacePath(path);
201
- const metadata = this.#files.get(normalized);
202
- return {
203
- path: normalized,
204
- content: new Uint8Array(bytes),
205
- mediaType: metadata?.mediaType,
206
- metadata: metadata?.metadata
207
- };
208
- }
209
- async writeFile(path, file) {
210
- await withWorkspacePathLock(this.root, path, () => this.#writeFile(path, file));
211
- }
212
- async writeFileConditional(path, file, ifDigest) {
213
- await withWorkspacePathLock(this.root, path, async () => {
214
- const normalized = normalizeWorkspacePath(path);
215
- const current = await this.stat(normalized);
216
- assertWorkspaceDigest(normalized, ifDigest, current?.type === "file" ? current.digest : void 0);
217
- await this.#writeFile(normalized, file);
218
- });
219
- }
220
- async #writeFile(path, file) {
221
- const { dirname } = await import("node:path");
222
- const { mkdir, rename, rm, writeFile } = await import("node:fs/promises");
223
- const absolute = resolveInside(this.root, path);
224
- const tempRoot = `${this.root}/.vitehub/tmp`;
225
- const temp = `${tempRoot}/${randomUUID()}.tmp`;
226
- const normalized = normalizeWorkspacePath(path);
227
- const bytes = contentToBytes(file.content);
228
- const digest = await sha256(bytes);
229
- const existing = await this.stat(normalized);
230
- if (existing?.type === "file" && existing.digest === digest) {
231
- this.#files.set(normalized, {
232
- mediaType: file.mediaType,
233
- metadata: file.metadata
234
- });
235
- return;
236
- }
237
- await Promise.all([mkdir(dirname(absolute), { recursive: true }), mkdir(tempRoot, { recursive: true })]);
238
- try {
239
- await writeFile(temp, bytes);
240
- await rename(temp, absolute);
241
- } catch (error) {
242
- await rm(temp, { force: true }).catch(() => void 0);
243
- throw error;
244
- }
245
- this.#files.set(normalized, {
246
- mediaType: file.mediaType,
247
- metadata: file.metadata
248
- });
249
- }
250
- async writeFileStream(path, file) {
251
- return await withWorkspacePathLock(this.root, path, () => this.#writeFileStream(path, file));
252
- }
253
- async #writeFileStream(path, file) {
254
- const { dirname } = await import("node:path");
255
- const { mkdir, rename, rm } = await import("node:fs/promises");
256
- const normalized = normalizeWorkspacePath(path);
257
- const absolute = resolveInside(this.root, path);
258
- const tempRoot = `${this.root}/.vitehub/tmp`;
259
- const temp = `${tempRoot}/${randomUUID()}.tmp`;
260
- const hash = createHash("sha256");
261
- let size = 0;
262
- await Promise.all([mkdir(dirname(absolute), { recursive: true }), mkdir(tempRoot, { recursive: true })]);
263
- try {
264
- const hashing = new Transform({ transform(chunk, _encoding, callback) {
265
- hash.update(chunk);
266
- size += chunk.byteLength;
267
- callback(void 0, chunk);
268
- } });
269
- await pipeline(Readable.from(contentStreamChunks(file.content)), hashing, createWriteStream(temp));
270
- const digest = hash.digest("hex");
271
- const existing = await this.stat(normalized);
272
- if (existing?.type === "file" && existing.digest === digest) {
273
- await rm(temp, { force: true });
274
- this.#files.set(normalized, {
275
- mediaType: file.mediaType,
276
- metadata: file.metadata
277
- });
278
- return {
279
- ...existing,
280
- mediaType: file.mediaType,
281
- metadata: file.metadata,
282
- size,
283
- digest
284
- };
285
- }
286
- await rename(temp, absolute);
287
- this.#files.set(normalized, {
288
- mediaType: file.mediaType,
289
- metadata: file.metadata
290
- });
291
- return {
292
- path: normalized,
293
- type: "file",
294
- size,
295
- mediaType: file.mediaType,
296
- metadata: file.metadata,
297
- digest
298
- };
299
- } catch (error) {
300
- await rm(temp, { force: true }).catch(() => void 0);
301
- throw error;
302
- }
303
- }
304
- async list(prefix = "", options = {}) {
305
- return await this.#list(prefix, options, false);
306
- }
307
- async #list(prefix, options, includeDigest) {
308
- const normalizedPrefix = normalizeWorkspacePath(prefix);
309
- const current = normalizedPrefix ? resolveInside(this.root, normalizedPrefix) : this.root;
310
- return (await walk(this.root, current, options.exclude, options.recursive === true, includeDigest)).filter((entry) => {
311
- if (!normalizedPrefix) return options.recursive || !entry.path.includes("/");
312
- if (entry.path === normalizedPrefix) return false;
313
- if (!entry.path.startsWith(`${normalizedPrefix}/`)) return false;
314
- return options.recursive || !entry.path.slice(normalizedPrefix.length + 1).includes("/");
315
- }).map((entry) => ({
316
- ...entry,
317
- mediaType: entry.type === "file" ? this.#files.get(entry.path)?.mediaType : entry.mediaType,
318
- metadata: entry.type === "file" ? this.#files.get(entry.path)?.metadata : entry.metadata
319
- })).sort((a, b) => a.path.localeCompare(b.path));
320
- }
321
- async glob(pattern, _options = {}) {
322
- const patterns = Array.isArray(pattern) ? pattern : [pattern];
323
- return (await this.list("", { recursive: true })).filter((entry) => entry.type === "file" && patterns.some((item) => matchesAny(entry.path, item)));
324
- }
325
- async stat(path) {
326
- const { stat } = await import("node:fs/promises");
327
- const normalized = normalizeWorkspacePath(path);
328
- const absolute = resolveInside(this.root, normalized);
329
- const info = await stat(absolute).catch((error) => {
330
- if (error.code === "ENOENT") return void 0;
331
- throw error;
332
- });
333
- if (!info) return void 0;
334
- return {
335
- path: normalized,
336
- type: info.isDirectory() ? "directory" : "file",
337
- size: info.isFile() ? info.size : void 0,
338
- mtime: info.mtimeMs,
339
- mediaType: info.isFile() ? this.#files.get(normalized)?.mediaType : void 0,
340
- metadata: info.isFile() ? this.#files.get(normalized)?.metadata : void 0,
341
- digest: info.isFile() ? await fileDigest(absolute) : void 0
342
- };
343
- }
344
- async mkdir(path, options = {}) {
345
- const { mkdir } = await import("node:fs/promises");
346
- await mkdir(resolveInside(this.root, path), { recursive: options.recursive ?? true });
347
- }
348
- async rm(path, options = {}) {
349
- await withWorkspacePathLock(this.root, path, () => this.#rm(path, options));
350
- }
351
- async #rm(path, options = {}) {
352
- const { rm } = await import("node:fs/promises");
353
- const normalized = normalizeWorkspacePath(path);
354
- await rm(resolveInside(this.root, path), {
355
- recursive: options.recursive ?? false,
356
- force: options.force ?? false
357
- }).catch((error) => {
358
- if (error.code === "ENOENT" && options.force) return;
359
- throw error;
360
- });
361
- for (const key of this.#files.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#files.delete(key);
362
- }
363
- async snapshot(options = {}) {
364
- const { mkdir } = await import("node:fs/promises");
365
- await mkdir(this.root, { recursive: true });
366
- const snapshot = await this.#createSnapshot(options.name);
367
- this.#baseline = snapshot;
368
- return snapshot;
369
- }
370
- async diff(options = {}) {
371
- const from = options.from || this.#baseline;
372
- const to = await this.#createSnapshot();
373
- const entries = [];
374
- const keys = new Set([...Object.keys(from?.entries || {}), ...Object.keys(to.entries)]);
375
- for (const path of [...keys].sort()) {
376
- const before = from?.entries[path];
377
- const after = to.entries[path];
378
- if (!before && after) entries.push({
379
- path,
380
- type: "added",
381
- after
382
- });
383
- else if (before && !after) entries.push({
384
- path,
385
- type: "removed",
386
- before
387
- });
388
- else if (before && after && (before.digest !== after.digest || before.type !== after.type || before.size !== after.size || JSON.stringify(before.metadata) !== JSON.stringify(after.metadata))) entries.push({
389
- path,
390
- type: "modified",
391
- before,
392
- after
393
- });
394
- }
395
- return {
396
- from: from?.id,
397
- to: to.id,
398
- entries
399
- };
400
- }
401
- async getMeta(key) {
402
- await this.#loadMeta();
403
- return this.#meta.get(key);
404
- }
405
- async setMeta(key, value) {
406
- await this.#loadMeta();
407
- this.#meta.set(key, value);
408
- await this.#writeMeta();
409
- }
410
- async #createSnapshot(name) {
411
- const entries = {};
412
- for (const entry of await this.#list("", { recursive: true }, true)) entries[entry.path] = {
413
- type: entry.type,
414
- digest: entry.digest,
415
- metadata: entry.metadata,
416
- size: entry.size
417
- };
418
- return {
419
- id: await sha256({
420
- name,
421
- entries,
422
- createdAt: Date.now()
423
- }),
424
- name,
425
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
426
- entries
427
- };
428
- }
429
- async #loadMeta() {
430
- if (this.#metaLoaded) return;
431
- this.#metaLoaded = true;
432
- const { readFile } = await import("node:fs/promises");
433
- const content = await readFile(this.#metaPath, "utf8").catch((error) => {
434
- if (error.code === "ENOENT") return void 0;
435
- throw error;
436
- });
437
- if (!content) return;
438
- const value = JSON.parse(content);
439
- if (!value || Object(value) !== value || Array.isArray(value)) return;
440
- this.#meta = new Map(Object.entries(Object(value)));
441
- }
442
- async #writeMeta() {
443
- const { dirname } = await import("node:path");
444
- const { mkdir, rename, rm, writeFile } = await import("node:fs/promises");
445
- const temp = `${this.#metaPath}.${randomUUID()}.tmp`;
446
- await mkdir(dirname(this.#metaPath), { recursive: true });
447
- try {
448
- await writeFile(temp, JSON.stringify(Object.fromEntries(this.#meta), null, 2));
449
- await rename(temp, this.#metaPath);
450
- } catch (error) {
451
- await rm(temp, { force: true }).catch(() => void 0);
452
- throw error;
453
- }
454
- }
455
- };
456
- function createLocalWorkspaceStore(root) {
457
- if (!root) throw workspaceError("[vitehub] Local workspace store requires a root directory.");
458
- return new LocalWorkspaceStore(root);
459
- }
460
- //#endregion
461
- //#region src/storage/memory.ts
462
- function now() {
463
- return Date.now();
464
- }
465
- var MemoryWorkspaceStore = class {
466
- [workspaceStoreTarget]() {
467
- return { provider: "memory" };
468
- }
469
- #nodes = new Map([["", {
470
- type: "directory",
471
- mtime: now()
472
- }]]);
473
- #meta = /* @__PURE__ */ new Map();
474
- #baseline;
475
- #mutationQueue = Promise.resolve();
476
- async readFile(path) {
477
- const normalized = normalizeWorkspacePath(path);
478
- const node = this.#nodes.get(normalized);
479
- if (!node || node.type !== "file") return void 0;
480
- return {
481
- path: normalized,
482
- content: node.content || "",
483
- mediaType: node.mediaType,
484
- metadata: node.metadata
485
- };
486
- }
487
- async writeFile(path, file) {
488
- await this.#mutate(() => this.#writeFile(path, file));
489
- }
490
- async writeFileConditional(path, file, ifDigest) {
491
- await this.#mutate(async () => {
492
- const normalized = normalizeWorkspacePath(path);
493
- const current = this.#nodes.get(normalized);
494
- assertWorkspaceDigest(normalized, ifDigest, current?.type === "file" ? (await this.#entry(normalized, current)).digest : void 0);
495
- this.#writeFile(normalized, file);
496
- });
497
- }
498
- async list(prefix = "", options = {}) {
499
- const normalizedPrefix = normalizeWorkspacePath(prefix);
500
- const result = [];
501
- for (const [path, node] of this.#nodes) {
502
- if (!path || path === normalizedPrefix) continue;
503
- if (isExcludedWorkspacePath(path, options.exclude)) continue;
504
- if (normalizedPrefix && !path.startsWith(`${normalizedPrefix}/`)) continue;
505
- if (!options.recursive && normalizeWorkspacePath(path.slice(normalizedPrefix.length)).replace(/^\//, "").includes("/")) continue;
506
- result.push(await this.#entry(path, node));
507
- }
508
- return result.sort((a, b) => a.path.localeCompare(b.path));
509
- }
510
- async glob(pattern, _options = {}) {
511
- const entries = await this.list("", { recursive: true });
512
- const patterns = Array.isArray(pattern) ? pattern : [pattern];
513
- return entries.filter((entry) => entry.type === "file" && patterns.some((item) => matchesAny(entry.path, item)));
514
- }
515
- async stat(path) {
516
- const normalized = normalizeWorkspacePath(path);
517
- const node = this.#nodes.get(normalized);
518
- return node ? await this.#entry(normalized, node) : void 0;
519
- }
520
- async mkdir(path, _options = {}) {
521
- await this.#mutate(() => {
522
- const normalized = normalizeWorkspacePath(path);
523
- this.#ensureParents(normalized);
524
- this.#nodes.set(normalized, {
525
- type: "directory",
526
- mtime: now()
527
- });
528
- });
529
- }
530
- async rm(path, options = {}) {
531
- await this.#mutate(() => {
532
- const normalized = normalizeWorkspacePath(path);
533
- const node = this.#nodes.get(normalized);
534
- if (!node) {
535
- if (options.force) return;
536
- throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
537
- }
538
- if (node.type === "directory" && !options.recursive) {
539
- for (const key of this.#nodes.keys()) if (key.startsWith(`${normalized}/`)) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
540
- }
541
- for (const key of this.#nodes.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#nodes.delete(key);
542
- });
543
- }
544
- async snapshot(options = {}) {
545
- const snapshot = await this.#createSnapshot(options.name);
546
- this.#baseline = snapshot;
547
- return snapshot;
548
- }
549
- async diff(options = {}) {
550
- const from = options.from || this.#baseline;
551
- const to = await this.#createSnapshot();
552
- const entries = [];
553
- const keys = new Set([...Object.keys(from?.entries || {}), ...Object.keys(to.entries)]);
554
- for (const path of [...keys].sort()) {
555
- const before = from?.entries[path];
556
- const after = to.entries[path];
557
- if (!before && after) entries.push({
558
- path,
559
- type: "added",
560
- after
561
- });
562
- else if (before && !after) entries.push({
563
- path,
564
- type: "removed",
565
- before
566
- });
567
- else if (before && after && (before.digest !== after.digest || before.type !== after.type || before.size !== after.size || JSON.stringify(before.metadata) !== JSON.stringify(after.metadata))) entries.push({
568
- path,
569
- type: "modified",
570
- before,
571
- after
572
- });
573
- }
574
- return {
575
- from: from?.id,
576
- to: to.id,
577
- entries
578
- };
579
- }
580
- async getMeta(key) {
581
- return this.#meta.get(key);
582
- }
583
- async setMeta(key, value) {
584
- this.#meta.set(key, value);
585
- }
586
- #writeFile(path, file) {
587
- const normalized = normalizeWorkspacePath(path);
588
- this.#ensureParents(normalized);
589
- this.#nodes.set(normalized, {
590
- type: "file",
591
- content: file.content,
592
- mediaType: file.mediaType,
593
- metadata: file.metadata,
594
- mtime: now()
595
- });
596
- }
597
- #mutate(operation) {
598
- const result = this.#mutationQueue.then(operation);
599
- this.#mutationQueue = result.then(() => void 0, () => void 0);
600
- return result;
601
- }
602
- #ensureParents(path) {
603
- const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
604
- for (let index = 1; index < parts.length; index++) {
605
- const dir = parts.slice(0, index).join("/");
606
- if (!this.#nodes.has(dir)) this.#nodes.set(dir, {
607
- type: "directory",
608
- mtime: now()
609
- });
610
- }
611
- }
612
- async #entry(path, node) {
613
- const content = node.content || "";
614
- const size = node.type === "file" ? typeof content === "string" ? new TextEncoder().encode(content).byteLength : content.byteLength : void 0;
615
- return {
616
- path,
617
- type: node.type,
618
- size,
619
- mtime: node.mtime,
620
- mediaType: node.mediaType,
621
- metadata: node.metadata,
622
- digest: node.type === "file" ? await sha256(content) : void 0
623
- };
624
- }
625
- async #createSnapshot(name) {
626
- const entries = {};
627
- for (const [path, node] of this.#nodes) {
628
- if (!path) continue;
629
- const entry = await this.#entry(path, node);
630
- entries[path] = {
631
- type: entry.type,
632
- digest: entry.digest,
633
- metadata: entry.metadata,
634
- size: entry.size
635
- };
636
- }
637
- return {
638
- id: await sha256({
639
- name,
640
- entries,
641
- createdAt: Date.now()
642
- }),
643
- name,
644
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
645
- entries
646
- };
647
- }
648
- };
649
- function createMemoryWorkspaceStore() {
650
- return new MemoryWorkspaceStore();
651
- }
652
- //#endregion
653
- //#region src/storage/provider.ts
654
- const MASKED_WORKSPACE_RUNTIME_VALUE = "********";
655
- function workspaceRepoName(name) {
656
- return name ? name.replace(/[^a-zA-Z0-9_.-]/g, "-") : void 0;
657
- }
658
- function gitHubWorkspaceOption(value) {
659
- return typeof value === "function" ? value : trimmed(value);
660
- }
661
- function resolveCloudflareArtifactsStore(config = {}, env = process.env) {
662
- const repoPrefix = trimmed(config.repoPrefix) ?? readEnv(env, "WORKSPACE_ARTIFACTS_REPO_PREFIX", "VITEHUB_WORKSPACE_ARTIFACTS_REPO_PREFIX") ?? "vitehub-workspace-";
663
- const repo = trimmed(config.repo) ?? workspaceRepoName(readEnv(env, "WORKSPACE_ARTIFACTS_REPO", "VITEHUB_WORKSPACE_ARTIFACTS_REPO"));
664
- return defu({
665
- binding: trimmed(config.binding) ?? readEnv(env, "WORKSPACE_ARTIFACTS_BINDING", "VITEHUB_WORKSPACE_ARTIFACTS_BINDING"),
666
- branch: trimmed(config.branch) ?? readEnv(env, "WORKSPACE_ARTIFACTS_BRANCH", "VITEHUB_WORKSPACE_ARTIFACTS_BRANCH"),
667
- namespace: trimmed(config.namespace) ?? readEnv(env, "WORKSPACE_ARTIFACTS_NAMESPACE", "VITEHUB_WORKSPACE_ARTIFACTS_NAMESPACE"),
668
- repo,
669
- repoPrefix
670
- }, {
671
- binding: "WORKSPACE_ARTIFACTS",
672
- namespace: "vitehub",
673
- provider: "cloudflare-artifacts"
674
- });
675
- }
676
- function resolveVercelBlobWorkspaceStore(config = {}, env = process.env) {
677
- return {
678
- access: config.access ?? "private",
679
- prefix: trimmed(config.prefix) ?? readEnv(env, "WORKSPACE_BLOB_PREFIX", "VITEHUB_WORKSPACE_BLOB_PREFIX") ?? ".vitehub/workspaces",
680
- provider: "vercel-blob",
681
- token: MASKED_WORKSPACE_RUNTIME_VALUE
682
- };
683
- }
684
- function resolveGitHubWorkspaceStore(config = {}, env = process.env, input = {}) {
685
- const branch = gitHubWorkspaceOption(config.branch) ?? readEnv(env, "WORKSPACE_GITHUB_BRANCH", "VITEHUB_WORKSPACE_GITHUB_BRANCH", "GITHUB_BRANCH");
686
- const root = gitHubWorkspaceOption(config.root) ?? readEnv(env, "WORKSPACE_GITHUB_ROOT", "VITEHUB_WORKSPACE_GITHUB_ROOT");
687
- return {
688
- branch: branch ?? (input.runtime ? void 0 : "main"),
689
- provider: "github",
690
- repository: gitHubWorkspaceOption(config.repository) ?? gitHubWorkspaceOption(config.repo) ?? readEnv(env, "WORKSPACE_GITHUB_REPOSITORY", "VITEHUB_WORKSPACE_GITHUB_REPOSITORY", "GITHUB_REPOSITORY"),
691
- root: root ?? (input.runtime ? void 0 : ".vitehub/workspaces/<workspace>"),
692
- token: input.runtime ? gitHubWorkspaceOption(config.token) ?? readEnv(env, "WORKSPACE_GITHUB_TOKEN", "VITEHUB_WORKSPACE_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN") ?? "********" : MASKED_WORKSPACE_RUNTIME_VALUE
693
- };
694
- }
695
- function hasVercelWorkspaceBlobEnv(env) {
696
- return Boolean(readEnv(env, "BLOB_READ_WRITE_TOKEN"));
697
- }
698
- function normalizeWorkspaceStoreOptions(store, input = {}) {
699
- if (store && "readFile" in store) return;
700
- if (input.dev && !store) return { provider: "local" };
701
- const env = input.env || process.env;
702
- const hosting = input.hosting || "";
703
- if (store?.provider === "cloudflare-artifacts") return resolveCloudflareArtifactsStore(store, env);
704
- if (store?.provider === "github") return resolveGitHubWorkspaceStore(store, env, input);
705
- if (store?.provider === "memory") return store;
706
- if (store?.provider === "vercel-blob") return resolveVercelBlobWorkspaceStore(store, env);
707
- if (store?.provider === "local" || store?.root) return defu(store, { provider: "local" });
708
- if (store && "provider" in store) throw workspaceError(`[vitehub] Unsupported workspace store provider: ${String(store.provider)}.`);
709
- if (hosting.includes("cloudflare")) return { provider: "memory" };
710
- if (hasVercelWorkspaceBlobEnv(env)) return resolveVercelBlobWorkspaceStore({}, env);
711
- if (hosting.includes("vercel")) return { provider: "memory" };
712
- return { provider: "local" };
713
- }
714
- function createWorkspaceStoreFromProvider(definition) {
715
- if (definition.store && "readFile" in definition.store) return definition.store;
716
- const rootDir = definition.rootDir || process.cwd();
717
- const runtimeConfig = getWorkspaceRuntimeConfig();
718
- const runtimeStore = runtimeConfig ? runtimeConfig.store : void 0;
719
- const store = normalizeWorkspaceStoreOptions(definition.store || runtimeStore, {
720
- env: typeof process !== "undefined" ? process.env : {},
721
- hosting: typeof process !== "undefined" ? process.env.VITEHUB_HOSTING : void 0,
722
- rootDir,
723
- runtime: true
724
- });
725
- if (store?.provider === "memory") return createMemoryWorkspaceStore();
726
- if (store?.provider === "cloudflare-artifacts" || store?.provider === "github" || store?.provider === "vercel-blob") {
727
- const loader = getWorkspaceHostedStoreLoader();
728
- if (!loader && store.provider === "github") return createGitHubWorkspaceStore(store, definition.name);
729
- if (!loader) throw workspaceError(`[vitehub] Hosted workspace store "${store.provider}" is not available in this runtime.`);
730
- return loader(store, definition.name);
731
- }
732
- return createLocalWorkspaceStore(store?.root ? resolve(rootDir, store.root) : runtimeConfig ? resolve(runtimeConfig.root, definition.name) : resolve(rootDir, ".vitehub/workspaces", definition.name));
733
- }
734
- function isMaskedWorkspaceRuntimeValue(value) {
735
- return !value || value === "********";
736
- }
737
- function resolveRuntimeVercelBlobWorkspaceStore(config, env) {
738
- const token = readEnv(env, "BLOB_READ_WRITE_TOKEN");
739
- if (isMaskedWorkspaceRuntimeValue(token)) throw new Error("Missing runtime environment variable `BLOB_READ_WRITE_TOKEN` for Vercel workspace Blob storage.");
740
- return {
741
- ...config,
742
- token
743
- };
744
- }
745
- //#endregion
746
- export { resolveRuntimeVercelBlobWorkspaceStore as a, getWorkspaceHostedStoreLoader as c, setWorkspaceRuntimeConfig as d, resolveGitHubWorkspaceStore as i, setWorkspaceHostedStoreLoader as l, normalizeWorkspaceStoreOptions as n, resolveVercelBlobWorkspaceStore as o, resolveCloudflareArtifactsStore as r, createMemoryWorkspaceStore as s, createWorkspaceStoreFromProvider as t, getWorkspaceRuntimeConfig as u };