@vite-hub/workspace 0.0.3 → 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 (129) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -58
  3. package/dist/{ai-nmHdzjCM.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  4. package/dist/{ai-Ce3PtWFW.js → ai-BZyLwULx.js} +147 -66
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-DfBV5kmw.js} +3 -2
  8. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  9. package/dist/blob-database.d.ts +521 -0
  10. package/dist/blob-database.js +601 -0
  11. package/dist/cloudflare.d.ts +5 -6
  12. package/dist/cloudflare.js +1 -1
  13. package/dist/config-B7dmzDX3.js +1112 -0
  14. package/dist/{config-3I1BnsdO.d.ts → config-DLKdaFWN.d.ts} +1 -2
  15. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  16. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  17. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  18. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  19. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  20. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  21. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  22. package/dist/file-C0_aPWSS.js +26 -0
  23. package/dist/file-metadata-CxDy-E2H.js +58 -0
  24. package/dist/{files-QRV55OCx.js → files-C7Px8uaC.js} +21 -10
  25. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  26. package/dist/{github-CfA5vpJ5.js → github-CPxHtFB7.js} +36 -34
  27. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  28. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  29. package/dist/glob--XcLlcml.js +22 -0
  30. package/dist/glob--kNYDbfU.js +30 -0
  31. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  32. package/dist/host-CFnrTXTK.js +1086 -0
  33. package/dist/{hosted-C1-tTTTf.js → hosted-acMA5XyL.js} +216 -43
  34. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  35. package/dist/hosted-vercel-blob.d.ts +5 -6
  36. package/dist/hosted-vercel-blob.js +1 -1
  37. package/dist/hosted.d.ts +6 -7
  38. package/dist/hosted.js +1 -1
  39. package/dist/index.d.ts +76 -64
  40. package/dist/index.js +162 -457
  41. package/dist/inspect-BoObD2cJ.js +167 -0
  42. package/dist/internal/path.d.ts +2 -0
  43. package/dist/internal/path.js +2 -0
  44. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  45. package/dist/loader.d.ts +5 -6
  46. package/dist/loader.js +3 -2
  47. package/dist/mcp-resources-BREFCmtn.js +39 -0
  48. package/dist/memory-BbwOqDXl.js +248 -0
  49. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  50. package/dist/mountx.d.ts +4 -6
  51. package/dist/mountx.js +10 -8
  52. package/dist/nitro.d.ts +1 -1
  53. package/dist/nitro.js +1 -1
  54. package/dist/nuxt.d.ts +13 -12
  55. package/dist/nuxt.js +10 -8
  56. package/dist/operations-BcpWr41m.js +159 -0
  57. package/dist/operations-CGqY1XeG.js +965 -0
  58. package/dist/operations-DnOwKsJT.d.ts +136 -0
  59. package/dist/operations.d.ts +53 -0
  60. package/dist/operations.js +2 -0
  61. package/dist/{path-CNI6wKIU.js → path-CNAwN7pw.js} +34 -35
  62. package/dist/path-DrSIenjj.js +59 -0
  63. package/dist/path-zHxQUbqa.d.ts +9 -0
  64. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  65. package/dist/provider-kXjfli9u.js +1457 -0
  66. package/dist/providers/github/store.d.ts +3 -5
  67. package/dist/providers/github/store.js +1 -1
  68. package/dist/registry-Bp-8UUfG.js +129 -0
  69. package/dist/{registry-BIQVCBWI.d.ts → registry-Cg1TJVVZ.d.ts} +3 -4
  70. package/dist/{request-execution-u9mgUXKX.js → request-execution-Dk9rY-Yh.js} +24 -20
  71. package/dist/rolldown-runtime-B4iAMlE-.js +35 -0
  72. package/dist/runtime/assets.d.ts +3 -5
  73. package/dist/runtime/assets.js +9 -6
  74. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  75. package/dist/runtime/empty-registry.d.ts +1 -2
  76. package/dist/runtime/state.d.ts +4 -4
  77. package/dist/runtime/state.js +10 -7
  78. package/dist/runtime/workspace.d.ts +1 -1
  79. package/dist/runtime/workspace.js +1 -1
  80. package/dist/runtime.d.ts +84 -15
  81. package/dist/runtime.js +561 -108
  82. package/dist/{search-C4REyHj9.js → search-CrTmXj5h.js} +10 -9
  83. package/dist/server-BNQ-Nbjj.js +290 -0
  84. package/dist/server.d.ts +22 -34
  85. package/dist/server.js +2 -355
  86. package/dist/shared-DalXdP0i.js +2158 -0
  87. package/dist/source-metadata.d.ts +7 -1
  88. package/dist/source-metadata.js +34 -2
  89. package/dist/{state-TTqa3x3Y.d.ts → state-B8zbLi5t.d.ts} +14 -13
  90. package/dist/store-CXgmu-uw.js +1729 -0
  91. package/dist/{sync-DiuDmSGk.js → sync-CN6ec-5M.js} +62 -41
  92. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  93. package/dist/test.d.ts +1 -1
  94. package/dist/test.js +1 -1
  95. package/dist/token-CO62GglH.js +61 -0
  96. package/dist/{types-60Yn149G.d.ts → types-DeK9GIxy.d.ts} +348 -49
  97. package/dist/{use-CsV3oIxH.js → use-BQj7nSz6.js} +200 -45
  98. package/dist/{use-CUFSnFCS.d.ts → use-DhwhbAVV.d.ts} +34 -12
  99. package/dist/utils-Blrh4N2n.js +545 -0
  100. package/dist/vite-BEvgU2GY.js +20909 -0
  101. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  102. package/dist/vite.d.ts +2 -50
  103. package/dist/vite.js +2 -2
  104. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  105. package/dist/workspace-6pxkOuxr.js +1286 -0
  106. package/dist/workspace-BWJQBK1u.d.ts +7 -0
  107. package/package.json +90 -59
  108. package/dist/chunk-8H4AJuhK.js +0 -14
  109. package/dist/collections/client.d.ts +0 -39
  110. package/dist/collections/client.js +0 -137
  111. package/dist/collections.d.ts +0 -59
  112. package/dist/collections.js +0 -159
  113. package/dist/config-CDoyls2X.js +0 -30
  114. package/dist/config-CZLO0m9h.js +0 -7811
  115. package/dist/file-CHfsZpso.js +0 -23
  116. package/dist/glob-D0vD_wRY.js +0 -17
  117. package/dist/host-CAnbugpI.js +0 -370
  118. package/dist/hosted-vercel-blob-CWBILDVo.js +0 -257
  119. package/dist/lifecycle-BYoa9hVb.js +0 -176
  120. package/dist/provider-C3_elpEh.js +0 -599
  121. package/dist/publish.d.ts +0 -35
  122. package/dist/publish.js +0 -112
  123. package/dist/registry-CqyDTW9Y.js +0 -74
  124. package/dist/runtime-options-BsPSv5O7.js +0 -13
  125. package/dist/shared-jfogBrd5.js +0 -273
  126. package/dist/store-Bs1SLh55.js +0 -414
  127. package/dist/vite-tbfDxtlu.js +0 -2191
  128. package/dist/workspace-66SKyiec.d.ts +0 -6
  129. package/dist/workspace-C4k92Ow8.js +0 -1460
@@ -1,9 +1,25 @@
1
- import { a as matchesAny, c as normalizeWorkspacePath, d as sha256, o as normalizeSafeWorkspacePath, p as workspaceError, r as contentToBytes, s as normalizeSafeWorkspacePattern } from "./path-CNI6wKIU.js";
2
- import { c as getWorkspaceHostedStoreLoader, d as setWorkspaceRuntimeConfig, i as resolveGitHubWorkspaceStore, l as setWorkspaceHostedStoreLoader, r as resolveCloudflareArtifactsStore } from "./provider-C3_elpEh.js";
3
- import { i as diffSnapshots, r as createSnapshotFromEntries, t as createGitHubWorkspaceStore } from "./store-Bs1SLh55.js";
4
- import { g as getActiveCloudflareBinding } from "./shared-jfogBrd5.js";
1
+ import { a as workspaceConflict, n as assertWorkspaceDigest, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, f as sha256, l as normalizeWorkspacePath, r as contentToBytes } from "./path-CNAwN7pw.js";
3
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
4
+ import { t as copyJsonFileMetadata } from "./file-metadata-CxDy-E2H.js";
5
+ import { n as createSnapshotFromEntries, r as diffSnapshots } from "./utils-Blrh4N2n.js";
6
+ import { t as createWorkspaceGlobMatcher } from "./glob--kNYDbfU.js";
7
+ import { b as getActiveCloudflareBinding } from "./shared-DalXdP0i.js";
8
+ import { a as resolveGitHubWorkspaceStore, f as setWorkspaceRuntimeConfig, i as resolveCloudflareArtifactsStore, l as getWorkspaceHostedStoreLoader, u as setWorkspaceHostedStoreLoader } from "./provider-kXjfli9u.js";
9
+ import { t as createGitHubWorkspaceStore } from "./store-CXgmu-uw.js";
5
10
  import { resolve } from "node:path";
11
+ import { boolean, check, object, optional, parse as parse$1, pipe, record, string, unknown } from "valibot";
12
+ //#region ../internal/src/object.ts
13
+ function isPlainObject(value) {
14
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
15
+ return typeof value === "object";
16
+ }
17
+ //#endregion
6
18
  //#region src/storage/memory-fs.ts
19
+ function copyBinaryData(data) {
20
+ if (ArrayBuffer.isView(data)) return Uint8Array.from(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
21
+ if (Object.prototype.toString.call(data) === "[object ArrayBuffer]") return Uint8Array.from(new Uint8Array(data));
22
+ }
7
23
  var MemoryStats = class {
8
24
  entry;
9
25
  constructor(entry) {
@@ -34,7 +50,7 @@ var MemoryStats = class {
34
50
  var MemoryFS = class {
35
51
  #decoder = new TextDecoder();
36
52
  #encoder = new TextEncoder();
37
- entries = new Map([["/", {
53
+ entries = /* @__PURE__ */ new Map([["/", {
38
54
  kind: "dir",
39
55
  children: /* @__PURE__ */ new Set(),
40
56
  mtimeMs: Date.now()
@@ -72,49 +88,61 @@ var MemoryFS = class {
72
88
  }
73
89
  async mkdir(path, options) {
74
90
  const target = this.normalize(path);
75
- if (target === "/") return;
76
- const recursive = typeof options === "object" && Boolean(options?.recursive);
91
+ const recursive = isPlainObject(options) && options.recursive === true;
92
+ if (target === "/") {
93
+ if (recursive) return;
94
+ throw memoryFsError("EEXIST", path);
95
+ }
77
96
  const parent = this.parent(target);
78
97
  if (!this.entries.has(parent)) {
79
- if (!recursive) throw new Error(`ENOENT: ${parent}`);
98
+ if (!recursive) throw memoryFsError("ENOENT", parent);
80
99
  await this.mkdir(parent, { recursive: true });
81
100
  }
82
- if (this.entries.has(target)) return;
101
+ const existing = this.entries.get(target);
102
+ if (existing) {
103
+ if (existing.kind === "dir" && recursive) return;
104
+ throw memoryFsError("EEXIST", path);
105
+ }
106
+ const parentEntry = this.#requireDir(parent);
83
107
  this.entries.set(target, {
84
108
  kind: "dir",
85
109
  children: /* @__PURE__ */ new Set(),
86
110
  mtimeMs: Date.now()
87
111
  });
88
- this.#requireDir(parent).children.add(this.basename(target));
112
+ parentEntry.children.add(this.basename(target));
89
113
  }
90
114
  async writeFile(path, data) {
91
115
  const target = this.normalize(path);
92
- await this.mkdir(this.parent(target), { recursive: true });
93
- const bytes = typeof data === "string" ? this.#encoder.encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
116
+ if (this.entries.get(target)?.kind === "dir") throw memoryFsError("EISDIR", path);
117
+ const parentPath = this.parent(target);
118
+ if (!this.entries.has(parentPath)) await this.mkdir(parentPath, { recursive: true });
119
+ const parent = this.#requireDir(parentPath);
120
+ const bytes = copyBinaryData(data) ?? this.#encoder.encode(String(data));
94
121
  this.entries.set(target, {
95
122
  kind: "file",
96
123
  data: bytes,
97
124
  mtimeMs: Date.now()
98
125
  });
99
- this.#requireDir(this.parent(target)).children.add(this.basename(target));
126
+ parent.children.add(this.basename(target));
100
127
  }
101
128
  async readFile(path, options) {
102
129
  const entry = this.#requireEntry(path);
103
- if (entry.kind !== "file") throw new Error(`EISDIR: ${path}`);
104
- return (typeof options === "string" ? options : options?.encoding) ? this.#decoder.decode(entry.data) : entry.data;
130
+ if (entry.kind !== "file") throw memoryFsError("EISDIR", path);
131
+ return (isPlainObject(options) ? options.encoding : options) ? this.#decoder.decode(entry.data) : Uint8Array.from(entry.data);
105
132
  }
106
133
  async readdir(path) {
107
134
  return [...this.#requireDir(path).children].sort();
108
135
  }
109
136
  async unlink(path) {
110
137
  const target = this.normalize(path);
111
- if (this.#requireEntry(target).kind !== "file") throw new Error(`EISDIR: ${path}`);
138
+ if (this.#requireEntry(target).kind !== "file") throw memoryFsError("EISDIR", path);
112
139
  this.entries.delete(target);
113
140
  this.#requireDir(this.parent(target)).children.delete(this.basename(target));
114
141
  }
115
142
  async rmdir(path) {
116
143
  const target = this.normalize(path);
117
- if (this.#requireDir(target).children.size) throw new Error(`ENOTEMPTY: ${path}`);
144
+ if (target === "/") throw memoryFsError("EBUSY", path);
145
+ if (this.#requireDir(target).children.size) throw memoryFsError("ENOTEMPTY", path);
118
146
  this.entries.delete(target);
119
147
  this.#requireDir(this.parent(target)).children.delete(this.basename(target));
120
148
  }
@@ -150,18 +178,36 @@ var MemoryFS = class {
150
178
  }
151
179
  #requireDir(path) {
152
180
  const entry = this.#requireEntry(path);
153
- if (entry.kind !== "dir") throw new Error(`ENOTDIR: ${path}`);
181
+ if (entry.kind !== "dir") throw memoryFsError("ENOTDIR", path);
154
182
  return entry;
155
183
  }
156
184
  };
157
185
  function memoryFsError(code, path) {
158
- return Object.assign(/* @__PURE__ */ new Error(`${code}: ${path}`), { code });
186
+ return Object.assign(workspaceErrorDiagnostics.WORKSPACE_R0065({ message: `${code}: ${path}` }), { code });
159
187
  }
160
188
  //#endregion
161
189
  //#region src/providers/cloudflare/artifacts-store.ts
162
190
  const dir = "/workspace";
163
191
  const fileMetadataPath = ".vitehub/files.json";
192
+ const fileMetadataJournalPath = ".vitehub/files.pending.json";
164
193
  const tokenRefreshWindow = 6e4;
194
+ const fileMetadataSchema = object({
195
+ mediaType: optional(string()),
196
+ metadata: optional(pipe(record(string(), unknown()), check((value) => value.source === void 0 || typeof value.source === "string", "metadata.source must be a string when provided")))
197
+ });
198
+ const fileMetadataFilesSchema = record(string(), fileMetadataSchema);
199
+ const fileMetadataJournalSchema = object({
200
+ path: string(),
201
+ existed: boolean(),
202
+ digest: string(),
203
+ metadata: fileMetadataSchema
204
+ });
205
+ function parseJson(content) {
206
+ return JSON.parse(new TextDecoder().decode(content));
207
+ }
208
+ function sameSnapshotEntry(left, right) {
209
+ return left?.digest === right?.digest && left?.type === right?.type && left?.size === right?.size && JSON.stringify(left?.metadata) === JSON.stringify(right?.metadata);
210
+ }
165
211
  function tokenSecret(token) {
166
212
  return token.split("?expires=")[0] || token;
167
213
  }
@@ -221,6 +267,9 @@ var CloudflareArtifactsWorkspaceStore = class {
221
267
  async readFile(path) {
222
268
  const normalized = normalizeSafeWorkspacePath(path);
223
269
  await this.#ensure();
270
+ return await this.#mutate(() => this.#readFile(normalized));
271
+ }
272
+ async #readFile(normalized) {
224
273
  const filepath = this.#absolute(normalized);
225
274
  const content = await this.#fs.promises.readFile(filepath).catch(() => void 0);
226
275
  if (!content) return void 0;
@@ -229,25 +278,26 @@ var CloudflareArtifactsWorkspaceStore = class {
229
278
  path: normalized,
230
279
  content,
231
280
  mediaType: fileMetadata?.mediaType,
232
- metadata: fileMetadata?.metadata
281
+ metadata: structuredClone(fileMetadata?.metadata)
233
282
  };
234
283
  }
235
284
  async writeFile(path, file) {
285
+ const normalized = normalizeSafeWorkspacePath(path);
286
+ await this.#ensure();
287
+ await this.#mutate(() => this.#writeFile(normalized, file));
288
+ }
289
+ async writeFileConditional(path, file, ifDigest) {
236
290
  const normalized = normalizeSafeWorkspacePath(path);
237
291
  await this.#ensure();
238
292
  await this.#mutate(async () => {
239
- await this.#fs.promises.writeFile(this.#absolute(normalized), contentToBytes(file.content));
240
- if (file.mediaType !== void 0 || file.metadata !== void 0) this.#files.set(normalized, {
241
- mediaType: file.mediaType,
242
- metadata: file.metadata
243
- });
244
- else this.#files.delete(normalized);
245
- await this.#writeFileMetadata();
293
+ const current = await this.#stat(normalized).catch(() => void 0);
294
+ assertWorkspaceDigest(normalized, ifDigest, current?.type === "file" ? current.digest : void 0);
295
+ await this.#writeFile(normalized, file);
246
296
  });
247
297
  }
248
298
  async list(prefix = "", options = {}) {
249
299
  await this.#ensure();
250
- return this.#listEntries(prefix, options);
300
+ return await this.#mutate(() => this.#listEntries(prefix, options));
251
301
  }
252
302
  async #listEntries(prefix = "", options = {}) {
253
303
  const normalizedPrefix = normalizeSafeWorkspacePath(prefix, { allowEmpty: true });
@@ -255,7 +305,9 @@ var CloudflareArtifactsWorkspaceStore = class {
255
305
  for (const [absolute, entry] of this.#fs.entries) {
256
306
  if (absolute === dir || !absolute.startsWith(`${dir}/`)) continue;
257
307
  const path = normalizeWorkspacePath(absolute.slice(`${dir}/`.length));
258
- if (!path || path === ".git" || path.startsWith(".git/") || path === ".vitehub" || path.startsWith(".vitehub/")) continue;
308
+ const root = path.split("/")[0]?.toLowerCase();
309
+ if (!path || root === ".git" || root === ".vitehub") continue;
310
+ if (isExcludedWorkspacePath(path, options.exclude)) continue;
259
311
  if (normalizedPrefix) {
260
312
  if (path === normalizedPrefix) continue;
261
313
  if (!path.startsWith(`${normalizedPrefix}/`)) continue;
@@ -266,7 +318,7 @@ var CloudflareArtifactsWorkspaceStore = class {
266
318
  entries.push({
267
319
  digest: await sha256(entry.data),
268
320
  mediaType: fileMetadata?.mediaType,
269
- metadata: fileMetadata?.metadata,
321
+ metadata: structuredClone(fileMetadata?.metadata),
270
322
  mtime: entry.mtimeMs,
271
323
  path,
272
324
  size: entry.data.byteLength,
@@ -280,13 +332,17 @@ var CloudflareArtifactsWorkspaceStore = class {
280
332
  }
281
333
  return entries.sort((a, b) => a.path.localeCompare(b.path));
282
334
  }
283
- async glob(pattern, _options = {}) {
335
+ async glob(pattern, options = {}) {
284
336
  const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
285
- return (await this.list("", { recursive: true })).filter((entry) => entry.type === "file" && matchesAny(entry.path, patterns));
337
+ const { cwd, matches } = createWorkspaceGlobMatcher(patterns, options);
338
+ return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
286
339
  }
287
340
  async stat(path) {
288
341
  const normalized = normalizeSafeWorkspacePath(path);
289
342
  await this.#ensure();
343
+ return await this.#mutate(() => this.#stat(normalized));
344
+ }
345
+ async #stat(normalized) {
290
346
  const stat = await this.#fs.promises.stat(this.#absolute(normalized)).catch(() => void 0);
291
347
  if (!stat) return void 0;
292
348
  const bytes = stat.isFile() ? await this.#fs.promises.readFile(this.#absolute(normalized)) : void 0;
@@ -294,7 +350,7 @@ var CloudflareArtifactsWorkspaceStore = class {
294
350
  return {
295
351
  digest: bytes ? await sha256(bytes) : void 0,
296
352
  mediaType: fileMetadata?.mediaType,
297
- metadata: fileMetadata?.metadata,
353
+ metadata: structuredClone(fileMetadata?.metadata),
298
354
  mtime: stat.mtimeMs,
299
355
  path: normalized,
300
356
  size: stat.isFile() ? stat.size : void 0,
@@ -306,10 +362,21 @@ var CloudflareArtifactsWorkspaceStore = class {
306
362
  await this.#ensure();
307
363
  await this.#mutate(() => this.#fs.promises.mkdir(this.#absolute(normalized), { recursive: options.recursive ?? true }));
308
364
  }
365
+ async removeEmptyDirectory(path) {
366
+ const normalized = normalizeSafeWorkspacePath(path, { allowEmpty: true });
367
+ if (!normalized) return;
368
+ await this.#ensure();
369
+ await this.#mutate(async () => {
370
+ await this.#fs.promises.rmdir(this.#absolute(normalized)).catch((error) => {
371
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
372
+ });
373
+ });
374
+ }
309
375
  async rm(path, options = {}) {
310
376
  const normalized = normalizeSafeWorkspacePath(path);
311
377
  await this.#ensure();
312
378
  await this.#mutate(async () => {
379
+ if (options.ifDigest !== void 0) assertWorkspaceDigest(path, options.ifDigest, (await this.#stat(normalized))?.digest);
313
380
  const absolute = this.#absolute(normalized);
314
381
  const stat = await this.#fs.promises.stat(absolute).catch(() => void 0);
315
382
  if (!stat) {
@@ -328,6 +395,55 @@ var CloudflareArtifactsWorkspaceStore = class {
328
395
  await this.#ensure();
329
396
  return this.#mutate(() => this.#createSnapshot(options));
330
397
  }
398
+ async rebase(options = {}) {
399
+ await this.#ensure();
400
+ await this.#mutate(async () => {
401
+ const baseline = this.#baseline;
402
+ const current = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
403
+ const changes = diffSnapshots(baseline, current).entries.filter((change) => change.before?.type === "file" || change.after?.type === "file");
404
+ const local = /* @__PURE__ */ new Map();
405
+ for (const change of changes) local.set(change.path, change.after ? await this.#readFile(change.path) : void 0);
406
+ const previous = {
407
+ baseline: this.#baseline,
408
+ branch: this.#branch,
409
+ files: this.#files,
410
+ fs: this.#fs,
411
+ head: this.#head,
412
+ pendingCommit: this.#pendingCommit,
413
+ remote: this.#remote
414
+ };
415
+ const restore = () => {
416
+ this.#baseline = previous.baseline;
417
+ this.#branch = previous.branch;
418
+ this.#files = previous.files;
419
+ this.#fs = previous.fs;
420
+ this.#head = previous.head;
421
+ this.#pendingCommit = previous.pendingCommit;
422
+ this.#remote = previous.remote;
423
+ };
424
+ try {
425
+ this.#files = /* @__PURE__ */ new Map();
426
+ this.#pendingCommit = void 0;
427
+ await this.#load();
428
+ const remoteChanges = new Map(diffSnapshots(baseline, this.#baseline).entries.map((change) => [change.path, change]));
429
+ const takeRemote = new Set(options.takeRemote || []);
430
+ 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.`);
431
+ for (const change of changes) {
432
+ if (remoteChanges.has(change.path) && takeRemote.has(change.path)) continue;
433
+ const file = local.get(change.path);
434
+ if (file) await this.#writeFile(change.path, file);
435
+ else {
436
+ this.#fs.deleteTree(this.#absolute(change.path));
437
+ this.#files.delete(change.path);
438
+ await this.#writeFileMetadata();
439
+ }
440
+ }
441
+ } catch (error) {
442
+ restore();
443
+ throw error;
444
+ }
445
+ });
446
+ }
331
447
  async #createSnapshot(options) {
332
448
  const git = await import("isomorphic-git");
333
449
  const http = await import("isomorphic-git/http/web");
@@ -381,7 +497,7 @@ var CloudflareArtifactsWorkspaceStore = class {
381
497
  url: this.#remote
382
498
  });
383
499
  } catch (error) {
384
- if (isNonFastForward(error)) throw workspaceError(`[vitehub] Workspace "${this.workspaceName}" changed remotely while snapshotting branch "${this.#branch}". Reload the Workspace before retrying.`, { cause: error });
500
+ if (isNonFastForward(error)) throw workspaceConflict(`[vitehub] Workspace "${this.workspaceName}" changed remotely while snapshotting branch "${this.#branch}". Reload the Workspace before retrying.`, { cause: error });
385
501
  throw error;
386
502
  }
387
503
  this.#head = id;
@@ -396,20 +512,52 @@ var CloudflareArtifactsWorkspaceStore = class {
396
512
  }
397
513
  async diff(options = {}) {
398
514
  await this.#ensure();
399
- return diffSnapshots(options.from || this.#baseline, await createSnapshotFromEntries(await this.#listEntries("", { recursive: true })));
515
+ return await this.#mutate(async () => {
516
+ const from = options.from || this.#baseline;
517
+ const to = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
518
+ return diffSnapshots(from, to);
519
+ });
400
520
  }
401
521
  async getMeta(key) {
402
522
  const path = this.#metaAbsolute(key);
403
523
  await this.#ensure();
404
- const content = await this.#fs.promises.readFile(path).catch(() => void 0);
405
- if (!content) return void 0;
406
- return JSON.parse(new TextDecoder().decode(contentToBytes(content)));
524
+ return await this.#mutate(async () => {
525
+ const content = await this.#fs.promises.readFile(path).catch(() => void 0);
526
+ if (!content) return void 0;
527
+ return JSON.parse(new TextDecoder().decode(contentToBytes(content)));
528
+ });
407
529
  }
408
530
  async setMeta(key, value) {
409
531
  const path = this.#metaAbsolute(key);
410
532
  await this.#ensure();
411
533
  await this.#mutate(() => this.#fs.promises.writeFile(path, contentToBytes(JSON.stringify(value))));
412
534
  }
535
+ async #writeFile(path, file) {
536
+ file = {
537
+ ...file,
538
+ metadata: copyJsonFileMetadata(path, file.metadata)
539
+ };
540
+ const existed = await this.#fs.promises.stat(this.#absolute(path)).then((stat) => stat.isFile()).catch(() => false);
541
+ const content = contentToBytes(file.content);
542
+ const digest = await sha256(content);
543
+ await this.#fs.promises.writeFile(this.#internalAbsolute(fileMetadataJournalPath), JSON.stringify({
544
+ path,
545
+ existed,
546
+ digest,
547
+ metadata: {
548
+ mediaType: file.mediaType,
549
+ metadata: file.metadata
550
+ }
551
+ }));
552
+ await this.#fs.promises.writeFile(this.#absolute(path), content);
553
+ if (file.mediaType !== void 0 || file.metadata !== void 0) this.#files.set(path, {
554
+ mediaType: file.mediaType,
555
+ metadata: file.metadata
556
+ });
557
+ else this.#files.delete(path);
558
+ await this.#writeFileMetadata();
559
+ this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
560
+ }
413
561
  #absolute(path) {
414
562
  return `${dir}/${path}`;
415
563
  }
@@ -422,9 +570,34 @@ var CloudflareArtifactsWorkspaceStore = class {
422
570
  }
423
571
  async #loadFileMetadata() {
424
572
  const content = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataPath)).catch(() => void 0);
425
- if (!content) return;
426
- const files = JSON.parse(new TextDecoder().decode(content));
427
- this.#files = new Map(Object.entries(files));
573
+ if (content) {
574
+ const files = parse$1(fileMetadataFilesSchema, parseJson(contentToBytes(content)));
575
+ this.#files = new Map(Object.entries(files).map(([path, file]) => [path, {
576
+ ...file,
577
+ metadata: copyJsonFileMetadata(path, file.metadata)
578
+ }]));
579
+ }
580
+ const pending = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataJournalPath)).catch(() => void 0);
581
+ if (!pending) return;
582
+ let journal;
583
+ try {
584
+ journal = parse$1(fileMetadataJournalSchema, parseJson(contentToBytes(pending)));
585
+ journal.metadata.metadata = copyJsonFileMetadata(journal.path, journal.metadata.metadata);
586
+ } catch {
587
+ this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
588
+ return;
589
+ }
590
+ try {
591
+ if (journal.path && await this.#fs.promises.stat(this.#absolute(journal.path)).then((stat) => stat.isFile()).catch(() => false)) {
592
+ const content = await this.#fs.promises.readFile(this.#absolute(journal.path));
593
+ if (await sha256(contentToBytes(content)) !== journal.digest) return;
594
+ if (journal.metadata && (journal.metadata.mediaType !== void 0 || journal.metadata.metadata !== void 0)) this.#files.set(journal.path, journal.metadata);
595
+ else this.#files.delete(journal.path);
596
+ await this.#writeFileMetadata();
597
+ }
598
+ } finally {
599
+ this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
600
+ }
428
601
  }
429
602
  async #writeFileMetadata() {
430
603
  const path = this.#internalAbsolute(fileMetadataPath);
@@ -566,7 +739,7 @@ function installHostedWorkspaceRuntime() {
566
739
  }
567
740
  function configureHostedWorkspaceRuntime(options = {}) {
568
741
  const root = resolve(process.cwd(), options.root || ".vitehub/workspaces");
569
- 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);
742
+ 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);
570
743
  if (!store) throw workspaceError("[vitehub] Vercel Blob hosted workspace runtime must use @vite-hub/workspace/internal/runtime/hosted-vercel-blob.");
571
744
  const config = {
572
745
  assets: options.assets,
@@ -578,4 +751,4 @@ function configureHostedWorkspaceRuntime(options = {}) {
578
751
  return config;
579
752
  }
580
753
  //#endregion
581
- export { installHostedWorkspaceRuntime as n, createCloudflareArtifactsWorkspaceStore as r, configureHostedWorkspaceRuntime as t };
754
+ export { isPlainObject as i, installHostedWorkspaceRuntime as n, createCloudflareArtifactsWorkspaceStore as r, configureHostedWorkspaceRuntime as t };