@vite-hub/workspace 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +225 -58
  2. package/dist/{ai-CjxvGqM0.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  3. package/dist/{ai-BqCC8BpY.js → ai-BZyLwULx.js} +147 -66
  4. package/dist/ai.d.ts +2 -2
  5. package/dist/ai.js +1 -1
  6. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  7. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  8. package/dist/blob-database.d.ts +521 -0
  9. package/dist/blob-database.js +601 -0
  10. package/dist/cloudflare.d.ts +5 -6
  11. package/dist/cloudflare.js +1 -1
  12. package/dist/config-B7dmzDX3.js +1112 -0
  13. package/dist/{config-DE9xlaIw.d.ts → config-DLKdaFWN.d.ts} +1 -2
  14. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  15. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  16. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  17. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  18. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  19. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  20. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  21. package/dist/file-C0_aPWSS.js +26 -0
  22. package/dist/file-metadata-CxDy-E2H.js +58 -0
  23. package/dist/{files-Q6xZjDHA.js → files-C7Px8uaC.js} +3 -3
  24. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  25. package/dist/{github-DHnjxQIX.js → github-CPxHtFB7.js} +16 -23
  26. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  27. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  28. package/dist/glob--XcLlcml.js +22 -0
  29. package/dist/glob--kNYDbfU.js +30 -0
  30. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  31. package/dist/{host-DJH8cuoU.js → host-CFnrTXTK.js} +97 -41
  32. package/dist/{hosted-RPeJOCFz.js → hosted-acMA5XyL.js} +102 -19
  33. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  34. package/dist/hosted-vercel-blob.d.ts +5 -6
  35. package/dist/hosted-vercel-blob.js +1 -1
  36. package/dist/hosted.d.ts +6 -7
  37. package/dist/hosted.js +1 -1
  38. package/dist/index.d.ts +57 -36
  39. package/dist/index.js +56 -56
  40. package/dist/inspect-BoObD2cJ.js +167 -0
  41. package/dist/internal/path.d.ts +2 -0
  42. package/dist/internal/path.js +2 -0
  43. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  44. package/dist/loader.d.ts +5 -6
  45. package/dist/loader.js +3 -2
  46. package/dist/mcp-resources-BREFCmtn.js +39 -0
  47. package/dist/memory-BbwOqDXl.js +248 -0
  48. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  49. package/dist/mountx.d.ts +4 -6
  50. package/dist/mountx.js +10 -8
  51. package/dist/nitro.d.ts +1 -1
  52. package/dist/nitro.js +1 -1
  53. package/dist/nuxt.d.ts +13 -12
  54. package/dist/nuxt.js +4 -8
  55. package/dist/operations-BcpWr41m.js +159 -0
  56. package/dist/operations-CGqY1XeG.js +965 -0
  57. package/dist/operations-DnOwKsJT.d.ts +136 -0
  58. package/dist/operations.d.ts +53 -0
  59. package/dist/operations.js +2 -0
  60. package/dist/path-CNAwN7pw.js +114 -0
  61. package/dist/path-DrSIenjj.js +59 -0
  62. package/dist/path-zHxQUbqa.d.ts +9 -0
  63. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  64. package/dist/provider-kXjfli9u.js +1457 -0
  65. package/dist/providers/github/store.d.ts +3 -5
  66. package/dist/providers/github/store.js +1 -1
  67. package/dist/{registry-D3yzt8HQ.js → registry-Bp-8UUfG.js} +9 -7
  68. package/dist/{registry-Uj6IVxes.d.ts → registry-Cg1TJVVZ.d.ts} +1 -2
  69. package/dist/{request-execution-B-dSFlGB.js → request-execution-Dk9rY-Yh.js} +19 -19
  70. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-B4iAMlE-.js} +2 -2
  71. package/dist/runtime/assets.d.ts +3 -5
  72. package/dist/runtime/assets.js +7 -6
  73. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  74. package/dist/runtime/empty-registry.d.ts +1 -2
  75. package/dist/runtime/state.d.ts +3 -3
  76. package/dist/runtime/state.js +6 -6
  77. package/dist/runtime/workspace.d.ts +1 -1
  78. package/dist/runtime/workspace.js +1 -1
  79. package/dist/runtime.d.ts +51 -17
  80. package/dist/runtime.js +320 -60
  81. package/dist/{search-BpiCF2Tw.js → search-CrTmXj5h.js} +10 -9
  82. package/dist/server-BNQ-Nbjj.js +290 -0
  83. package/dist/server.d.ts +22 -34
  84. package/dist/server.js +2 -328
  85. package/dist/shared-DalXdP0i.js +2158 -0
  86. package/dist/source-metadata.d.ts +6 -7
  87. package/dist/source-metadata.js +7 -7
  88. package/dist/{state-tYcRWEh2.d.ts → state-B8zbLi5t.d.ts} +3 -3
  89. package/dist/store-CXgmu-uw.js +1729 -0
  90. package/dist/{sync-DnTQwt8r.js → sync-CN6ec-5M.js} +61 -41
  91. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  92. package/dist/test.d.ts +1 -1
  93. package/dist/test.js +1 -1
  94. package/dist/{token-CVzURBxC.js → token-CO62GglH.js} +3 -3
  95. package/dist/{types-CYuwjJ4V.d.ts → types-DeK9GIxy.d.ts} +256 -24
  96. package/dist/{use-BTNDR5Rd.js → use-BQj7nSz6.js} +82 -41
  97. package/dist/{use-BiHzt0xA.d.ts → use-DhwhbAVV.d.ts} +16 -11
  98. package/dist/utils-Blrh4N2n.js +545 -0
  99. package/dist/vite-BEvgU2GY.js +20909 -0
  100. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  101. package/dist/vite.d.ts +2 -2
  102. package/dist/vite.js +2 -2
  103. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  104. package/dist/{workspace-Dq08Yn72.js → workspace-6pxkOuxr.js} +361 -230
  105. package/dist/{workspace-Xddf4G1B.d.ts → workspace-BWJQBK1u.d.ts} +4 -3
  106. package/package.json +89 -55
  107. package/dist/collections/client.d.ts +0 -39
  108. package/dist/collections/client.js +0 -137
  109. package/dist/collections.d.ts +0 -59
  110. package/dist/collections.js +0 -159
  111. package/dist/config-Bc3c4Su1.js +0 -7904
  112. package/dist/config-CHLLWklZ.js +0 -36
  113. package/dist/file-Bc1X7pco.js +0 -23
  114. package/dist/glob-CEZKeZFC.js +0 -18
  115. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  116. package/dist/lifecycle-LrL3sA4n.js +0 -316
  117. package/dist/metadata-target-B0tOmVW7.js +0 -717
  118. package/dist/path-Cp59koVz.js +0 -139
  119. package/dist/provider-B1yLjCJJ.js +0 -746
  120. package/dist/publish.d.ts +0 -35
  121. package/dist/publish.js +0 -112
  122. package/dist/runtime-options-BsPSv5O7.js +0 -13
  123. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  124. package/dist/shared-DTR1Hhma.js +0 -331
  125. package/dist/store-Dt_Jyys3.js +0 -608
  126. package/dist/vite-BptCrpv2.js +0 -4526
  127. package/dist/vite-CtA9guIM.d.ts +0 -66
@@ -0,0 +1,1457 @@
1
+ import { n as assertWorkspaceDigest, o as workspaceConflictError, s as workspaceError } from "./path-DrSIenjj.js";
2
+ import { a as isExcludedWorkspacePath, d as resolveInside, f as sha256, l as normalizeWorkspacePath, r as contentToBytes, t as contentStreamChunks } from "./path-CNAwN7pw.js";
3
+ import { r as workspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
5
+ import { r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-BbwOqDXl.js";
6
+ import { t as copyJsonFileMetadata } from "./file-metadata-CxDy-E2H.js";
7
+ import { t as createWorkspaceGlobMatcher } from "./glob--kNYDbfU.js";
8
+ import { C as forgeEnv, w as readForgeEnv } from "./shared-DalXdP0i.js";
9
+ import { t as createGitHubWorkspaceStore } from "./store-CXgmu-uw.js";
10
+ import { dirname, join, relative, resolve, sep } from "node:path";
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { defu } from "defu";
13
+ import { check, fallback, literal, object, optional, pipe, record, safeParse, string, unknown } from "valibot";
14
+ import { constants, createReadStream, createWriteStream } from "node:fs";
15
+ import { chmod, chown, copyFile, link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, utimes, writeFile } from "node:fs/promises";
16
+ import { Readable, Transform } from "node:stream";
17
+ import { pipeline } from "node:stream/promises";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
+ //#region ../internal/src/env.ts
20
+ function trimmed(value) {
21
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
22
+ }
23
+ function readEnv(env, ...names) {
24
+ for (const name of names) {
25
+ const value = trimmed(env[name]);
26
+ if (value) return value;
27
+ }
28
+ }
29
+ //#endregion
30
+ //#region src/runtime/config.ts
31
+ const workspaceRuntimeConfigKey = Symbol.for("vitehub.workspace.runtimeConfig");
32
+ function workspaceRuntimeConfigGlobal() {
33
+ const scope = globalThis;
34
+ scope[workspaceRuntimeConfigKey] ??= false;
35
+ return scope;
36
+ }
37
+ function setWorkspaceRuntimeConfig(config) {
38
+ workspaceRuntimeConfigGlobal()[workspaceRuntimeConfigKey] = config;
39
+ }
40
+ function getWorkspaceRuntimeConfig() {
41
+ return workspaceRuntimeConfigGlobal()[workspaceRuntimeConfigKey] ?? false;
42
+ }
43
+ //#endregion
44
+ //#region src/runtime/hosted-store-loader.ts
45
+ const workspaceHostedStoreLoaderKey = Symbol.for("vitehub.workspace.hostedStoreLoader");
46
+ function workspaceHostedStoreLoaderGlobal() {
47
+ return globalThis;
48
+ }
49
+ function setWorkspaceHostedStoreLoader(loader) {
50
+ workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey] = loader;
51
+ }
52
+ function getWorkspaceHostedStoreLoader() {
53
+ return workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey];
54
+ }
55
+ //#endregion
56
+ //#region src/storage/local.ts
57
+ const fileMetadataSchema = optional(pipe(unknown(), check((value) => !Array.isArray(value)), record(string(), unknown()), check((value) => {
58
+ return safeParse(optional(string()), value.source).success;
59
+ })));
60
+ function assertFileMetadata(path, metadata) {
61
+ metadata = copyJsonFileMetadata(path, metadata);
62
+ if (!safeParse(fileMetadataSchema, metadata).success) throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}. metadata.source must be a string when provided.`);
63
+ return metadata;
64
+ }
65
+ async function backupFile(path, backup) {
66
+ try {
67
+ await link(path, backup);
68
+ } catch (error) {
69
+ if (![
70
+ "EPERM",
71
+ "ENOTSUP",
72
+ "EOPNOTSUPP",
73
+ "ENOSYS",
74
+ "EXDEV"
75
+ ].includes(Reflect.get(Object(error), "code"))) throw error;
76
+ const original = await stat(path);
77
+ try {
78
+ await copyFile(path, backup, constants.COPYFILE_EXCL);
79
+ const copied = await stat(backup);
80
+ if (process.platform !== "win32" && copied.gid !== original.gid) await chown(backup, copied.uid, original.gid);
81
+ await chmod(backup, original.mode & (copied.uid === original.uid ? 4095 : 511));
82
+ await utimes(backup, original.atime, original.mtime);
83
+ if (process.platform !== "win32" && copied.uid !== original.uid) return original.uid;
84
+ } catch (error) {
85
+ await rm(backup, { force: true }).catch(() => void 0);
86
+ throw error;
87
+ }
88
+ }
89
+ }
90
+ async function restoreBackup(backup, path, foreignUid, publicationError) {
91
+ if (foreignUid !== void 0) throw new AggregateError([publicationError], `[vitehub] Cannot roll back ${path} without changing owner UID ${foreignUid}. Recovery content remains at ${backup}.`);
92
+ await rename(backup, path);
93
+ }
94
+ async function reclaimBackup(path, retryDelay = 1e3, attempts = 0) {
95
+ try {
96
+ if (!path.endsWith(".committed.bak")) {
97
+ const committed = path.replace(/\.bak$/, ".committed.bak");
98
+ await rename(path, committed).catch((error) => {
99
+ if (error.code !== "ENOENT") throw error;
100
+ });
101
+ path = committed;
102
+ }
103
+ await rm(path, { force: true });
104
+ } catch {
105
+ if (attempts >= 5) return;
106
+ setTimeout(() => {
107
+ reclaimBackup(path, Math.min(retryDelay * 2, 3e4), attempts + 1);
108
+ }, retryDelay).unref();
109
+ }
110
+ }
111
+ async function reclaimCommittedBackups(root) {
112
+ const entries = await readdir(root).catch(() => []);
113
+ await Promise.all(entries.filter((name) => /^[0-9a-f-]{36}\.committed\.bak$/.test(name)).map((name) => reclaimBackup(`${root}/${name}`)));
114
+ }
115
+ function assertTrustedMetadata(path, info, root) {
116
+ const sharedGroup = (root.mode & 16) !== 0 && info.gid === root.gid;
117
+ const trustedOwner = info.uid === root.uid || info.uid === process.geteuid?.() || sharedGroup;
118
+ if (info.isSymbolicLink() || process.platform !== "win32" && (!trustedOwner || (info.mode & 2) !== 0 || (info.mode & 16) !== 0 && !sharedGroup)) throw workspaceError(`[vitehub] Untrusted Workspace metadata path: ${path}.`);
119
+ }
120
+ async function applyMetadataPermissions(path, mode, gid) {
121
+ const info = await stat(path);
122
+ if (info.gid !== gid) try {
123
+ await chown(path, info.uid, gid);
124
+ } catch (error) {
125
+ if (!["EPERM", "EACCES"].includes(Reflect.get(Object(error), "code"))) throw error;
126
+ mode &= 448;
127
+ }
128
+ if ((info.mode & 511) !== mode) try {
129
+ await chmod(path, mode);
130
+ } catch (error) {
131
+ if (!["EPERM", "EACCES"].includes(Reflect.get(Object(error), "code"))) throw error;
132
+ if ((info.mode & 511 & ~mode) !== 0) throw error;
133
+ }
134
+ }
135
+ async function validateLockDirectory(path) {
136
+ const info = await lstat(path).catch((error) => {
137
+ if (error.code === "ENOENT") return void 0;
138
+ throw error;
139
+ });
140
+ if (info && (!info.isDirectory() || info.isSymbolicLink())) throw workspaceError(`[vitehub] Untrusted Workspace lock path: ${path}.`);
141
+ }
142
+ async function ensureLockDirectory(path) {
143
+ await mkdir(path, { mode: 448 }).catch((error) => {
144
+ if (error.code !== "EEXIST") throw error;
145
+ });
146
+ await validateLockDirectory(path);
147
+ }
148
+ async function withLeaseHeartbeat(file, operation, onFailure) {
149
+ let renewal = Promise.resolve();
150
+ let rejectHeartbeat;
151
+ const heartbeatFailure = new Promise((_, reject) => {
152
+ rejectHeartbeat = reject;
153
+ });
154
+ heartbeatFailure.catch(() => {});
155
+ const timer = setInterval(() => {
156
+ renewal = renewal.then(async () => {
157
+ const now = /* @__PURE__ */ new Date();
158
+ await file.utimes(now, now);
159
+ });
160
+ renewal.catch((error) => {
161
+ rejectHeartbeat(error);
162
+ onFailure?.(error);
163
+ });
164
+ }, 3e4);
165
+ timer.unref();
166
+ const active = Promise.resolve().then(operation);
167
+ try {
168
+ return await Promise.race([active, heartbeatFailure]);
169
+ } catch (error) {
170
+ await active.catch(() => void 0);
171
+ throw error;
172
+ } finally {
173
+ clearInterval(timer);
174
+ try {
175
+ await renewal;
176
+ } finally {
177
+ await file.close();
178
+ }
179
+ }
180
+ }
181
+ async function removeOwnedGate(lock) {
182
+ for (let attempt = 0;; attempt++) try {
183
+ await rm(lock, {
184
+ force: true,
185
+ recursive: true
186
+ });
187
+ return;
188
+ } catch (error) {
189
+ if (attempt >= 2) throw error;
190
+ await setTimeout$1(25);
191
+ }
192
+ }
193
+ async function withFilesystemLock(lock, permissions, description, operation, deadline) {
194
+ const expiresAt = Date.now() + 1e4;
195
+ const owner = randomUUID();
196
+ const ownerPath = `${lock}/owner`;
197
+ let lease;
198
+ while (true) {
199
+ let created = false;
200
+ try {
201
+ await mkdir(lock, { mode: 448 });
202
+ created = true;
203
+ if (process.platform !== "win32") await applyMetadataPermissions(lock, permissions.mode & 504, permissions.gid);
204
+ const ownerFile = await open(ownerPath, "wx");
205
+ try {
206
+ await ownerFile.writeFile(owner);
207
+ } catch (error) {
208
+ await ownerFile.close();
209
+ throw error;
210
+ }
211
+ lease = ownerFile;
212
+ break;
213
+ } catch (error) {
214
+ if (created) {
215
+ try {
216
+ await removeOwnedGate(lock);
217
+ } catch (cleanupError) {
218
+ throw new AggregateError([error, cleanupError], "Workspace gate acquisition and cleanup failed", { cause: error });
219
+ }
220
+ throw error;
221
+ }
222
+ if (Reflect.get(Object(error), "code") !== "EEXIST") throw error;
223
+ await validateLockDirectory(lock);
224
+ if (Date.now() >= (deadline?.() ?? expiresAt)) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
225
+ else await setTimeout$1(25);
226
+ }
227
+ }
228
+ try {
229
+ return await withLeaseHeartbeat(lease, operation);
230
+ } finally {
231
+ await removeOwnedGate(lock);
232
+ }
233
+ }
234
+ async function withFilesystemReadLock(lock, permissions, description, operation, onFailure) {
235
+ const reader = `${lock}.readers/${randomUUID()}`;
236
+ await ensureLockDirectory(`${lock}.readers`);
237
+ if (process.platform !== "win32") await applyMetadataPermissions(`${lock}.readers`, permissions.mode & 504, permissions.gid);
238
+ const lease = await open(reader, "wx");
239
+ try {
240
+ return await withLeaseHeartbeat(lease, operation, onFailure);
241
+ } finally {
242
+ await rm(reader, { force: true });
243
+ await withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
244
+ await rmdir(`${lock}.readers`).catch((error) => {
245
+ if (![
246
+ "ENOENT",
247
+ "ENOTEMPTY",
248
+ "EEXIST"
249
+ ].includes(error.code ?? "")) throw error;
250
+ });
251
+ }, () => Date.now()).catch(() => {});
252
+ }
253
+ }
254
+ async function withFilesystemWriteLock(lock, permissions, description, operation) {
255
+ return await withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
256
+ const readers = `${lock}.readers`;
257
+ const deadline = Date.now() + 1e4;
258
+ while (true) {
259
+ await validateLockDirectory(readers);
260
+ if ((await readdir(readers).catch((error) => {
261
+ if (error.code === "ENOENT") return [];
262
+ throw error;
263
+ })).length === 0) {
264
+ await rmdir(readers).catch(() => {});
265
+ return await operation();
266
+ }
267
+ if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
268
+ await setTimeout$1(25);
269
+ }
270
+ });
271
+ }
272
+ async function withFilesystemWriterIntent(lock, permissions, operation) {
273
+ const intents = `${lock}.writers`;
274
+ const intent = `${intents}/${randomUUID()}`;
275
+ for (;;) try {
276
+ await ensureLockDirectory(intents);
277
+ if (process.platform !== "win32") await applyMetadataPermissions(intents, permissions.mode & 504, permissions.gid);
278
+ await mkdir(intent, { mode: 448 });
279
+ break;
280
+ } catch (error) {
281
+ if (Reflect.get(Object(error), "code") !== "ENOENT") {
282
+ await rmdir(intents).catch(() => {});
283
+ throw error;
284
+ }
285
+ }
286
+ try {
287
+ return await operation();
288
+ } finally {
289
+ await rm(intent, {
290
+ recursive: true,
291
+ force: true
292
+ });
293
+ await rmdir(intents).catch((error) => {
294
+ if (![
295
+ "ENOENT",
296
+ "ENOTEMPTY",
297
+ "EEXIST"
298
+ ].includes(error.code ?? "")) throw error;
299
+ });
300
+ }
301
+ }
302
+ const sharedReadLeases = /* @__PURE__ */ new Map();
303
+ const pendingWriters = /* @__PURE__ */ new Map();
304
+ async function openSharedReadLease(lock, permissions, description) {
305
+ let release;
306
+ const released = new Promise((resolve) => {
307
+ release = resolve;
308
+ });
309
+ let settled;
310
+ const acquired = new Promise((resolve, reject) => {
311
+ settled = withFilesystemReadLock(lock, permissions, description, async () => {
312
+ resolve();
313
+ await released;
314
+ }, (error) => {
315
+ lease.failure = { error };
316
+ });
317
+ settled.catch(reject);
318
+ });
319
+ const lease = {
320
+ acquired,
321
+ readers: 0,
322
+ release,
323
+ settled
324
+ };
325
+ settled.catch(() => {
326
+ if (sharedReadLeases.get(lock) === lease) sharedReadLeases.delete(lock);
327
+ });
328
+ await acquired;
329
+ return lease;
330
+ }
331
+ const readAdmissions = /* @__PURE__ */ new Map();
332
+ async function admitSharedReader(lock, permissions, description, deadline) {
333
+ const ticket = {
334
+ deadline,
335
+ charged: false
336
+ };
337
+ let admission = readAdmissions.get(lock);
338
+ if (!admission) {
339
+ admission = {
340
+ tickets: /* @__PURE__ */ new Set(),
341
+ admitted: Promise.resolve(void 0)
342
+ };
343
+ const batch = admission;
344
+ readAdmissions.set(lock, batch);
345
+ let chargedLease;
346
+ let chargedCount = 0;
347
+ const liveTickets = () => [...batch.tickets].filter((reader) => Date.now() < reader.deadline);
348
+ batch.admitted = withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
349
+ readAdmissions.delete(lock);
350
+ if (!liveTickets().length) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
351
+ if (pendingWriters.has(lock) || await lstat(`${lock}.writers`).then(() => true).catch((error) => {
352
+ if (error.code === "ENOENT") return false;
353
+ throw error;
354
+ })) return void 0;
355
+ let lease = sharedReadLeases.get(lock);
356
+ if (!lease) {
357
+ lease = await openSharedReadLease(lock, permissions, description);
358
+ sharedReadLeases.set(lock, lease);
359
+ }
360
+ const tickets = liveTickets();
361
+ chargedCount = tickets.length;
362
+ if (!chargedCount) {
363
+ await releaseSharedReaders(lock, lease, 0);
364
+ throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
365
+ }
366
+ lease.readers += chargedCount;
367
+ chargedLease = lease;
368
+ for (const reader of tickets) reader.charged = true;
369
+ return lease;
370
+ }, () => Math.max(...[...batch.tickets].map((reader) => reader.deadline))).catch(async (error) => {
371
+ if (chargedLease) try {
372
+ await releaseSharedReaders(lock, chargedLease, chargedCount);
373
+ } catch (cleanupError) {
374
+ throw new AggregateError([error, cleanupError], "Workspace reader admission and cleanup failed", { cause: error });
375
+ }
376
+ throw error;
377
+ }).finally(() => {
378
+ if (readAdmissions.get(lock) === batch) readAdmissions.delete(lock);
379
+ });
380
+ }
381
+ admission.tickets.add(ticket);
382
+ const batch = admission;
383
+ let timedOut = false;
384
+ let timeout;
385
+ const expired = new Promise((_, reject) => {
386
+ timeout = setInterval(() => {
387
+ if (Date.now() < deadline) return;
388
+ timedOut = true;
389
+ batch.tickets.delete(ticket);
390
+ reject(workspaceError(`[vitehub] Timed out waiting to ${description}.`));
391
+ }, 25);
392
+ });
393
+ try {
394
+ const lease = await Promise.race([batch.admitted, expired]);
395
+ if (lease && !ticket.charged) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
396
+ return lease;
397
+ } catch (error) {
398
+ if (timedOut && ticket.charged) try {
399
+ await batch.admitted.then((lease) => lease ? releaseSharedReaders(lock, lease) : void 0, () => void 0);
400
+ } catch (cleanupError) {
401
+ throw new AggregateError([error, cleanupError], "Workspace reader timeout and cleanup failed", { cause: error });
402
+ }
403
+ throw error;
404
+ } finally {
405
+ clearInterval(timeout);
406
+ batch.tickets.delete(ticket);
407
+ }
408
+ }
409
+ async function releaseSharedReaders(lock, lease, count = 1) {
410
+ lease.readers -= count;
411
+ if (lease.readers === 0) {
412
+ if (sharedReadLeases.get(lock) === lease) sharedReadLeases.delete(lock);
413
+ lease.release();
414
+ await lease.settled;
415
+ }
416
+ if (lease.failure) throw lease.failure.error;
417
+ }
418
+ async function withSharedFilesystemReadLock(lock, permissions, description, operation) {
419
+ const deadline = Date.now() + 1e4;
420
+ let lease;
421
+ while (!lease) {
422
+ for (let writers = pendingWriters.get(lock); writers; writers = pendingWriters.get(lock)) {
423
+ const remaining = deadline - Date.now();
424
+ if (remaining <= 0) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
425
+ await new Promise((resolve, reject) => {
426
+ const timeout = setTimeout(() => reject(workspaceError(`[vitehub] Timed out waiting to ${description}.`)), remaining);
427
+ writers.idle.then(() => {
428
+ clearTimeout(timeout);
429
+ resolve();
430
+ });
431
+ });
432
+ }
433
+ const writerIntent = await lstat(`${lock}.writers`).catch((error) => {
434
+ if (error.code === "ENOENT") return void 0;
435
+ throw error;
436
+ });
437
+ const gate = await lstat(`${lock}.gate`).catch((error) => {
438
+ if (error.code === "ENOENT") return void 0;
439
+ throw error;
440
+ });
441
+ if (!writerIntent && !gate && !pendingWriters.has(lock)) {
442
+ lease = await admitSharedReader(lock, permissions, description, deadline);
443
+ if (lease) break;
444
+ }
445
+ if (writerIntent) await validateLockDirectory(`${lock}.writers`);
446
+ if (gate) await validateLockDirectory(`${lock}.gate`);
447
+ if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
448
+ await setTimeout$1(25);
449
+ }
450
+ try {
451
+ await lease.acquired;
452
+ if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
453
+ if (lease.failure) throw lease.failure.error;
454
+ return await operation();
455
+ } finally {
456
+ await releaseSharedReaders(lock, lease);
457
+ }
458
+ }
459
+ async function withPendingWriter(lock, operation) {
460
+ let writers = pendingWriters.get(lock);
461
+ if (!writers) {
462
+ let resolve;
463
+ writers = {
464
+ count: 0,
465
+ idle: new Promise((done) => {
466
+ resolve = done;
467
+ }),
468
+ resolve
469
+ };
470
+ pendingWriters.set(lock, writers);
471
+ }
472
+ writers.count++;
473
+ try {
474
+ return await operation();
475
+ } finally {
476
+ if (--writers.count === 0) {
477
+ pendingWriters.delete(lock);
478
+ writers.resolve();
479
+ }
480
+ }
481
+ }
482
+ async function withWorkspacePathLock(root, path, operation, readOnly = false, heldReadPrefix) {
483
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
484
+ const paths = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
485
+ if (paths.length === 0) return await operation();
486
+ await mkdir(root, { recursive: true });
487
+ const permissions = await stat(root);
488
+ for (const directory of [`${root}/.vitehub`, `${root}/.vitehub/locks`]) {
489
+ await ensureLockDirectory(directory);
490
+ if (process.platform !== "win32") await applyMetadataPermissions(directory, permissions.mode & 504, permissions.gid);
491
+ }
492
+ const lock = async (index) => {
493
+ if (index === paths.length) return await operation();
494
+ const lockedPath = paths[index];
495
+ if (readOnly && heldReadPrefix && (heldReadPrefix === lockedPath || heldReadPrefix.startsWith(`${lockedPath}/`))) return await lock(index + 1);
496
+ const lockPath = `${root}/.vitehub/locks/${createHash("sha256").update(lockedPath).digest("hex")}`;
497
+ const next = () => lock(index + 1);
498
+ const description = `${readOnly ? "read" : "write"} Workspace path: ${lockedPath}`;
499
+ return !readOnly && index === paths.length - 1 ? await withPendingWriter(lockPath, () => withFilesystemWriterIntent(lockPath, permissions, () => withFilesystemWriteLock(lockPath, permissions, description, next))) : await withSharedFilesystemReadLock(lockPath, permissions, description, next);
500
+ };
501
+ return await lock(0);
502
+ }
503
+ function isGitMetadataName(name) {
504
+ return name === ".git" || process.platform === "win32" && name.toLowerCase() === ".git";
505
+ }
506
+ /** Check whether a path belongs to a Git worktree before classifying Git errors. */
507
+ async function hasGitMetadata(root) {
508
+ let current = resolve(root);
509
+ while (true) {
510
+ if (await lstat(join(current, ".git")).catch((error) => {
511
+ if (error.code === "ENOENT") return void 0;
512
+ throw error;
513
+ })) return true;
514
+ const parent = resolve(current, "..");
515
+ if (parent === current) return false;
516
+ current = parent;
517
+ }
518
+ }
519
+ /** Paths that Git ignores under a checkout root. Ignored directories are listed once, not descended. */
520
+ async function gitIgnoredWorkspacePaths(root) {
521
+ const { execFile } = await import("node:child_process");
522
+ const gitMetadata = await hasGitMetadata(root);
523
+ return [".git", ...(await new Promise((resolveOutput, reject) => execFile("git", [
524
+ "-C",
525
+ root,
526
+ "-c",
527
+ "core.hooksPath=/dev/null",
528
+ "ls-files",
529
+ "-z",
530
+ "--others",
531
+ "--ignored",
532
+ "--exclude-standard",
533
+ "--directory"
534
+ ], {
535
+ encoding: "utf8",
536
+ env: {
537
+ ...process.env,
538
+ GIT_TERMINAL_PROMPT: "0",
539
+ LC_ALL: "C"
540
+ },
541
+ maxBuffer: 67108864
542
+ }, (error, stdout, stderr) => {
543
+ if (error) {
544
+ if (Reflect.get(Object(error), "code") === 128 && /not a git repository/i.test(stderr) && !gitMetadata) {
545
+ resolveOutput("");
546
+ return;
547
+ }
548
+ reject(error);
549
+ return;
550
+ }
551
+ resolveOutput(stdout);
552
+ }))).split("\0").filter(Boolean).map((path) => path.replace(/\/$/, ""))];
553
+ }
554
+ /** Include ignore rules from Git roots that contain a non-root listing prefix. */
555
+ async function gitIgnoredWorkspacePathsForPrefix(root, current, excluded) {
556
+ const { relative, sep } = await import("node:path");
557
+ const relativePrefix = relative(root, current);
558
+ if (!relativePrefix || relativePrefix === "." || relativePrefix.startsWith(`..${sep}`)) return [...excluded];
559
+ const result = [...excluded];
560
+ let ancestor = root;
561
+ let prefix = "";
562
+ for (const segment of relativePrefix.split(sep)) {
563
+ ancestor = `${ancestor}/${segment}`;
564
+ prefix = prefix ? `${prefix}/${segment}` : segment;
565
+ if ((await readdir(ancestor, { withFileTypes: true }).catch(() => [])).some((dirent) => isGitMetadataName(dirent.name))) {
566
+ const nestedExcluded = await gitIgnoredWorkspacePaths(ancestor);
567
+ result.push(...nestedExcluded.map((path) => `${prefix}/${path}`));
568
+ }
569
+ }
570
+ return result;
571
+ }
572
+ const processPathLocks = /* @__PURE__ */ new Map();
573
+ const processMetadataRoots = /* @__PURE__ */ new Map();
574
+ async function withProcessLock(key, exclusive, operation) {
575
+ let state = processPathLocks.get(key);
576
+ if (!state) processPathLocks.set(key, state = {
577
+ pendingWriters: 0,
578
+ readers: 0,
579
+ writer: false,
580
+ waiters: []
581
+ });
582
+ const current = state;
583
+ if (exclusive) current.pendingWriters++;
584
+ try {
585
+ while (current.writer || (exclusive ? current.readers > 0 : current.pendingWriters > 0)) await new Promise((resolve) => current.waiters.push(resolve));
586
+ } finally {
587
+ if (exclusive) current.pendingWriters--;
588
+ }
589
+ if (exclusive) current.writer = true;
590
+ else current.readers++;
591
+ try {
592
+ return await operation();
593
+ } finally {
594
+ if (exclusive) current.writer = false;
595
+ else current.readers--;
596
+ const waiters = current.waiters.splice(0);
597
+ if (!current.writer && current.readers === 0 && current.pendingWriters === 0 && waiters.length === 0) processPathLocks.delete(key);
598
+ for (const resolve of waiters) resolve();
599
+ }
600
+ }
601
+ async function prepareProcessMetadataRoot(root) {
602
+ const { lstat, mkdir, stat } = await import("node:fs/promises");
603
+ const previous = processMetadataRoots.get(root);
604
+ if (previous) {
605
+ if (await previous.then(() => lstat(`${root}/.vitehub`).then(() => true, () => false), () => false)) return;
606
+ if (processMetadataRoots.get(root) === previous) processMetadataRoots.delete(root);
607
+ }
608
+ let prepared = processMetadataRoots.get(root);
609
+ if (!prepared) {
610
+ prepared = (async () => {
611
+ await mkdir(root, { recursive: true });
612
+ const permissions = await stat(root);
613
+ await ensureLockDirectory(`${root}/.vitehub`);
614
+ if (process.platform !== "win32") await applyMetadataPermissions(`${root}/.vitehub`, permissions.mode & 504, permissions.gid);
615
+ })();
616
+ processMetadataRoots.set(root, prepared);
617
+ const current = prepared;
618
+ current.catch(() => {
619
+ if (processMetadataRoots.get(root) === current) processMetadataRoots.delete(root);
620
+ });
621
+ }
622
+ await prepared;
623
+ }
624
+ /**
625
+ * Keeps the lock order of withWorkspacePathLock in memory: shared reads on
626
+ * each parent path and an exclusive lock on the target path for a write. Use
627
+ * it only for a store root that one process owns.
628
+ */
629
+ async function withProcessPathLock(root, path, operation, readOnly = false) {
630
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
631
+ const paths = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
632
+ if (paths.length === 0) return await operation();
633
+ const key = resolve(root);
634
+ await prepareProcessMetadataRoot(key);
635
+ const lock = async (index) => {
636
+ if (index === paths.length) return await operation();
637
+ return await withProcessLock(`${key}\0${paths[index]}`, !readOnly && index === paths.length - 1, () => lock(index + 1));
638
+ };
639
+ return await lock(0);
640
+ }
641
+ async function walk(root, current, privatePaths, excluded = [], recursive = true) {
642
+ const { isAbsolute, relative, sep } = await import("node:path");
643
+ if (privatePaths.some((path) => {
644
+ const relativePath = relative(path, current);
645
+ return !relativePath || !isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith(`..${sep}`);
646
+ })) return [];
647
+ const entries = [];
648
+ const dirents = await readdir(current, { withFileTypes: true }).catch((error) => {
649
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return [];
650
+ throw error;
651
+ });
652
+ let currentExcluded = excluded;
653
+ if (current !== root && dirents.some((dirent) => isGitMetadataName(dirent.name))) {
654
+ const nestedExcluded = await gitIgnoredWorkspacePaths(current);
655
+ const prefix = normalizeWorkspacePath(relative(root, current));
656
+ currentExcluded = [...excluded, ...nestedExcluded.map((path) => prefix ? `${prefix}/${path}` : path)];
657
+ }
658
+ for (const dirent of dirents) {
659
+ if (dirent.isSymbolicLink()) continue;
660
+ const absolute = `${current}/${dirent.name}`;
661
+ if (privatePaths.some((path) => !relative(path, absolute))) continue;
662
+ const path = normalizeWorkspacePath(relative(root, absolute));
663
+ if (path.split("/")[0]?.toLowerCase() === ".vitehub") continue;
664
+ if (path.split("/").some((component) => isGitMetadataName(component))) continue;
665
+ if (isExcludedWorkspacePath(path, currentExcluded)) continue;
666
+ const info = await stat(absolute).catch((error) => {
667
+ if (error.code === "ENOENT") return void 0;
668
+ throw error;
669
+ });
670
+ if (!info) continue;
671
+ if (dirent.isDirectory()) {
672
+ entries.push({
673
+ path,
674
+ type: "directory",
675
+ mtime: info.mtimeMs
676
+ });
677
+ if (recursive) entries.push(...await walk(root, absolute, privatePaths, currentExcluded, true));
678
+ continue;
679
+ }
680
+ if (dirent.isFile()) {
681
+ const entry = {
682
+ path,
683
+ type: "file",
684
+ size: info.size,
685
+ mtime: info.mtimeMs
686
+ };
687
+ entries.push(entry);
688
+ }
689
+ }
690
+ return entries;
691
+ }
692
+ async function fileDigest(path) {
693
+ return await new Promise((resolve, reject) => {
694
+ const hash = createHash("sha256");
695
+ const stream = createReadStream(path);
696
+ stream.on("data", (chunk) => hash.update(chunk));
697
+ stream.on("error", reject);
698
+ stream.on("end", () => resolve(hash.digest("hex")));
699
+ });
700
+ }
701
+ var LocalWorkspaceStore = class {
702
+ root;
703
+ [workspaceStoreTarget]() {
704
+ return {
705
+ provider: "local",
706
+ containsPath: async (ancestor, path) => {
707
+ const readIdentity = async (value) => await stat(value, { bigint: true }).catch((error) => {
708
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return void 0;
709
+ throw error;
710
+ });
711
+ const destination = await readIdentity(resolveInside(this.root, ancestor));
712
+ if (!destination) return false;
713
+ const root = resolve(this.root);
714
+ let current = resolveInside(root, path);
715
+ while (current !== root) {
716
+ const source = await readIdentity(current);
717
+ if (source && source.dev === destination.dev && source.ino === destination.ino) return true;
718
+ current = dirname(current);
719
+ }
720
+ return false;
721
+ }
722
+ };
723
+ }
724
+ #baseline;
725
+ #files = /* @__PURE__ */ new Map();
726
+ #metaCache;
727
+ #fileMetadataRoot;
728
+ #metaPath;
729
+ #ignoreGit;
730
+ #processLocks;
731
+ constructor(root, options = {}) {
732
+ this.root = root;
733
+ this.#ignoreGit = options.ignore === "git";
734
+ this.#processLocks = options.locks === "process";
735
+ this.#fileMetadataRoot = `${root}/.vitehub/file-metadata`;
736
+ this.#metaPath = `${root}.meta.json`;
737
+ }
738
+ async #pathLock(root, path, operation, readOnly = false) {
739
+ return this.#processLocks ? await withProcessPathLock(root, path, operation, readOnly) : await withWorkspacePathLock(root, path, operation, readOnly);
740
+ }
741
+ #removalMarker(path) {
742
+ return `${this.root}/.vitehub/file-removals/${createHash("sha256").update(path).digest("hex")}`;
743
+ }
744
+ async #assertNoPendingRemoval(path) {
745
+ const directory = `${this.root}/.vitehub/file-removals`;
746
+ const info = await lstat(directory).catch((error) => {
747
+ if (error.code === "ENOENT") return void 0;
748
+ throw error;
749
+ });
750
+ if (!info) return;
751
+ assertTrustedMetadata(directory, info, await stat(this.root));
752
+ if (!info.isDirectory()) throw workspaceError(`[vitehub] Invalid Workspace removal directory.`);
753
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
754
+ for (let index = 0; index <= parts.length; index++) {
755
+ const ancestor = parts.slice(0, index).join("/");
756
+ if (await lstat(this.#removalMarker(ancestor)).catch((error) => {
757
+ if (error.code === "ENOENT") return void 0;
758
+ throw error;
759
+ })) throw workspaceError(`[vitehub] Interrupted Workspace removal at ${ancestor || "/"}; retry removal before accessing ${path}.`);
760
+ }
761
+ }
762
+ async #readFileMetadata(path) {
763
+ await this.#assertNoPendingRemoval(path);
764
+ const { root } = await this.#prepareMetadataDirectories(path, false, false);
765
+ if (!root) return;
766
+ const metadataPath = resolveInside(this.#fileMetadataRoot, `${path}/metadata.json`);
767
+ const info = await lstat(metadataPath).catch((error) => {
768
+ if (error.code === "ENOENT") return void 0;
769
+ throw error;
770
+ });
771
+ if (info) {
772
+ assertTrustedMetadata(metadataPath, info, root);
773
+ if (!info.isFile()) return;
774
+ }
775
+ const file = await open(metadataPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)).catch((error) => {
776
+ if (error.code === "ENOENT") return void 0;
777
+ throw error;
778
+ });
779
+ if (!file) {
780
+ this.#files.delete(path);
781
+ return;
782
+ }
783
+ let content;
784
+ try {
785
+ const opened = await file.stat();
786
+ assertTrustedMetadata(metadataPath, opened, root);
787
+ if (!opened.isFile()) return;
788
+ content = await file.readFile("utf8");
789
+ } finally {
790
+ await file.close();
791
+ }
792
+ let value;
793
+ try {
794
+ value = JSON.parse(content);
795
+ } catch {
796
+ throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}.`);
797
+ }
798
+ const parsed = safeParse(object({
799
+ path: literal(path),
800
+ mediaType: fallback(optional(string()), void 0),
801
+ metadata: fileMetadataSchema
802
+ }), value);
803
+ if (!parsed.success) throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}.`);
804
+ const { path: _path, ...result } = parsed.output;
805
+ return {
806
+ ...result,
807
+ metadata: assertFileMetadata(path, result.metadata)
808
+ };
809
+ }
810
+ async #prepareMetadataDirectories(path, create, repair = true) {
811
+ const root = await stat(this.root).catch((error) => {
812
+ if (error.code === "ENOENT" && !create) return void 0;
813
+ throw error;
814
+ });
815
+ if (!root) return {
816
+ mode: 384,
817
+ gid: void 0,
818
+ root: void 0
819
+ };
820
+ const mode = root.mode & 504;
821
+ let directory = this.root;
822
+ for (const part of [
823
+ ".vitehub",
824
+ "file-metadata",
825
+ ...normalizeWorkspacePath(path).split("/").filter(Boolean)
826
+ ]) {
827
+ if (part) directory = resolveInside(directory, part);
828
+ if (create) await mkdir(directory, { mode: 448 }).catch((error) => {
829
+ if (error.code !== "EEXIST") throw error;
830
+ });
831
+ const info = await lstat(directory).catch((error) => {
832
+ if (error.code === "ENOENT" && !create) return void 0;
833
+ throw error;
834
+ });
835
+ if (!info) return {
836
+ mode: mode & 438,
837
+ gid: root.gid,
838
+ root: void 0
839
+ };
840
+ assertTrustedMetadata(directory, info, root);
841
+ if (!info.isDirectory()) {
842
+ if (repair) await rm(directory, { force: true });
843
+ if (!create) return {
844
+ mode: mode & 438,
845
+ gid: root.gid,
846
+ root: void 0
847
+ };
848
+ await mkdir(directory, { mode: 448 });
849
+ }
850
+ if (repair && process.platform !== "win32") await applyMetadataPermissions(directory, mode, root.gid);
851
+ }
852
+ return {
853
+ mode: mode & 438,
854
+ gid: root.gid,
855
+ root
856
+ };
857
+ }
858
+ async #writeFileMetadata(path, value) {
859
+ await this.#assertNoPendingRemoval(path);
860
+ const metadataPath = resolveInside(this.#fileMetadataRoot, `${path}/metadata.json`);
861
+ const hasMetadata = value.mediaType !== void 0 || value.metadata !== void 0;
862
+ const permissions = await this.#prepareMetadataDirectories(path, hasMetadata);
863
+ if (!permissions.root) {
864
+ this.#files.delete(path);
865
+ return;
866
+ }
867
+ const existing = await lstat(metadataPath).catch((error) => {
868
+ if (error.code === "ENOENT") return void 0;
869
+ throw error;
870
+ });
871
+ if (existing) {
872
+ assertTrustedMetadata(metadataPath, existing, permissions.root);
873
+ if (existing.isDirectory()) await rm(metadataPath, {
874
+ recursive: true,
875
+ force: true
876
+ });
877
+ }
878
+ if (!hasMetadata) {
879
+ await rm(metadataPath, { force: true });
880
+ this.#files.delete(path);
881
+ return;
882
+ }
883
+ const temp = `${metadataPath}.${randomUUID()}.tmp`;
884
+ try {
885
+ await writeFile(temp, JSON.stringify({
886
+ path,
887
+ ...value
888
+ }), { mode: 384 });
889
+ if (process.platform !== "win32" && permissions.gid !== void 0) await applyMetadataPermissions(temp, permissions.mode, permissions.gid);
890
+ await rename(temp, metadataPath);
891
+ } catch (error) {
892
+ await rm(temp, { force: true }).catch(() => void 0);
893
+ throw error;
894
+ }
895
+ this.#files.delete(path);
896
+ }
897
+ async readFile(path) {
898
+ return await this.#pathLock(this.root, path, () => this.#readFile(path), true);
899
+ }
900
+ async #readFile(path) {
901
+ const absolute = resolveInside(this.root, path);
902
+ await this.#assertPathComponents(path);
903
+ const bytes = await readFile(absolute).catch((error) => {
904
+ if (error.code === "ENOENT") return void 0;
905
+ throw error;
906
+ });
907
+ if (!bytes) return void 0;
908
+ const normalized = normalizeWorkspacePath(path);
909
+ const metadata = await this.#readFileMetadata(normalized);
910
+ return {
911
+ path: normalized,
912
+ content: new Uint8Array(bytes),
913
+ mediaType: metadata?.mediaType,
914
+ metadata: metadata?.metadata
915
+ };
916
+ }
917
+ async writeFile(path, file) {
918
+ await this.#pathLock(this.root, path, () => this.#writeFile(path, file));
919
+ }
920
+ async writeFileConditional(path, file, ifDigest) {
921
+ await this.#pathLock(this.root, path, async () => {
922
+ const normalized = normalizeWorkspacePath(path);
923
+ const current = await this.#stat(normalized);
924
+ assertWorkspaceDigest(normalized, ifDigest, current?.type === "file" ? current.digest : void 0);
925
+ await this.#writeFile(normalized, file);
926
+ });
927
+ }
928
+ async #writeFile(path, file) {
929
+ file = {
930
+ ...file,
931
+ metadata: assertFileMetadata(path, file.metadata)
932
+ };
933
+ const { dirname } = await import("node:path");
934
+ const absolute = resolveInside(this.root, path);
935
+ const tempRoot = `${this.root}/.vitehub/tmp`;
936
+ const temp = `${tempRoot}/${randomUUID()}.tmp`;
937
+ const backup = `${tempRoot}/${randomUUID()}.bak`;
938
+ await reclaimCommittedBackups(tempRoot);
939
+ const normalized = normalizeWorkspacePath(path);
940
+ await this.#assertPathComponents(normalized);
941
+ const bytes = contentToBytes(file.content);
942
+ const digest = await sha256(bytes);
943
+ const existing = await this.#stat(normalized);
944
+ if (existing?.type === "directory") throw workspaceError(`[vitehub] Cannot write a file over directory: ${normalized}.`);
945
+ if (existing?.type === "file" && existing.digest === digest) {
946
+ await this.#writeFileMetadata(normalized, {
947
+ mediaType: file.mediaType,
948
+ metadata: file.metadata
949
+ });
950
+ return;
951
+ }
952
+ await Promise.all([mkdir(dirname(absolute), { recursive: true }), mkdir(tempRoot, { recursive: true })]);
953
+ try {
954
+ await writeFile(temp, bytes);
955
+ const hadExisting = existing?.type === "file";
956
+ const foreignUid = hadExisting ? await backupFile(absolute, backup) : void 0;
957
+ await rename(temp, absolute).catch(async (error) => {
958
+ await rm(backup, { force: true });
959
+ throw error;
960
+ });
961
+ try {
962
+ await this.#writeFileMetadata(normalized, {
963
+ mediaType: file.mediaType,
964
+ metadata: file.metadata
965
+ });
966
+ } catch (error) {
967
+ if (hadExisting) await restoreBackup(backup, absolute, foreignUid, error);
968
+ else await rm(absolute, { force: true });
969
+ throw error;
970
+ }
971
+ await reclaimBackup(backup);
972
+ return;
973
+ } catch (error) {
974
+ await rm(temp, { force: true }).catch(() => void 0);
975
+ throw error;
976
+ }
977
+ }
978
+ async #assertPathComponents(path, includeTarget = true) {
979
+ const root = resolve(this.root);
980
+ const parts = relative(root, resolveInside(root, path)).split(sep).filter(Boolean);
981
+ if (!includeTarget) parts.pop();
982
+ let current = root;
983
+ for (const part of parts) {
984
+ current = join(current, part);
985
+ const info = await lstat(current).catch((error) => {
986
+ if (error.code === "ENOENT") return void 0;
987
+ throw error;
988
+ });
989
+ if (!info) return;
990
+ if (info.isSymbolicLink()) throw workspaceError(`[vitehub] Refusing to access symbolic-link Workspace path: ${path}.`);
991
+ }
992
+ }
993
+ async writeFileStream(path, file) {
994
+ return await this.#pathLock(this.root, path, () => this.#writeFileStream(path, file));
995
+ }
996
+ async #writeFileStream(path, file) {
997
+ await this.#assertPathComponents(path);
998
+ file = {
999
+ ...file,
1000
+ metadata: assertFileMetadata(path, file.metadata)
1001
+ };
1002
+ const { dirname } = await import("node:path");
1003
+ const normalized = normalizeWorkspacePath(path);
1004
+ const absolute = resolveInside(this.root, path);
1005
+ const tempRoot = `${this.root}/.vitehub/tmp`;
1006
+ const temp = `${tempRoot}/${randomUUID()}.tmp`;
1007
+ const backup = `${tempRoot}/${randomUUID()}.bak`;
1008
+ await reclaimCommittedBackups(tempRoot);
1009
+ const hash = createHash("sha256");
1010
+ let size = 0;
1011
+ await Promise.all([mkdir(dirname(absolute), { recursive: true }), mkdir(tempRoot, { recursive: true })]);
1012
+ try {
1013
+ const hashing = new Transform({ transform(chunk, _encoding, callback) {
1014
+ hash.update(chunk);
1015
+ size += chunk.byteLength;
1016
+ callback(void 0, chunk);
1017
+ } });
1018
+ await pipeline(Readable.from(contentStreamChunks(file.content)), hashing, createWriteStream(temp));
1019
+ const digest = hash.digest("hex");
1020
+ const existing = await this.#stat(normalized);
1021
+ if (existing?.type === "directory") throw workspaceError(`[vitehub] Cannot write a file over directory: ${normalized}.`);
1022
+ if (existing?.type === "file" && existing.digest === digest) {
1023
+ await rm(temp, { force: true });
1024
+ await this.#writeFileMetadata(normalized, {
1025
+ mediaType: file.mediaType,
1026
+ metadata: file.metadata
1027
+ });
1028
+ return {
1029
+ ...existing,
1030
+ mediaType: file.mediaType,
1031
+ metadata: file.metadata,
1032
+ size,
1033
+ digest
1034
+ };
1035
+ }
1036
+ const hadExisting = existing?.type === "file";
1037
+ const foreignUid = hadExisting ? await backupFile(absolute, backup) : void 0;
1038
+ await rename(temp, absolute).catch(async (error) => {
1039
+ await rm(backup, { force: true });
1040
+ throw error;
1041
+ });
1042
+ try {
1043
+ await this.#writeFileMetadata(normalized, {
1044
+ mediaType: file.mediaType,
1045
+ metadata: file.metadata
1046
+ });
1047
+ } catch (error) {
1048
+ if (hadExisting) await restoreBackup(backup, absolute, foreignUid, error);
1049
+ else await rm(absolute, { force: true });
1050
+ throw error;
1051
+ }
1052
+ await reclaimBackup(backup);
1053
+ return {
1054
+ path: normalized,
1055
+ type: "file",
1056
+ size,
1057
+ mediaType: file.mediaType,
1058
+ metadata: file.metadata,
1059
+ digest
1060
+ };
1061
+ } catch (error) {
1062
+ await rm(temp, { force: true }).catch(() => void 0);
1063
+ throw error;
1064
+ }
1065
+ }
1066
+ async list(prefix = "", options = {}) {
1067
+ return await this.#list(prefix, options, false);
1068
+ }
1069
+ async #list(prefix, options, includeDigest) {
1070
+ await this.#assertPathComponents(prefix);
1071
+ const normalizedPrefix = normalizeWorkspacePath(prefix);
1072
+ const current = normalizedPrefix ? resolveInside(this.root, normalizedPrefix) : this.root;
1073
+ const privatePaths = [this.#fileMetadataRoot, this.#metaPath];
1074
+ let excluded = this.#ignoreGit ? [...options.exclude ?? [], ...await gitIgnoredWorkspacePaths(this.root)] : options.exclude;
1075
+ if (this.#ignoreGit) excluded = await gitIgnoredWorkspacePathsForPrefix(this.root, current, excluded ?? []);
1076
+ const filtered = (await walk(this.root, current, privatePaths, excluded, options.recursive === true)).filter((entry) => {
1077
+ if (!normalizedPrefix) return options.recursive || !entry.path.includes("/");
1078
+ if (entry.path === normalizedPrefix) return false;
1079
+ if (!entry.path.startsWith(`${normalizedPrefix}/`)) return false;
1080
+ return options.recursive || !entry.path.slice(normalizedPrefix.length + 1).includes("/");
1081
+ });
1082
+ const entries = [];
1083
+ const readBatchDurationMs = 1e3;
1084
+ const groups = /* @__PURE__ */ new Map();
1085
+ for (const entry of filtered) {
1086
+ const key = entry.path.split("/")[0];
1087
+ const group = groups.get(key) ?? [];
1088
+ group.push(entry);
1089
+ groups.set(key, group);
1090
+ }
1091
+ const independent = this.#processLocks ? filtered.map((entry) => [entry]) : [...groups.values()];
1092
+ for (let index = 0; index < independent.length; index += 64) await Promise.all(independent.slice(index, index + 64).map(async (group) => {
1093
+ if (this.#processLocks) {
1094
+ for (const entry of group) {
1095
+ const info = await this.#pathLock(this.root, entry.path, () => this.#stat(entry.path, includeDigest), true);
1096
+ if (info) entries.push(info);
1097
+ }
1098
+ return;
1099
+ }
1100
+ const heldReadPrefix = normalizedPrefix || group[0].path.split("/")[0];
1101
+ let offset = 0;
1102
+ while (offset < group.length) await withWorkspacePathLock(this.root, heldReadPrefix, async () => {
1103
+ const startedAt = Date.now();
1104
+ do {
1105
+ const entry = group[offset++];
1106
+ const info = await withWorkspacePathLock(this.root, entry.path, () => this.#stat(entry.path, includeDigest), true, heldReadPrefix);
1107
+ if (info) entries.push(info);
1108
+ } while (offset < group.length && Date.now() - startedAt < readBatchDurationMs);
1109
+ }, true);
1110
+ }));
1111
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
1112
+ }
1113
+ async glob(pattern, options = {}) {
1114
+ const { cwd, matches } = createWorkspaceGlobMatcher(pattern, options);
1115
+ return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
1116
+ }
1117
+ async stat(path) {
1118
+ return await this.#pathLock(this.root, path, () => this.#stat(path), true);
1119
+ }
1120
+ async #stat(path, includeDigest = true) {
1121
+ const normalized = normalizeWorkspacePath(path);
1122
+ const absolute = resolveInside(this.root, normalized);
1123
+ await this.#assertPathComponents(normalized);
1124
+ const info = await stat(absolute, { bigint: true }).catch((error) => {
1125
+ if (error.code === "ENOENT") return void 0;
1126
+ throw error;
1127
+ });
1128
+ if (!info) return void 0;
1129
+ const metadata = info.isFile() ? await this.#readFileMetadata(normalized) : void 0;
1130
+ const entry = {
1131
+ path: normalized,
1132
+ type: info.isDirectory() ? "directory" : "file",
1133
+ size: info.isFile() ? Number(info.size) : void 0,
1134
+ mtime: Number(info.mtimeNs) / 1e6,
1135
+ revision: info.isFile() ? `${info.dev}:${info.ino}:${info.birthtimeNs}:${info.ctimeNs}:${info.mtimeNs}` : void 0,
1136
+ mediaType: metadata?.mediaType,
1137
+ metadata: metadata?.metadata
1138
+ };
1139
+ if (includeDigest && info.isFile()) entry.digest = await fileDigest(absolute);
1140
+ return entry;
1141
+ }
1142
+ async mkdir(path, options = {}) {
1143
+ await this.#pathLock(this.root, path, async () => {
1144
+ await this.#assertPathComponents(path);
1145
+ await mkdir(resolveInside(this.root, path), { recursive: options.recursive ?? true });
1146
+ });
1147
+ }
1148
+ async removeEmptyDirectory(path) {
1149
+ await this.#pathLock(this.root, path, async () => {
1150
+ if (!normalizeWorkspacePath(path)) return;
1151
+ await this.#assertPathComponents(path, false);
1152
+ const absolute = resolveInside(this.root, path);
1153
+ const info = await lstat(absolute).catch((error) => {
1154
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
1155
+ });
1156
+ if (!info || info.isSymbolicLink()) return;
1157
+ await rmdir(absolute).catch((error) => {
1158
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
1159
+ });
1160
+ });
1161
+ }
1162
+ async rm(path, options = {}) {
1163
+ await this.#pathLock(this.root, path, () => this.#rm(path, options));
1164
+ }
1165
+ async #rm(path, options = {}) {
1166
+ await this.#assertPathComponents(path, false);
1167
+ const normalized = normalizeWorkspacePath(path);
1168
+ if (options.ifDigest !== void 0) {
1169
+ const current = await this.#stat(normalized);
1170
+ if (options.ifDigest === null ? current !== void 0 : current?.digest !== options.ifDigest) throw workspaceConflictError(path, options.ifDigest, current?.digest);
1171
+ }
1172
+ const metadata = await this.#prepareMetadataDirectories(normalized, false);
1173
+ const marker = this.#removalMarker(normalized);
1174
+ let createdMarker = false;
1175
+ if (metadata.root) {
1176
+ const directory = `${this.root}/.vitehub/file-removals`;
1177
+ await mkdir(directory, { mode: 448 }).catch((error) => {
1178
+ if (error.code !== "EEXIST") throw error;
1179
+ });
1180
+ const info = await lstat(directory);
1181
+ assertTrustedMetadata(directory, info, metadata.root);
1182
+ if (!info.isDirectory()) throw workspaceError(`[vitehub] Invalid Workspace removal directory.`);
1183
+ if (process.platform !== "win32") await applyMetadataPermissions(directory, metadata.root.mode & 504, metadata.root.gid);
1184
+ const file = await open(marker, "wx", 384).catch((error) => {
1185
+ if (error.code === "EEXIST") return void 0;
1186
+ throw error;
1187
+ });
1188
+ createdMarker = file !== void 0;
1189
+ await file?.close();
1190
+ }
1191
+ let missingTargetError;
1192
+ await rm(resolveInside(this.root, path), {
1193
+ recursive: options.recursive ?? false,
1194
+ force: options.force ?? false
1195
+ }).catch(async (error) => {
1196
+ if (error.code === "ERR_FS_EISDIR" && !options.recursive) {
1197
+ await rmdir(resolveInside(this.root, path));
1198
+ return;
1199
+ }
1200
+ throw error;
1201
+ }).catch(async (error) => {
1202
+ if (error.code === "ENOENT") {
1203
+ if (!options.force) missingTargetError = error;
1204
+ return;
1205
+ }
1206
+ if (createdMarker && !options.recursive) await rm(marker, { force: true });
1207
+ throw error;
1208
+ });
1209
+ for (const key of this.#files.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#files.delete(key);
1210
+ if (metadata.root) await rm(resolveInside(this.#fileMetadataRoot, normalized), {
1211
+ force: true,
1212
+ recursive: true
1213
+ });
1214
+ await rm(marker, { force: true });
1215
+ if (missingTargetError) throw missingTargetError;
1216
+ }
1217
+ async snapshot(options = {}) {
1218
+ await mkdir(this.root, { recursive: true });
1219
+ const snapshot = await this.#createSnapshot(options.name);
1220
+ this.#baseline = snapshot;
1221
+ return snapshot;
1222
+ }
1223
+ async diff(options = {}) {
1224
+ const from = options.from || this.#baseline;
1225
+ const to = await this.#createSnapshot();
1226
+ const entries = [];
1227
+ const keys = /* @__PURE__ */ new Set([...Object.keys(from?.entries || {}), ...Object.keys(to.entries)]);
1228
+ for (const path of [...keys].sort()) {
1229
+ const before = from && Object.hasOwn(from.entries, path) ? from.entries[path] : void 0;
1230
+ const after = Object.hasOwn(to.entries, path) ? to.entries[path] : void 0;
1231
+ if (!before && after) entries.push({
1232
+ path,
1233
+ type: "added",
1234
+ after
1235
+ });
1236
+ else if (before && !after) entries.push({
1237
+ path,
1238
+ type: "removed",
1239
+ before
1240
+ });
1241
+ 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({
1242
+ path,
1243
+ type: "modified",
1244
+ before,
1245
+ after
1246
+ });
1247
+ }
1248
+ return {
1249
+ from: from?.id,
1250
+ to: to.id,
1251
+ entries
1252
+ };
1253
+ }
1254
+ async getMeta(key) {
1255
+ return structuredClone((await this.#readMeta()).get(key));
1256
+ }
1257
+ async setMeta(key, value) {
1258
+ await this.#pathLock(this.root, ".vitehub/metadata", async () => {
1259
+ const metadata = new Map(await this.#readMeta());
1260
+ metadata.set(key, value);
1261
+ await this.#writeMeta(metadata);
1262
+ });
1263
+ }
1264
+ async #createSnapshot(name) {
1265
+ const entries = Object.create(null);
1266
+ for (const entry of await this.#list("", { recursive: true }, true)) entries[entry.path] = {
1267
+ type: entry.type,
1268
+ digest: entry.digest,
1269
+ metadata: entry.metadata,
1270
+ size: entry.size
1271
+ };
1272
+ return {
1273
+ id: await sha256({
1274
+ name,
1275
+ entries,
1276
+ createdAt: Date.now()
1277
+ }),
1278
+ name,
1279
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1280
+ entries
1281
+ };
1282
+ }
1283
+ async #readMeta() {
1284
+ const info = await stat(this.#metaPath).catch((error) => {
1285
+ if (error.code === "ENOENT") return void 0;
1286
+ throw error;
1287
+ });
1288
+ if (!info) {
1289
+ this.#metaCache = void 0;
1290
+ return /* @__PURE__ */ new Map();
1291
+ }
1292
+ if (this.#metaCache?.ino === info.ino && this.#metaCache.mtimeMs === info.mtimeMs && this.#metaCache.size === info.size) return this.#metaCache.value;
1293
+ const content = await readFile(this.#metaPath, "utf8").catch((error) => {
1294
+ if (error.code === "ENOENT") return void 0;
1295
+ throw error;
1296
+ });
1297
+ if (!content) {
1298
+ this.#metaCache = {
1299
+ ino: info.ino,
1300
+ mtimeMs: info.mtimeMs,
1301
+ size: info.size,
1302
+ value: /* @__PURE__ */ new Map()
1303
+ };
1304
+ return this.#metaCache.value;
1305
+ }
1306
+ const value = JSON.parse(content);
1307
+ const metadata = !value || Object(value) !== value || Array.isArray(value) ? /* @__PURE__ */ new Map() : new Map(Object.entries(Object(value)));
1308
+ this.#metaCache = {
1309
+ ino: info.ino,
1310
+ mtimeMs: info.mtimeMs,
1311
+ size: info.size,
1312
+ value: metadata
1313
+ };
1314
+ return metadata;
1315
+ }
1316
+ async #writeMeta(metadata) {
1317
+ const { dirname } = await import("node:path");
1318
+ const temp = `${this.#metaPath}.${randomUUID()}.tmp`;
1319
+ await mkdir(dirname(this.#metaPath), { recursive: true });
1320
+ try {
1321
+ await writeFile(temp, JSON.stringify(Object.fromEntries(metadata), null, 2));
1322
+ await rename(temp, this.#metaPath);
1323
+ } catch (error) {
1324
+ await rm(temp, { force: true }).catch(() => void 0);
1325
+ throw error;
1326
+ }
1327
+ }
1328
+ };
1329
+ function createLocalWorkspaceStore(root, options = {}) {
1330
+ if (!root) throw workspaceError("[vitehub] Local workspace store requires a root directory.");
1331
+ if (options.locks !== void 0 && options.locks !== "filesystem" && options.locks !== "process") throw workspaceError("[vitehub] Local workspace store locks must be \"filesystem\" or \"process\".");
1332
+ if (options.ignore !== void 0 && options.ignore !== "git") throw workspaceError("[vitehub] Local workspace store ignore must be \"git\".");
1333
+ return new LocalWorkspaceStore(root, options);
1334
+ }
1335
+ //#endregion
1336
+ //#region src/storage/owned-blob-prefix.ts
1337
+ /**
1338
+ * Returns `_vitehub/<root>`, or `_vitehub/<root>/<prefix>` for a custom prefix.
1339
+ * ViteHub owns every Workspace Blob object, so a custom prefix only nests below the owned root.
1340
+ */
1341
+ function ownedBlobPrefix(root, prefix, label) {
1342
+ if (prefix !== void 0 && !/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(prefix)) throw workspaceError(`[vitehub] ${label} Blob prefix must contain only letters, numbers, underscores, dashes, and single slashes.`);
1343
+ const owned = `${vitehubOwnedPrefix}${root}`;
1344
+ return prefix === void 0 ? owned : `${owned}/${prefix}`;
1345
+ }
1346
+ //#endregion
1347
+ //#region src/storage/provider.ts
1348
+ const MASKED_WORKSPACE_RUNTIME_VALUE = "********";
1349
+ function workspaceRepoName(name) {
1350
+ return name ? name.replace(/[^a-zA-Z0-9_.-]/g, "-") : void 0;
1351
+ }
1352
+ function isWorkspaceStore(value) {
1353
+ if (!value) return false;
1354
+ if (Object.hasOwn(value, "readFile")) return "readFile" in value && typeof value.readFile === "function";
1355
+ let prototype = Object.getPrototypeOf(value);
1356
+ while (prototype && prototype !== Object.prototype) {
1357
+ if (Object.hasOwn(prototype, "readFile")) return Object.hasOwn(prototype, "constructor") && prototype.constructor !== Object && "readFile" in value && typeof value.readFile === "function";
1358
+ prototype = Object.getPrototypeOf(prototype);
1359
+ }
1360
+ return false;
1361
+ }
1362
+ function gitHubWorkspaceOption(value) {
1363
+ return typeof value === "function" ? value : trimmed(value);
1364
+ }
1365
+ function resolveCloudflareArtifactsStore(config = {}, env = process.env) {
1366
+ const repoPrefix = trimmed(config.repoPrefix) ?? readEnv(env, "WORKSPACE_ARTIFACTS_REPO_PREFIX", "VITEHUB_WORKSPACE_ARTIFACTS_REPO_PREFIX") ?? "vitehub-workspace-";
1367
+ const repo = trimmed(config.repo) ?? workspaceRepoName(readEnv(env, "WORKSPACE_ARTIFACTS_REPO", "VITEHUB_WORKSPACE_ARTIFACTS_REPO"));
1368
+ return defu({
1369
+ binding: trimmed(config.binding) ?? readEnv(env, "WORKSPACE_ARTIFACTS_BINDING", "VITEHUB_WORKSPACE_ARTIFACTS_BINDING"),
1370
+ branch: trimmed(config.branch) ?? readEnv(env, "WORKSPACE_ARTIFACTS_BRANCH", "VITEHUB_WORKSPACE_ARTIFACTS_BRANCH"),
1371
+ namespace: trimmed(config.namespace) ?? readEnv(env, "WORKSPACE_ARTIFACTS_NAMESPACE", "VITEHUB_WORKSPACE_ARTIFACTS_NAMESPACE"),
1372
+ repo,
1373
+ repoPrefix
1374
+ }, {
1375
+ binding: "WORKSPACE_ARTIFACTS",
1376
+ namespace: "vitehub",
1377
+ provider: "cloudflare-artifacts"
1378
+ });
1379
+ }
1380
+ function resolveVercelBlobWorkspaceStore(config = {}, env = process.env) {
1381
+ const prefix = config.prefix ?? readEnv(env, "WORKSPACE_BLOB_PREFIX", "VITEHUB_WORKSPACE_BLOB_PREFIX");
1382
+ ownedBlobPrefix("workspaces", prefix, "Workspace");
1383
+ return {
1384
+ access: config.access ?? "private",
1385
+ ...prefix === void 0 ? {} : { prefix },
1386
+ provider: "vercel-blob",
1387
+ token: MASKED_WORKSPACE_RUNTIME_VALUE
1388
+ };
1389
+ }
1390
+ function resolveGitHubWorkspaceStore(config = {}, env = process.env, input = {}) {
1391
+ const branch = gitHubWorkspaceOption(config.branch) ?? readEnv(env, "VITEHUB_WORKSPACE_GITHUB_BRANCH");
1392
+ const root = config.root === "" ? "" : gitHubWorkspaceOption(config.root) ?? readEnv(env, "VITEHUB_WORKSPACE_GITHUB_ROOT");
1393
+ return {
1394
+ branch: branch ?? (input.runtime ? void 0 : "main"),
1395
+ ...config.database === void 0 ? {} : { database: config.database },
1396
+ provider: "github",
1397
+ ...config.refs ? { refs: { ...config.refs } } : {},
1398
+ repository: gitHubWorkspaceOption(config.repository) ?? gitHubWorkspaceOption(config.repo) ?? readEnv(env, "VITEHUB_WORKSPACE_GITHUB_REPOSITORY"),
1399
+ root: root ?? (input.runtime ? void 0 : ".vitehub/workspaces/<workspace>"),
1400
+ token: input.runtime ? gitHubWorkspaceOption(config.token) ?? readForgeEnv(forgeEnv.github.token, env) ?? "********" : MASKED_WORKSPACE_RUNTIME_VALUE
1401
+ };
1402
+ }
1403
+ function hasVercelWorkspaceBlobEnv(env) {
1404
+ return Boolean(readEnv(env, "BLOB_READ_WRITE_TOKEN"));
1405
+ }
1406
+ function normalizeWorkspaceStoreOptions(store, input = {}) {
1407
+ if (isWorkspaceStore(store)) return;
1408
+ if (input.dev && !store) return { provider: "local" };
1409
+ const env = input.env || process.env;
1410
+ const hosting = input.hosting || "";
1411
+ if (store?.provider === "cloudflare-artifacts") return resolveCloudflareArtifactsStore(store, env);
1412
+ if (store?.provider === "github") return resolveGitHubWorkspaceStore(store, env, input);
1413
+ if (store?.provider === "memory") return store;
1414
+ if (store?.provider === "vercel-blob") return resolveVercelBlobWorkspaceStore(store, env);
1415
+ if (store?.provider === "local" || store?.root) return defu(store, { provider: "local" });
1416
+ if (store && "provider" in store) throw workspaceError(`[vitehub] Unsupported workspace store provider: ${String(store.provider)}.`);
1417
+ if (hosting.includes("cloudflare")) return { provider: "memory" };
1418
+ if (hasVercelWorkspaceBlobEnv(env)) return resolveVercelBlobWorkspaceStore({}, env);
1419
+ if (hosting.includes("vercel")) return { provider: "memory" };
1420
+ return { provider: "local" };
1421
+ }
1422
+ function createWorkspaceStoreFromProvider(definition) {
1423
+ if (isWorkspaceStore(definition.store)) return definition.store;
1424
+ const rootDir = definition.rootDir || process.cwd();
1425
+ const runtimeConfig = getWorkspaceRuntimeConfig();
1426
+ const runtimeStore = runtimeConfig ? runtimeConfig.store : void 0;
1427
+ const store = normalizeWorkspaceStoreOptions(definition.store || runtimeStore, {
1428
+ env: typeof process !== "undefined" ? process.env : {},
1429
+ hosting: typeof process !== "undefined" ? process.env.VITEHUB_HOSTING : void 0,
1430
+ rootDir,
1431
+ runtime: true
1432
+ });
1433
+ if (store?.provider === "memory") return createMemoryWorkspaceStore();
1434
+ if (store?.provider === "cloudflare-artifacts" || store?.provider === "github" || store?.provider === "vercel-blob") {
1435
+ const loader = getWorkspaceHostedStoreLoader();
1436
+ if (!loader && store.provider === "github") return createGitHubWorkspaceStore(store, definition.name);
1437
+ if (!loader) throw workspaceError(`[vitehub] Hosted workspace store "${store.provider}" is not available in this runtime.`);
1438
+ return loader(store, definition.name);
1439
+ }
1440
+ return createLocalWorkspaceStore(store?.root ? resolve(rootDir, store.root) : runtimeConfig ? resolve(runtimeConfig.root, definition.name) : resolve(rootDir, ".vitehub/workspaces", definition.name), {
1441
+ ignore: store?.ignore,
1442
+ locks: store?.locks
1443
+ });
1444
+ }
1445
+ function isMaskedWorkspaceRuntimeValue(value) {
1446
+ return !value || value === "********";
1447
+ }
1448
+ function resolveRuntimeVercelBlobWorkspaceStore(config, env) {
1449
+ const token = readEnv(env, "BLOB_READ_WRITE_TOKEN");
1450
+ if (isMaskedWorkspaceRuntimeValue(token)) throw workspaceErrorDiagnostics.WORKSPACE_R0066({ message: "Missing runtime environment variable `BLOB_READ_WRITE_TOKEN` for Vercel workspace Blob storage." });
1451
+ return {
1452
+ ...config,
1453
+ token
1454
+ };
1455
+ }
1456
+ //#endregion
1457
+ export { resolveGitHubWorkspaceStore as a, ownedBlobPrefix as c, getWorkspaceRuntimeConfig as d, setWorkspaceRuntimeConfig as f, resolveCloudflareArtifactsStore as i, getWorkspaceHostedStoreLoader as l, isWorkspaceStore as n, resolveRuntimeVercelBlobWorkspaceStore as o, normalizeWorkspaceStoreOptions as r, resolveVercelBlobWorkspaceStore as s, createWorkspaceStoreFromProvider as t, setWorkspaceHostedStoreLoader as u };