@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,9 +1,17 @@
1
- import { _ as workspaceError, a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, f as sha256, g as workspaceConflict, l as normalizeWorkspacePath, o as matchesAny, p as assertWorkspaceDigest, r as contentToBytes, s as normalizeSafeWorkspacePath } from "./path-Cp59koVz.js";
2
- import { n as isPlainObject } from "./config-CHLLWklZ.js";
3
- import { c as getWorkspaceHostedStoreLoader, d as setWorkspaceRuntimeConfig, i as resolveGitHubWorkspaceStore, l as setWorkspaceHostedStoreLoader, r as resolveCloudflareArtifactsStore } from "./provider-B1yLjCJJ.js";
4
- import { a as createSnapshotFromEntries, o as diffSnapshots, t as createGitHubWorkspaceStore } from "./store-Dt_Jyys3.js";
5
- import { _ as getActiveCloudflareBinding } from "./shared-DTR1Hhma.js";
1
+ import { a as workspaceConflict, n as assertWorkspaceDigest, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { o as copyJsonFileMetadata } from "./target-jWhTdIuF.js";
3
+ import { a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, f as sha256, l as normalizeWorkspacePath, r as contentToBytes } from "./path--wrT_Azm.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
5
+ import { n as createSnapshotFromEntries, r as diffSnapshots } from "./utils-CgMZCHsX.js";
6
+ import { t as createWorkspaceGlobMatcher } from "./glob-Cjxms1t7.js";
7
+ import { t as isRecord } from "./object-Da1zyPCR.js";
8
+ import { T as getActiveCloudflareBinding } from "./shared-B3_EUk89.js";
9
+ import { a as resolveGitHubWorkspaceStore, d as setWorkspaceHostedStoreLoader, i as resolveCloudflareArtifactsStore, u as getWorkspaceHostedStoreLoader } from "./provider-9s4Ufkm5.js";
10
+ import { t as workspaceStoreDiscard } from "./discard-CNNtCozM.js";
11
+ import { t as createGitHubWorkspaceStore } from "./store-ybhyD38Z.js";
12
+ import { n as setWorkspaceRuntimeConfig } from "./config-B-863EgC.js";
6
13
  import { resolve } from "node:path";
14
+ import { boolean, check, object, optional, parse as parse$1, pipe, record, string, unknown } from "valibot";
7
15
  //#region src/storage/memory-fs.ts
8
16
  function copyBinaryData(data) {
9
17
  if (ArrayBuffer.isView(data)) return Uint8Array.from(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
@@ -39,7 +47,7 @@ var MemoryStats = class {
39
47
  var MemoryFS = class {
40
48
  #decoder = new TextDecoder();
41
49
  #encoder = new TextEncoder();
42
- entries = new Map([["/", {
50
+ entries = /* @__PURE__ */ new Map([["/", {
43
51
  kind: "dir",
44
52
  children: /* @__PURE__ */ new Set(),
45
53
  mtimeMs: Date.now()
@@ -77,7 +85,7 @@ var MemoryFS = class {
77
85
  }
78
86
  async mkdir(path, options) {
79
87
  const target = this.normalize(path);
80
- const recursive = isPlainObject(options) && options.recursive === true;
88
+ const recursive = isRecord(options) && options.recursive === true;
81
89
  if (target === "/") {
82
90
  if (recursive) return;
83
91
  throw memoryFsError("EEXIST", path);
@@ -117,7 +125,7 @@ var MemoryFS = class {
117
125
  async readFile(path, options) {
118
126
  const entry = this.#requireEntry(path);
119
127
  if (entry.kind !== "file") throw memoryFsError("EISDIR", path);
120
- return (isPlainObject(options) ? options.encoding : options) ? this.#decoder.decode(entry.data) : Uint8Array.from(entry.data);
128
+ return (isRecord(options) ? options.encoding : options) ? this.#decoder.decode(entry.data) : Uint8Array.from(entry.data);
121
129
  }
122
130
  async readdir(path) {
123
131
  return [...this.#requireDir(path).children].sort();
@@ -172,13 +180,30 @@ var MemoryFS = class {
172
180
  }
173
181
  };
174
182
  function memoryFsError(code, path) {
175
- return Object.assign(/* @__PURE__ */ new Error(`${code}: ${path}`), { code });
183
+ return Object.assign(workspaceErrorDiagnostics.WORKSPACE_R0065({ message: `${code}: ${path}` }), { code });
176
184
  }
177
185
  //#endregion
178
186
  //#region src/providers/cloudflare/artifacts-store.ts
179
187
  const dir = "/workspace";
180
188
  const fileMetadataPath = ".vitehub/files.json";
189
+ const fileMetadataJournalPath = ".vitehub/files.pending.json";
181
190
  const tokenRefreshWindow = 6e4;
191
+ /** How long a Store without staged writes trusts the branch head that it loaded, in milliseconds. */
192
+ const remoteHeadCacheMs = 5e3;
193
+ const fileMetadataSchema = object({
194
+ mediaType: optional(string()),
195
+ metadata: optional(pipe(record(string(), unknown()), check((value) => value.source === void 0 || typeof value.source === "string", "metadata.source must be a string when provided")))
196
+ });
197
+ const fileMetadataFilesSchema = record(string(), fileMetadataSchema);
198
+ const fileMetadataJournalSchema = object({
199
+ path: string(),
200
+ existed: boolean(),
201
+ digest: string(),
202
+ metadata: fileMetadataSchema
203
+ });
204
+ function parseJson(content) {
205
+ return JSON.parse(new TextDecoder().decode(content));
206
+ }
182
207
  function sameSnapshotEntry(left, right) {
183
208
  return left?.digest === right?.digest && left?.type === right?.type && left?.size === right?.size && JSON.stringify(left?.metadata) === JSON.stringify(right?.metadata);
184
209
  }
@@ -229,7 +254,12 @@ var CloudflareArtifactsWorkspaceStore = class {
229
254
  #files = /* @__PURE__ */ new Map();
230
255
  #fs;
231
256
  #head;
257
+ #loadedAt = 0;
232
258
  #pendingCommit;
259
+ /** Whether files or metadata changed since the last load or push. */
260
+ #staged = false;
261
+ /** Metadata written since the last load or push, by absolute path. A rebase writes it again on the new head. */
262
+ #stagedMeta = /* @__PURE__ */ new Map();
233
263
  #remote;
234
264
  #ready;
235
265
  #mutationQueue = Promise.resolve();
@@ -238,6 +268,17 @@ var CloudflareArtifactsWorkspaceStore = class {
238
268
  this.options = options;
239
269
  this.workspaceName = workspaceName;
240
270
  }
271
+ /** Drops the staged writes. The next call clones the branch again, as the first call does. */
272
+ async [workspaceStoreDiscard]() {
273
+ await this.#mutate(async () => {
274
+ this.#files = /* @__PURE__ */ new Map();
275
+ this.#head = void 0;
276
+ this.#pendingCommit = void 0;
277
+ this.#ready = void 0;
278
+ this.#staged = false;
279
+ this.#stagedMeta = /* @__PURE__ */ new Map();
280
+ });
281
+ }
241
282
  async readFile(path) {
242
283
  const normalized = normalizeSafeWorkspacePath(path);
243
284
  await this.#ensure();
@@ -252,7 +293,7 @@ var CloudflareArtifactsWorkspaceStore = class {
252
293
  path: normalized,
253
294
  content,
254
295
  mediaType: fileMetadata?.mediaType,
255
- metadata: fileMetadata?.metadata
296
+ metadata: structuredClone(fileMetadata?.metadata)
256
297
  };
257
298
  }
258
299
  async writeFile(path, file) {
@@ -279,7 +320,8 @@ var CloudflareArtifactsWorkspaceStore = class {
279
320
  for (const [absolute, entry] of this.#fs.entries) {
280
321
  if (absolute === dir || !absolute.startsWith(`${dir}/`)) continue;
281
322
  const path = normalizeWorkspacePath(absolute.slice(`${dir}/`.length));
282
- if (!path || path === ".git" || path.startsWith(".git/") || path === ".vitehub" || path.startsWith(".vitehub/")) continue;
323
+ const root = path.split("/")[0]?.toLowerCase();
324
+ if (!path || root === ".git" || root === ".vitehub") continue;
283
325
  if (isExcludedWorkspacePath(path, options.exclude)) continue;
284
326
  if (normalizedPrefix) {
285
327
  if (path === normalizedPrefix) continue;
@@ -291,7 +333,7 @@ var CloudflareArtifactsWorkspaceStore = class {
291
333
  entries.push({
292
334
  digest: await sha256(entry.data),
293
335
  mediaType: fileMetadata?.mediaType,
294
- metadata: fileMetadata?.metadata,
336
+ metadata: structuredClone(fileMetadata?.metadata),
295
337
  mtime: entry.mtimeMs,
296
338
  path,
297
339
  size: entry.data.byteLength,
@@ -305,9 +347,10 @@ var CloudflareArtifactsWorkspaceStore = class {
305
347
  }
306
348
  return entries.sort((a, b) => a.path.localeCompare(b.path));
307
349
  }
308
- async glob(pattern, _options = {}) {
350
+ async glob(pattern, options = {}) {
309
351
  const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
310
- return (await this.list("", { recursive: true })).filter((entry) => entry.type === "file" && matchesAny(entry.path, patterns));
352
+ const { cwd, matches } = createWorkspaceGlobMatcher(patterns, options);
353
+ return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
311
354
  }
312
355
  async stat(path) {
313
356
  const normalized = normalizeSafeWorkspacePath(path);
@@ -322,7 +365,7 @@ var CloudflareArtifactsWorkspaceStore = class {
322
365
  return {
323
366
  digest: bytes ? await sha256(bytes) : void 0,
324
367
  mediaType: fileMetadata?.mediaType,
325
- metadata: fileMetadata?.metadata,
368
+ metadata: structuredClone(fileMetadata?.metadata),
326
369
  mtime: stat.mtimeMs,
327
370
  path: normalized,
328
371
  size: stat.isFile() ? stat.size : void 0,
@@ -334,10 +377,21 @@ var CloudflareArtifactsWorkspaceStore = class {
334
377
  await this.#ensure();
335
378
  await this.#mutate(() => this.#fs.promises.mkdir(this.#absolute(normalized), { recursive: options.recursive ?? true }));
336
379
  }
380
+ async removeEmptyDirectory(path) {
381
+ const normalized = normalizeSafeWorkspacePath(path, { allowEmpty: true });
382
+ if (!normalized) return;
383
+ await this.#ensure();
384
+ await this.#mutate(async () => {
385
+ await this.#fs.promises.rmdir(this.#absolute(normalized)).catch((error) => {
386
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
387
+ });
388
+ });
389
+ }
337
390
  async rm(path, options = {}) {
338
391
  const normalized = normalizeSafeWorkspacePath(path);
339
392
  await this.#ensure();
340
393
  await this.#mutate(async () => {
394
+ if (options.ifDigest !== void 0) assertWorkspaceDigest(path, options.ifDigest, (await this.#stat(normalized))?.digest);
341
395
  const absolute = this.#absolute(normalized);
342
396
  const stat = await this.#fs.promises.stat(absolute).catch(() => void 0);
343
397
  if (!stat) {
@@ -347,7 +401,9 @@ var CloudflareArtifactsWorkspaceStore = class {
347
401
  if (stat.isDirectory() && !options.recursive) {
348
402
  if ((await this.#fs.promises.readdir(absolute)).length) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
349
403
  }
350
- if (!this.#fs.deleteTree(absolute) && !options.force) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
404
+ const removed = this.#fs.deleteTree(absolute);
405
+ if (!removed && !options.force) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
406
+ if (removed) this.#staged = true;
351
407
  for (const key of this.#files.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#files.delete(key);
352
408
  await this.#writeFileMetadata();
353
409
  });
@@ -358,54 +414,75 @@ var CloudflareArtifactsWorkspaceStore = class {
358
414
  }
359
415
  async rebase(options = {}) {
360
416
  await this.#ensure();
361
- await this.#mutate(async () => {
362
- const baseline = this.#baseline;
363
- const current = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
364
- const changes = diffSnapshots(baseline, current).entries.filter((change) => change.before?.type === "file" || change.after?.type === "file");
365
- const local = /* @__PURE__ */ new Map();
366
- for (const change of changes) local.set(change.path, change.after ? await this.#readFile(change.path) : void 0);
367
- const previous = {
368
- baseline: this.#baseline,
417
+ await this.#mutate(async () => await this.#rebase(options));
418
+ }
419
+ /** Load the current branch head and write the staged changes on it again. A path that changed on both sides fails with its name in `details.paths`. */
420
+ async #rebase(options) {
421
+ const baseline = this.#baseline;
422
+ const current = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
423
+ const changes = diffSnapshots(baseline, current).entries.filter((change) => change.before?.type === "file" || change.after?.type === "file");
424
+ const local = /* @__PURE__ */ new Map();
425
+ for (const change of changes) local.set(change.path, change.after ? await this.#readFile(change.path) : void 0);
426
+ const previous = {
427
+ baseline: this.#baseline,
428
+ branch: this.#branch,
429
+ files: this.#files,
430
+ fs: this.#fs,
431
+ head: this.#head,
432
+ pendingCommit: this.#pendingCommit,
433
+ remote: this.#remote,
434
+ staged: this.#staged,
435
+ stagedMeta: this.#stagedMeta
436
+ };
437
+ const restore = () => {
438
+ this.#baseline = previous.baseline;
439
+ this.#branch = previous.branch;
440
+ this.#files = previous.files;
441
+ this.#fs = previous.fs;
442
+ this.#head = previous.head;
443
+ this.#pendingCommit = previous.pendingCommit;
444
+ this.#remote = previous.remote;
445
+ this.#staged = previous.staged;
446
+ this.#stagedMeta = previous.stagedMeta;
447
+ };
448
+ try {
449
+ this.#files = /* @__PURE__ */ new Map();
450
+ this.#pendingCommit = void 0;
451
+ await this.#load();
452
+ const remoteChanges = new Map(diffSnapshots(baseline, this.#baseline).entries.map((change) => [change.path, change]));
453
+ const takeRemote = new Set(options.takeRemote || []);
454
+ const conflicts = changes.filter((change) => remoteChanges.has(change.path) && !takeRemote.has(change.path) && !sameSnapshotEntry(current.entries[change.path], this.#baseline?.entries[change.path])).map((change) => change.path).sort();
455
+ if (conflicts.length) throw workspaceConflict(`[vitehub] Cloudflare Artifacts Workspace Store rebase conflict: ${conflicts.join(", ")} changed locally and remotely.`, { details: {
369
456
  branch: this.#branch,
370
- files: this.#files,
371
- fs: this.#fs,
372
- head: this.#head,
373
- pendingCommit: this.#pendingCommit,
374
- remote: this.#remote
375
- };
376
- const restore = () => {
377
- this.#baseline = previous.baseline;
378
- this.#branch = previous.branch;
379
- this.#files = previous.files;
380
- this.#fs = previous.fs;
381
- this.#head = previous.head;
382
- this.#pendingCommit = previous.pendingCommit;
383
- this.#remote = previous.remote;
384
- };
385
- try {
386
- this.#files = /* @__PURE__ */ new Map();
387
- this.#pendingCommit = void 0;
388
- await this.#load();
389
- const remoteChanges = new Map(diffSnapshots(baseline, this.#baseline).entries.map((change) => [change.path, change]));
390
- const takeRemote = new Set(options.takeRemote || []);
391
- for (const change of changes) if (remoteChanges.has(change.path) && !takeRemote.has(change.path) && !sameSnapshotEntry(current.entries[change.path], this.#baseline?.entries[change.path])) throw workspaceConflict(`[vitehub] Cloudflare Artifacts Workspace Store rebase conflict: ${change.path} changed locally and remotely.`);
392
- for (const change of changes) {
393
- if (remoteChanges.has(change.path) && takeRemote.has(change.path)) continue;
394
- const file = local.get(change.path);
395
- if (file) await this.#writeFile(change.path, file);
396
- else {
397
- this.#fs.deleteTree(this.#absolute(change.path));
398
- this.#files.delete(change.path);
399
- await this.#writeFileMetadata();
400
- }
457
+ paths: conflicts
458
+ } });
459
+ let replayed = 0;
460
+ for (const change of changes) {
461
+ if (remoteChanges.has(change.path) && takeRemote.has(change.path)) continue;
462
+ replayed++;
463
+ const file = local.get(change.path);
464
+ if (file) await this.#writeFile(change.path, file);
465
+ else {
466
+ this.#fs.deleteTree(this.#absolute(change.path));
467
+ this.#files.delete(change.path);
468
+ await this.#writeFileMetadata();
401
469
  }
402
- } catch (error) {
403
- restore();
404
- throw error;
405
470
  }
406
- });
471
+ for (const [path, bytes] of previous.stagedMeta) if (bytes.byteLength) await this.#fs.promises.writeFile(path, bytes);
472
+ else this.#fs.deleteTree(path);
473
+ this.#stagedMeta = new Map(previous.stagedMeta);
474
+ this.#staged = replayed > 0 || previous.stagedMeta.size > 0;
475
+ } catch (error) {
476
+ restore();
477
+ throw error;
478
+ }
407
479
  }
408
- async #createSnapshot(options) {
480
+ /**
481
+ * Commit and push the staged changes. When the branch moved since the Store loaded, for example because another
482
+ * isolate pushed, the Store loads the new head, writes the staged changes on it again, and pushes once more. A path
483
+ * that changed on both sides, or a second move, fails with `WORKSPACE_CONFLICT`.
484
+ */
485
+ async #createSnapshot(options, retry = true) {
409
486
  const git = await import("isomorphic-git");
410
487
  const http = await import("isomorphic-git/http/web");
411
488
  const matrix = await git.statusMatrix({
@@ -413,28 +490,30 @@ var CloudflareArtifactsWorkspaceStore = class {
413
490
  fs: this.#fs,
414
491
  ignored: true
415
492
  });
416
- let changed = false;
493
+ const removed = [];
494
+ const added = [];
417
495
  for (const [filepath, head, workdir, stage] of matrix) {
418
496
  if (filepath.startsWith(".git/")) continue;
419
- if (workdir === 0 && (head !== 0 || stage !== 0)) {
420
- await git.remove({
421
- dir,
422
- filepath,
423
- fs: this.#fs
424
- });
425
- changed = true;
426
- } else if (workdir !== stage) {
427
- await git.add({
428
- dir,
429
- filepath,
430
- force: true,
431
- fs: this.#fs
432
- });
433
- changed = true;
434
- }
497
+ if (workdir === 0 && (head !== 0 || stage !== 0)) removed.push(filepath);
498
+ else if (workdir !== stage) added.push(filepath);
435
499
  }
436
- if (changed || !this.#head && !this.#pendingCommit) this.#pendingCommit = await git.commit({
437
- author: {
500
+ if (removed.length) await git.remove({
501
+ dir,
502
+ filepath: removed,
503
+ fs: this.#fs
504
+ });
505
+ if (added.length) await git.add({
506
+ dir,
507
+ filepath: added,
508
+ force: true,
509
+ fs: this.#fs
510
+ });
511
+ if (removed.length > 0 || added.length > 0 || !this.#head && !this.#pendingCommit) this.#pendingCommit = await git.commit({
512
+ author: options.author ?? {
513
+ email: "workspace@vitehub.dev",
514
+ name: "ViteHub Workspace"
515
+ },
516
+ committer: {
438
517
  email: "workspace@vitehub.dev",
439
518
  name: "ViteHub Workspace"
440
519
  },
@@ -458,12 +537,21 @@ var CloudflareArtifactsWorkspaceStore = class {
458
537
  url: this.#remote
459
538
  });
460
539
  } catch (error) {
461
- if (isNonFastForward(error)) throw workspaceConflict(`[vitehub] Workspace "${this.workspaceName}" changed remotely while snapshotting branch "${this.#branch}". Reload the Workspace before retrying.`, { cause: error });
540
+ if (isNonFastForward(error)) {
541
+ if (retry) {
542
+ await this.#rebase({});
543
+ return await this.#createSnapshot(options, false);
544
+ }
545
+ throw workspaceConflict(`[vitehub] Workspace "${this.workspaceName}" changed remotely while snapshotting branch "${this.#branch}". Reload the Workspace before retrying.`, { cause: error });
546
+ }
462
547
  throw error;
463
548
  }
464
549
  this.#head = id;
465
550
  this.#pendingCommit = void 0;
466
551
  }
552
+ this.#staged = false;
553
+ this.#stagedMeta = /* @__PURE__ */ new Map();
554
+ this.#loadedAt = Date.now();
467
555
  const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
468
556
  this.#baseline = {
469
557
  ...snapshot,
@@ -474,7 +562,9 @@ var CloudflareArtifactsWorkspaceStore = class {
474
562
  async diff(options = {}) {
475
563
  await this.#ensure();
476
564
  return await this.#mutate(async () => {
477
- return diffSnapshots(options.from || this.#baseline, await createSnapshotFromEntries(await this.#listEntries("", { recursive: true })));
565
+ const from = options.from || this.#baseline;
566
+ const to = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
567
+ return diffSnapshots(from, to);
478
568
  });
479
569
  }
480
570
  async getMeta(key) {
@@ -482,23 +572,48 @@ var CloudflareArtifactsWorkspaceStore = class {
482
572
  await this.#ensure();
483
573
  return await this.#mutate(async () => {
484
574
  const content = await this.#fs.promises.readFile(path).catch(() => void 0);
485
- if (!content) return void 0;
486
- return JSON.parse(new TextDecoder().decode(contentToBytes(content)));
575
+ const bytes = content === void 0 ? void 0 : contentToBytes(content);
576
+ if (!bytes?.byteLength) return void 0;
577
+ return JSON.parse(new TextDecoder().decode(bytes));
487
578
  });
488
579
  }
489
580
  async setMeta(key, value) {
490
581
  const path = this.#metaAbsolute(key);
491
582
  await this.#ensure();
492
- await this.#mutate(() => this.#fs.promises.writeFile(path, contentToBytes(JSON.stringify(value))));
583
+ await this.#mutate(async () => {
584
+ const bytes = value === void 0 ? /* @__PURE__ */ new Uint8Array() : contentToBytes(JSON.stringify(value));
585
+ if (bytes.byteLength) await this.#fs.promises.writeFile(path, bytes);
586
+ else this.#fs.deleteTree(path);
587
+ this.#stagedMeta.set(path, bytes);
588
+ this.#staged = true;
589
+ });
493
590
  }
494
591
  async #writeFile(path, file) {
495
- await this.#fs.promises.writeFile(this.#absolute(path), contentToBytes(file.content));
592
+ file = {
593
+ ...file,
594
+ metadata: copyJsonFileMetadata(path, file.metadata)
595
+ };
596
+ const existed = await this.#fs.promises.stat(this.#absolute(path)).then((stat) => stat.isFile()).catch(() => false);
597
+ const content = contentToBytes(file.content);
598
+ const digest = await sha256(content);
599
+ await this.#fs.promises.writeFile(this.#internalAbsolute(fileMetadataJournalPath), JSON.stringify({
600
+ path,
601
+ existed,
602
+ digest,
603
+ metadata: {
604
+ mediaType: file.mediaType,
605
+ metadata: file.metadata
606
+ }
607
+ }));
608
+ await this.#fs.promises.writeFile(this.#absolute(path), content);
609
+ this.#staged = true;
496
610
  if (file.mediaType !== void 0 || file.metadata !== void 0) this.#files.set(path, {
497
611
  mediaType: file.mediaType,
498
612
  metadata: file.metadata
499
613
  });
500
614
  else this.#files.delete(path);
501
615
  await this.#writeFileMetadata();
616
+ this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
502
617
  }
503
618
  #absolute(path) {
504
619
  return `${dir}/${path}`;
@@ -512,9 +627,34 @@ var CloudflareArtifactsWorkspaceStore = class {
512
627
  }
513
628
  async #loadFileMetadata() {
514
629
  const content = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataPath)).catch(() => void 0);
515
- if (!content) return;
516
- const files = JSON.parse(new TextDecoder().decode(content));
517
- this.#files = new Map(Object.entries(files));
630
+ if (content) {
631
+ const files = parse$1(fileMetadataFilesSchema, parseJson(contentToBytes(content)));
632
+ this.#files = new Map(Object.entries(files).map(([path, file]) => [path, {
633
+ ...file,
634
+ metadata: copyJsonFileMetadata(path, file.metadata)
635
+ }]));
636
+ }
637
+ const pending = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataJournalPath)).catch(() => void 0);
638
+ if (!pending) return;
639
+ let journal;
640
+ try {
641
+ journal = parse$1(fileMetadataJournalSchema, parseJson(contentToBytes(pending)));
642
+ journal.metadata.metadata = copyJsonFileMetadata(journal.path, journal.metadata.metadata);
643
+ } catch {
644
+ this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
645
+ return;
646
+ }
647
+ try {
648
+ if (journal.path && await this.#fs.promises.stat(this.#absolute(journal.path)).then((stat) => stat.isFile()).catch(() => false)) {
649
+ const content = await this.#fs.promises.readFile(this.#absolute(journal.path));
650
+ if (await sha256(contentToBytes(content)) !== journal.digest) return;
651
+ if (journal.metadata && (journal.metadata.mediaType !== void 0 || journal.metadata.metadata !== void 0)) this.#files.set(journal.path, journal.metadata);
652
+ else this.#files.delete(journal.path);
653
+ await this.#writeFileMetadata();
654
+ }
655
+ } finally {
656
+ this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
657
+ }
518
658
  }
519
659
  async #writeFileMetadata() {
520
660
  const path = this.#internalAbsolute(fileMetadataPath);
@@ -550,9 +690,62 @@ var CloudflareArtifactsWorkspaceStore = class {
550
690
  if (!binding) throw workspaceError(`[vitehub] Cloudflare Artifacts binding "${bindingName}" not found.`);
551
691
  return binding;
552
692
  }
693
+ /**
694
+ * Load the branch once. A Store without staged changes that loaded more than `remoteHeadCacheMs` ago asks for the
695
+ * branch head again and loads it when it moved, so a Store that one isolate keeps for many requests sees pushes from
696
+ * other writers before it stages new changes.
697
+ */
553
698
  async #ensure() {
554
- this.#ready ||= this.#load();
699
+ const wasReady = !!this.#ready;
700
+ this.#ready ||= this.#load().catch((error) => {
701
+ this.#ready = void 0;
702
+ throw error;
703
+ });
555
704
  await this.#ready;
705
+ if (!wasReady) return;
706
+ await this.#mutate(async () => {
707
+ if (this.#staged || this.#pendingCommit || Date.now() - this.#loadedAt < remoteHeadCacheMs) return;
708
+ if (await this.#remoteHead() === this.#head) {
709
+ this.#loadedAt = Date.now();
710
+ return;
711
+ }
712
+ const previous = {
713
+ baseline: this.#baseline,
714
+ branch: this.#branch,
715
+ files: this.#files,
716
+ fs: this.#fs,
717
+ head: this.#head,
718
+ remote: this.#remote
719
+ };
720
+ try {
721
+ this.#files = /* @__PURE__ */ new Map();
722
+ this.#head = void 0;
723
+ await this.#load();
724
+ } catch (error) {
725
+ this.#baseline = previous.baseline;
726
+ this.#branch = previous.branch;
727
+ this.#files = previous.files;
728
+ this.#fs = previous.fs;
729
+ this.#head = previous.head;
730
+ this.#remote = previous.remote;
731
+ throw error;
732
+ }
733
+ });
734
+ }
735
+ async #remoteHead() {
736
+ const git = await import("isomorphic-git");
737
+ const http = await import("isomorphic-git/http/web");
738
+ const token = await this.#writeToken();
739
+ const branchRef = `refs/heads/${this.#branch}`;
740
+ return (await git.listServerRefs({
741
+ http,
742
+ onAuth: () => ({
743
+ password: token,
744
+ username: "x"
745
+ }),
746
+ prefix: branchRef,
747
+ url: this.#remote
748
+ })).find((ref) => ref.ref === branchRef)?.oid;
556
749
  }
557
750
  #mutate(operation) {
558
751
  const result = this.#mutationQueue.then(operation);
@@ -638,6 +831,9 @@ var CloudflareArtifactsWorkspaceStore = class {
638
831
  ...baseline,
639
832
  id: this.#head
640
833
  } : baseline;
834
+ this.#loadedAt = Date.now();
835
+ this.#staged = false;
836
+ this.#stagedMeta = /* @__PURE__ */ new Map();
641
837
  }
642
838
  };
643
839
  function createCloudflareArtifactsWorkspaceStore(options, workspaceName) {
@@ -645,27 +841,37 @@ function createCloudflareArtifactsWorkspaceStore(options, workspaceName) {
645
841
  }
646
842
  //#endregion
647
843
  //#region src/hosted.ts
648
- function installHostedWorkspaceRuntime() {
844
+ function installHostedGitHubWorkspaceStore() {
649
845
  const existingWorkspaceHostedStoreLoader = getWorkspaceHostedStoreLoader();
650
846
  setWorkspaceHostedStoreLoader((storeOptions, workspaceName) => {
651
- if (storeOptions.provider === "cloudflare-artifacts") return createCloudflareArtifactsWorkspaceStore(storeOptions, workspaceName);
652
- if (storeOptions.provider === "github") return createGitHubWorkspaceStore(storeOptions, workspaceName);
653
- if (existingWorkspaceHostedStoreLoader) return existingWorkspaceHostedStoreLoader(storeOptions, workspaceName);
654
- throw workspaceError("[vitehub] Hosted workspace runtime cannot load unsupported hosted store.");
847
+ if (storeOptions.driver === "github") return createGitHubWorkspaceStore(storeOptions, workspaceName);
848
+ return existingWorkspaceHostedStoreLoader?.(storeOptions, workspaceName);
655
849
  });
656
850
  }
851
+ function installHostedCloudflareArtifactsWorkspaceStore() {
852
+ const existingWorkspaceHostedStoreLoader = getWorkspaceHostedStoreLoader();
853
+ setWorkspaceHostedStoreLoader((storeOptions, workspaceName) => {
854
+ if (storeOptions.driver === "cloudflare") return createCloudflareArtifactsWorkspaceStore(storeOptions, workspaceName);
855
+ return existingWorkspaceHostedStoreLoader?.(storeOptions, workspaceName);
856
+ });
857
+ }
858
+ function installHostedWorkspaceRuntime() {
859
+ installHostedGitHubWorkspaceStore();
860
+ installHostedCloudflareArtifactsWorkspaceStore();
861
+ }
657
862
  function configureHostedWorkspaceRuntime(options = {}) {
658
863
  const root = resolve(process.cwd(), options.root || ".vitehub/workspaces");
659
- const store = options.store?.provider === "github" ? resolveGitHubWorkspaceStore(options.store, options.env || {}, { runtime: true }) : options.store?.provider === "vercel-blob" ? void 0 : resolveCloudflareArtifactsStore(options.store, options.env);
864
+ const store = options.store?.driver === "github" ? resolveGitHubWorkspaceStore(options.store, options.env || {}, { runtime: true }) : options.store?.driver === "vercel" ? void 0 : resolveCloudflareArtifactsStore(options.store, options.env);
660
865
  if (!store) throw workspaceError("[vitehub] Vercel Blob hosted workspace runtime must use @vite-hub/workspace/internal/runtime/hosted-vercel-blob.");
661
866
  const config = {
662
867
  assets: options.assets,
663
868
  root,
664
869
  store
665
870
  };
666
- installHostedWorkspaceRuntime();
871
+ if (store.driver === "github") installHostedGitHubWorkspaceStore();
872
+ else installHostedCloudflareArtifactsWorkspaceStore();
667
873
  setWorkspaceRuntimeConfig(config);
668
874
  return config;
669
875
  }
670
876
  //#endregion
671
- export { installHostedWorkspaceRuntime as n, createCloudflareArtifactsWorkspaceStore as r, configureHostedWorkspaceRuntime as t };
877
+ export { createCloudflareArtifactsWorkspaceStore as a, installHostedWorkspaceRuntime as i, installHostedCloudflareArtifactsWorkspaceStore as n, installHostedGitHubWorkspaceStore as r, configureHostedWorkspaceRuntime as t };