@vite-hub/workspace 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +339 -115
  2. package/dist/abort-BCwpdrN0.js +32 -0
  3. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  4. package/dist/blob-database.d.ts +474 -0
  5. package/dist/blob-database.js +608 -0
  6. package/dist/checkout.d.ts +128 -0
  7. package/dist/checkout.js +849 -0
  8. package/dist/cloudflare.d.ts +6 -7
  9. package/dist/cloudflare.js +1 -1
  10. package/dist/config-B-863EgC.js +15 -0
  11. package/dist/config-BAgL2dtB.js +1076 -0
  12. package/dist/{config-DE9xlaIw.d.ts → config-BQKcPawI.d.ts} +1 -2
  13. package/dist/discard-CNNtCozM.js +8 -0
  14. package/dist/durability.d.ts +22 -0
  15. package/dist/durability.js +70 -0
  16. package/dist/error-diagnostics-CtKjGtGb.js +188 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/file-2pFYNtsU.js +22 -0
  19. package/dist/{files-Q6xZjDHA.js → files-BOo4SbwE.js} +3 -3
  20. package/dist/files.d.ts +38 -0
  21. package/dist/files.js +6 -0
  22. package/dist/{github-DHnjxQIX.js → github-CrYp4v8k.js} +44 -24
  23. package/dist/glob-B8YGvTrZ.js +21 -0
  24. package/dist/glob-Cjxms1t7.js +30 -0
  25. package/dist/{host-DJH8cuoU.js → host-BFBpXn0N.js} +144 -77
  26. package/dist/{hosted-RPeJOCFz.js → hosted-KcUR_jPv.js} +303 -97
  27. package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
  28. package/dist/hosted-vercel-blob.d.ts +6 -7
  29. package/dist/hosted-vercel-blob.js +1 -1
  30. package/dist/hosted.d.ts +10 -9
  31. package/dist/hosted.js +2 -2
  32. package/dist/index.d.ts +26 -47
  33. package/dist/index.js +30 -100
  34. package/dist/internal/path.d.ts +2 -0
  35. package/dist/internal/path.js +2 -0
  36. package/dist/lifecycle-B-enk_4A.js +596 -0
  37. package/dist/lineage.d.ts +26 -0
  38. package/dist/lineage.js +76 -0
  39. package/dist/loader.d.ts +5 -6
  40. package/dist/loader.js +3 -2
  41. package/dist/mcp-resources-DF0F5rcL.js +39 -0
  42. package/dist/memory-BOexthyW.js +247 -0
  43. package/dist/metadata-target-CWz6KHKq.js +1589 -0
  44. package/dist/object-Da1zyPCR.js +11 -0
  45. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  46. package/dist/operations-C6FpR8Rr.js +389 -0
  47. package/dist/operations-CE2drFih.js +1234 -0
  48. package/dist/operations.d.ts +90 -0
  49. package/dist/operations.js +3 -0
  50. package/dist/path--wrT_Azm.js +113 -0
  51. package/dist/path-AxMho1wo.d.ts +7 -0
  52. package/dist/path-DrSIenjj.js +59 -0
  53. package/dist/path-zHxQUbqa.d.ts +9 -0
  54. package/dist/plugins-C8C0auoW.d.ts +10 -0
  55. package/dist/provider-9s4Ufkm5.js +1479 -0
  56. package/dist/providers/github/store.d.ts +3 -5
  57. package/dist/providers/github/store.js +1 -1
  58. package/dist/registry-B3BBm4Ts.d.ts +19 -0
  59. package/dist/{registry-D3yzt8HQ.js → registry-CNphafBx.js} +60 -23
  60. package/dist/registry-CYNN623b.d.ts +9 -0
  61. package/dist/request-scope-Dw5n8bMC.js +83 -0
  62. package/dist/results-DgkZUmTL.js +8 -0
  63. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-rQ84J-ij.js} +3 -4
  64. package/dist/runtime/assets.d.ts +3 -5
  65. package/dist/runtime/assets.js +7 -6
  66. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  67. package/dist/runtime/empty-registry.d.ts +2 -2
  68. package/dist/runtime/registry.d.ts +2 -0
  69. package/dist/runtime/registry.js +23 -0
  70. package/dist/runtime/request.d.ts +4 -0
  71. package/dist/runtime/request.js +8 -0
  72. package/dist/runtime/state.d.ts +5 -4
  73. package/dist/runtime/state.js +8 -18
  74. package/dist/runtime/workspace.d.ts +1 -1
  75. package/dist/runtime/workspace.js +1 -1
  76. package/dist/runtime.d.ts +52 -17
  77. package/dist/runtime.js +324 -67
  78. package/dist/{search-BpiCF2Tw.js → search-C_RfoM2j.js} +10 -9
  79. package/dist/server-8tGltlGz.js +303 -0
  80. package/dist/server.d.ts +36 -39
  81. package/dist/server.js +2 -328
  82. package/dist/shared-B3_EUk89.js +848 -0
  83. package/dist/source-metadata.d.ts +10 -7
  84. package/dist/source-metadata.js +12 -12
  85. package/dist/state-BISnUf1s.d.ts +35 -0
  86. package/dist/{ai-BqCC8BpY.js → state-DbrW-njQ.js} +237 -114
  87. package/dist/store-ybhyD38Z.js +1873 -0
  88. package/dist/{sync-DnTQwt8r.js → sync-CCD_VYC8.js} +61 -41
  89. package/dist/target-jWhTdIuF.js +89 -0
  90. package/dist/test.d.ts +1 -1
  91. package/dist/test.js +1 -1
  92. package/dist/{types-CYuwjJ4V.d.ts → types-BbtwmBZ5.d.ts} +321 -35
  93. package/dist/use-C6lV3-wC.d.ts +321 -0
  94. package/dist/{use-BTNDR5Rd.js → use-CSpT5W87.js} +141 -107
  95. package/dist/utils-CgMZCHsX.js +616 -0
  96. package/dist/vite.d.ts +585 -2
  97. package/dist/vite.js +21369 -2
  98. package/dist/workspace-CYB2xZ1T.d.ts +7 -0
  99. package/dist/{workspace-Dq08Yn72.js → workspace-sPWn2Jxj.js} +441 -225
  100. package/package.json +97 -72
  101. package/dist/ai-CjxvGqM0.d.ts +0 -162
  102. package/dist/ai.d.ts +0 -3
  103. package/dist/ai.js +0 -2
  104. package/dist/collections/client.d.ts +0 -39
  105. package/dist/collections/client.js +0 -137
  106. package/dist/collections.d.ts +0 -59
  107. package/dist/collections.js +0 -159
  108. package/dist/config-Bc3c4Su1.js +0 -7904
  109. package/dist/config-CHLLWklZ.js +0 -36
  110. package/dist/file-Bc1X7pco.js +0 -23
  111. package/dist/glob-CEZKeZFC.js +0 -18
  112. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  113. package/dist/lifecycle-LrL3sA4n.js +0 -316
  114. package/dist/metadata-target-B0tOmVW7.js +0 -717
  115. package/dist/mountx.d.ts +0 -10
  116. package/dist/mountx.js +0 -143
  117. package/dist/nitro.d.ts +0 -2
  118. package/dist/nitro.js +0 -2
  119. package/dist/nuxt.d.ts +0 -26
  120. package/dist/nuxt.js +0 -42
  121. package/dist/path-Cp59koVz.js +0 -139
  122. package/dist/provider-B1yLjCJJ.js +0 -746
  123. package/dist/publish.d.ts +0 -35
  124. package/dist/publish.js +0 -112
  125. package/dist/registry-Uj6IVxes.d.ts +0 -11
  126. package/dist/request-execution-B-dSFlGB.js +0 -84
  127. package/dist/runtime-options-BsPSv5O7.js +0 -13
  128. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  129. package/dist/shared-DTR1Hhma.js +0 -331
  130. package/dist/state-tYcRWEh2.d.ts +0 -26
  131. package/dist/store-Dt_Jyys3.js +0 -608
  132. package/dist/target-D4Bqb1eH.js +0 -11
  133. package/dist/token-CVzURBxC.js +0 -61
  134. package/dist/use-BiHzt0xA.d.ts +0 -103
  135. package/dist/vite-BptCrpv2.js +0 -4526
  136. package/dist/vite-CtA9guIM.d.ts +0 -66
  137. package/dist/workspace-Xddf4G1B.d.ts +0 -6
@@ -0,0 +1,608 @@
1
+ import { n as forkMemoryWorkspaceStore, r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-BOexthyW.js";
2
+ import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
+ import { o as copyJsonFileMetadata, r as workspaceStoreTarget, s as copyJsonWorkspaceMetadata } from "./target-jWhTdIuF.js";
4
+ import { a as isExcludedWorkspacePath, f as sha256, i as decodeFile, o as isWorkspaceBytes, r as contentToBytes } from "./path--wrT_Azm.js";
5
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
6
+ import { d as normalizeHistoryRef, l as historyConflict, n as createSnapshotFromEntries, p as validateHistoryMessage, r as diffSnapshots, u as normalizeHistoryPath } from "./utils-CgMZCHsX.js";
7
+ import { and, desc, eq, inArray, isNotNull, lt, sql } from "drizzle-orm";
8
+ import { ViteHubError } from "@vite-hub/runtime";
9
+ import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
10
+ /** Include these tables in a Database Definition and apply its migrations. */
11
+ const workspaceHistorySchema = {
12
+ workspaceHistoryWorkspaces: sqliteTable("workspace_history_workspaces", {
13
+ workspace: text("workspace").primaryKey(),
14
+ deleted: integer("deleted", { mode: "boolean" }).notNull().default(false)
15
+ }),
16
+ workspaceHistoryRefs: sqliteTable("workspace_history_refs", {
17
+ workspace: text("workspace").notNull(),
18
+ ref: text("ref").notNull(),
19
+ head: text("head"),
20
+ sequence: integer("sequence").notNull().default(0)
21
+ }, (table) => [primaryKey({ columns: [table.workspace, table.ref] })]),
22
+ workspaceHistoryRevisions: sqliteTable("workspace_history_revisions", {
23
+ workspace: text("workspace").notNull(),
24
+ id: text("id").notNull(),
25
+ ref: text("ref").notNull(),
26
+ parentId: text("parent_id"),
27
+ sequence: integer("sequence").notNull(),
28
+ createdAt: text("created_at").notNull(),
29
+ message: text("message"),
30
+ metadata: text("metadata", { mode: "json" }).$type(),
31
+ files: integer("files").notNull(),
32
+ bytes: integer("bytes").notNull(),
33
+ entries: text("entries", { mode: "json" }).$type().notNull(),
34
+ committed: integer("committed", { mode: "boolean" }).notNull().default(false)
35
+ }, (table) => [primaryKey({ columns: [table.workspace, table.id] }), index("workspace_history_timeline").on(table.workspace, table.ref, table.committed, table.sequence)]),
36
+ workspaceHistoryObjects: sqliteTable("workspace_history_objects", {
37
+ workspace: text("workspace").notNull(),
38
+ digest: text("digest").notNull(),
39
+ size: integer("size").notNull()
40
+ }, (table) => [primaryKey({ columns: [table.workspace, table.digest] })]),
41
+ workspaceHistoryMetadata: sqliteTable("workspace_history_metadata", {
42
+ workspace: text("workspace").notNull(),
43
+ key: text("key").notNull(),
44
+ value: text("value", { mode: "json" }).$type().notNull()
45
+ }, (table) => [primaryKey({ columns: [table.workspace, table.key] })])
46
+ };
47
+ //#endregion
48
+ //#region src/storage/blob-database.ts
49
+ const { workspaceHistoryWorkspaces: workspaces, workspaceHistoryRefs: refs, workspaceHistoryRevisions: revisions, workspaceHistoryObjects: objects, workspaceHistoryMetadata: metadata } = workspaceHistorySchema;
50
+ function publicRevision(row) {
51
+ const revision = {
52
+ id: row.id,
53
+ ref: row.ref,
54
+ parentId: row.parentId,
55
+ createdAt: row.createdAt,
56
+ files: row.files,
57
+ bytes: row.bytes
58
+ };
59
+ if (row.message !== null) revision.message = row.message;
60
+ if (row.metadata !== null) revision.metadata = structuredClone(row.metadata);
61
+ return revision;
62
+ }
63
+ var ContentAddressedWorkspaceStore = class {
64
+ options;
65
+ #namespace;
66
+ #ready;
67
+ #draft;
68
+ #dirty = false;
69
+ #baseline;
70
+ #queue = Promise.resolve();
71
+ #database;
72
+ constructor(options) {
73
+ this.options = options;
74
+ if (typeof options.workspace !== "string" || !options.workspace) throw workspaceError("[vitehub] Blob + Database Store requires a workspace identity.");
75
+ if (options.prefix !== void 0 && !/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(options.prefix)) throw workspaceError("[vitehub] History Blob prefix must contain only letters, numbers, underscores, dashes, and single slashes.");
76
+ const root = `${vitehubOwnedPrefix}workspace-history`;
77
+ const prefix = options.prefix === void 0 ? root : `${root}/${options.prefix}`;
78
+ const legacyPrefix = options.prefix === void 0 ? "vitehub/workspace-history" : options.prefix;
79
+ this.#namespace = sha256(options.workspace).then((digest) => {
80
+ const current = `${prefix}/${digest}`;
81
+ const legacy = `${legacyPrefix}/${digest}`;
82
+ return legacy === current ? [current] : [current, legacy];
83
+ });
84
+ }
85
+ [workspaceStoreTarget]() {
86
+ return {
87
+ provider: "blob-database",
88
+ workspace: this.options.workspace,
89
+ database: this.#db
90
+ };
91
+ }
92
+ get #db() {
93
+ if (this.#database) return this.#database;
94
+ const { database } = this.options;
95
+ const resolved = typeof database === "function" ? database() : database;
96
+ if (typeof resolved?.batch !== "function") throw workspaceErrorDiagnostics.WORKSPACE_R0077({ message: `[vitehub] The \`database\` of the Blob + Database Store for workspace "${this.options.workspace}" is not a Drizzle database.` });
97
+ return this.#database = resolved;
98
+ }
99
+ history = {
100
+ head: async (options) => await this.#head(normalizeHistoryRef(options?.ref)),
101
+ list: async (options) => await this.#listHistory(options),
102
+ refs: async () => await this.#refs(),
103
+ open: async (id) => await this.#open(id),
104
+ usage: async () => {
105
+ const workspace = await this.#key();
106
+ const [result] = await this.#db.values(sql`
107
+ select coalesce(sum(size), 0) as bytes, count(*) as objects from (
108
+ select distinct json_extract(file.value, '$.digest') as digest,
109
+ json_extract(file.value, '$.size') as size
110
+ from ${revisions}, json_each(${revisions.entries}) as file
111
+ where ${revisions.workspace} = ${workspace} and ${revisions.committed} = 1
112
+ and ${this.#active(workspace)}
113
+ )
114
+ `);
115
+ return {
116
+ bytes: result?.[0] ?? 0,
117
+ objects: result?.[1] ?? 0
118
+ };
119
+ },
120
+ commit: async (options) => await this.#mutate(async () => {
121
+ const revision = await this.#commit(options);
122
+ if (revision.ref === "main") {
123
+ this.#draft = void 0;
124
+ this.#dirty = false;
125
+ this.#baseline = void 0;
126
+ }
127
+ return revision;
128
+ })
129
+ };
130
+ async #key() {
131
+ const candidates = await this.#namespace;
132
+ this.#ready ??= this.#db.batch([
133
+ this.#db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, candidates[0])),
134
+ this.#db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, candidates[1] ?? candidates[0])),
135
+ this.#db.insert(workspaces).select(sql`
136
+ select ${candidates[0]}, 0
137
+ where not exists (
138
+ select 1 from ${workspaces} where ${workspaces.workspace} = ${candidates[1] ?? candidates[0]}
139
+ )
140
+ `).onConflictDoNothing()
141
+ ]).then((results) => {
142
+ const [current, legacy] = results;
143
+ return current[0]?.workspace ?? legacy[0]?.workspace ?? candidates[0];
144
+ }).catch((error) => {
145
+ this.#ready = void 0;
146
+ throw error;
147
+ });
148
+ return await this.#ready;
149
+ }
150
+ #active(workspace) {
151
+ return sql`exists (select 1 from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0)`;
152
+ }
153
+ async #isDeleted() {
154
+ const workspace = await this.#key();
155
+ const [row] = await this.#db.select({ deleted: workspaces.deleted }).from(workspaces).where(eq(workspaces.workspace, workspace));
156
+ if (!row) throw workspaceError("[vitehub] Workspace history identity is missing.");
157
+ return row.deleted;
158
+ }
159
+ async #ref(workspace, ref) {
160
+ const [row] = await this.#db.select().from(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), this.#active(workspace)));
161
+ return row;
162
+ }
163
+ async #head(ref) {
164
+ const workspace = await this.#key();
165
+ const row = await this.#ref(workspace, ref);
166
+ return row?.head ? publicRevision(await this.#revision(row.head)) : null;
167
+ }
168
+ async #refs() {
169
+ const workspace = await this.#key();
170
+ const heads = await this.#db.select({
171
+ ref: refs.ref,
172
+ head: refs.head
173
+ }).from(refs).where(and(eq(refs.workspace, workspace), isNotNull(refs.head), this.#active(workspace)));
174
+ if (!heads.length) return [];
175
+ const rows = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.committed, true), inArray(revisions.id, heads.map((row) => row.head)), this.#active(workspace)));
176
+ const byId = new Map(rows.map((row) => [row.id, row]));
177
+ return heads.flatMap(({ ref, head }) => {
178
+ const row = byId.get(head);
179
+ return row ? [{
180
+ name: ref,
181
+ head: publicRevision(row)
182
+ }] : [];
183
+ }).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
184
+ }
185
+ #deleted() {
186
+ throw new ViteHubError("WORKSPACE_NOT_FOUND", "[vitehub] This Workspace has been deleted. Use a new workspace identity.", { details: { workspace: this.options.workspace } });
187
+ }
188
+ async #assertActive() {
189
+ if (await this.#isDeleted()) this.#deleted();
190
+ }
191
+ async #revision(id) {
192
+ const workspace = await this.#key();
193
+ const [row] = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), eq(revisions.committed, true), this.#active(workspace)));
194
+ if (!row) throw new ViteHubError("WORKSPACE_NOT_FOUND", `[vitehub] Workspace revision does not exist: ${id}.`);
195
+ return row;
196
+ }
197
+ async #listHistory(options = {}) {
198
+ const limit = options.limit ?? 20;
199
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: "[vitehub] History list limit must be an integer from 1 to 100." });
200
+ const ref = normalizeHistoryRef(options.ref);
201
+ const path = options.path === void 0 ? void 0 : normalizeHistoryPath(options.path);
202
+ const workspace = await this.#key();
203
+ const cursor = options.cursor ? await this.#revision(options.cursor) : void 0;
204
+ if (cursor && cursor.ref !== ref) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor belongs to ref "${cursor.ref}". Pass it with the ref that returned it.` });
205
+ const previousEntries = sql`
206
+ coalesce((
207
+ select previous.entries
208
+ from ${revisions} as previous
209
+ where previous.workspace = ${revisions.workspace}
210
+ and previous.id = ${revisions.parentId}
211
+ and previous.committed = 1
212
+ ), '{}')
213
+ `;
214
+ const pathFilter = path === void 0 ? void 0 : sql`(
215
+ exists (
216
+ select 1
217
+ from json_each(${revisions.entries}) as current_file
218
+ left join json_each(${previousEntries}) as previous_file
219
+ on previous_file.key = current_file.key
220
+ where (current_file.key = ${path} or substr(current_file.key, 1, length(${path}) + 1) = ${path} || '/')
221
+ and (
222
+ previous_file.key is null
223
+ or json_extract(current_file.value, '$.digest') is not json_extract(previous_file.value, '$.digest')
224
+ or json_extract(current_file.value, '$.size') is not json_extract(previous_file.value, '$.size')
225
+ or json_extract(current_file.value, '$.mediaType') is not json_extract(previous_file.value, '$.mediaType')
226
+ or json_extract(current_file.value, '$.metadata') is not json_extract(previous_file.value, '$.metadata')
227
+ )
228
+ )
229
+ or exists (
230
+ select 1
231
+ from json_each(${previousEntries}) as previous_file
232
+ left join json_each(${revisions.entries}) as current_file
233
+ on current_file.key = previous_file.key
234
+ where (previous_file.key = ${path} or substr(previous_file.key, 1, length(${path}) + 1) = ${path} || '/')
235
+ and current_file.key is null
236
+ )
237
+ )`;
238
+ const rows = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), eq(revisions.committed, true), cursor ? lt(revisions.sequence, cursor.sequence) : void 0, pathFilter, this.#active(workspace))).orderBy(desc(revisions.sequence)).limit(limit + 1);
239
+ const result = { revisions: rows.slice(0, limit).map(publicRevision) };
240
+ if (rows.length > limit) result.cursor = rows[limit - 1].id;
241
+ return result;
242
+ }
243
+ async #open(id) {
244
+ const row = await this.#revision(id);
245
+ const workspace = await this.#key();
246
+ const entries = /* @__PURE__ */ new Map();
247
+ for (const [path, file] of Object.entries(row.entries)) {
248
+ entries.set(path, {
249
+ path,
250
+ type: "file",
251
+ digest: file.digest,
252
+ size: file.size,
253
+ mediaType: file.mediaType,
254
+ metadata: structuredClone(file.metadata),
255
+ revision: id
256
+ });
257
+ const parts = path.split("/");
258
+ for (let index = 1; index < parts.length; index++) {
259
+ const directory = parts.slice(0, index).join("/");
260
+ entries.set(directory, {
261
+ path: directory,
262
+ type: "directory"
263
+ });
264
+ }
265
+ }
266
+ entries.set("", {
267
+ path: "",
268
+ type: "directory"
269
+ });
270
+ return Object.freeze({
271
+ revision: publicRevision(row),
272
+ list: async (path = "", options) => {
273
+ await this.#assertActive();
274
+ const normalized = normalizeSafeWorkspacePath(path, { allowEmpty: true }).split("/").filter(Boolean).join("/");
275
+ return [...entries.values()].filter((entry) => entry.path && entry.path !== normalized && (!normalized || entry.path.startsWith(`${normalized}/`)) && !isExcludedWorkspacePath(entry.path, options?.exclude) && (options?.recursive || !entry.path.slice(normalized ? normalized.length + 1 : 0).includes("/"))).sort((left, right) => left.path.localeCompare(right.path)).map((entry) => structuredClone(entry));
276
+ },
277
+ stat: async (path) => {
278
+ await this.#assertActive();
279
+ const normalized = path === "" ? "" : normalizeHistoryPath(path);
280
+ const entry = entries.get(normalized);
281
+ if (!entry) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
282
+ return structuredClone(entry);
283
+ },
284
+ readFile: async (path, options) => {
285
+ await this.#assertActive();
286
+ const normalized = normalizeHistoryPath(path);
287
+ const file = Object.hasOwn(row.entries, normalized) ? row.entries[normalized] : void 0;
288
+ if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
289
+ const [error, body] = await this.options.blob.get(`${workspace}/sha256/${file.digest}`);
290
+ if (error) throw error;
291
+ if (!body) throw workspaceError(`[vitehub] Retained history object is missing: ${file.digest}.`);
292
+ const bytes = new Uint8Array(await body.arrayBuffer());
293
+ if (bytes.byteLength !== file.size || await sha256(bytes) !== file.digest) throw workspaceError(`[vitehub] Retained history object failed its content hash check: ${file.digest}.`);
294
+ return decodeFile(bytes, options);
295
+ }
296
+ });
297
+ }
298
+ async #commit(options) {
299
+ validateHistoryMessage(options.message);
300
+ const ref = normalizeHistoryRef(options.ref);
301
+ if (options.files === void 0 === (options.changes === void 0)) throw workspaceError("[vitehub] History commit requires exactly one of files or changes.");
302
+ const expectedHeads = Object.entries(options.ifHeads ?? {}).map(([name, head]) => {
303
+ if (head !== null && (typeof head !== "string" || !head)) throw workspaceError("[vitehub] History ifHeads values must be revision ids or null.");
304
+ return [normalizeHistoryRef(name), head];
305
+ });
306
+ const workspace = await this.#key();
307
+ await this.#assertActive();
308
+ const current = await this.#ref(workspace, ref);
309
+ if ((current?.head ?? null) !== options.ifHead) throw this.#conflict(ref, options.ifHead, current?.head ?? null);
310
+ const entries = Object.create(null);
311
+ const removed = /* @__PURE__ */ new Set();
312
+ if (options.changes && current?.head) Object.assign(entries, (await this.#revision(current.head)).entries);
313
+ for (const path of options.changes?.delete ?? []) {
314
+ const normalized = normalizeHistoryPath(path);
315
+ if (!Object.hasOwn(entries, normalized)) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
316
+ delete entries[normalized];
317
+ removed.add(normalized);
318
+ }
319
+ const puts = /* @__PURE__ */ new Set();
320
+ const contents = /* @__PURE__ */ new Map();
321
+ for (const [path, file] of Object.entries(options.files ?? options.changes?.put ?? {}).sort(([left], [right]) => left.localeCompare(right))) {
322
+ const normalized = normalizeHistoryPath(path);
323
+ if (puts.has(normalized) || removed.has(normalized)) throw workspaceError(`[vitehub] Duplicate history file path: ${normalized}.`);
324
+ puts.add(normalized);
325
+ if (typeof file.content !== "string" && !isWorkspaceBytes(file.content)) throw workspaceError(`[vitehub] Invalid history file content: ${normalized}.`);
326
+ const bytes = new Uint8Array(contentToBytes(file.content));
327
+ const digest = await sha256(bytes);
328
+ const entry = {
329
+ digest,
330
+ size: bytes.byteLength,
331
+ mediaType: file.mediaType || "application/octet-stream"
332
+ };
333
+ if (file.metadata !== void 0) entry.metadata = copyJsonFileMetadata(normalized, file.metadata);
334
+ entries[normalized] = entry;
335
+ contents.set(digest, bytes);
336
+ }
337
+ for (const path of Object.keys(entries)) {
338
+ const parts = path.split("/");
339
+ for (let index = 1; index < parts.length; index++) if (Object.hasOwn(entries, parts.slice(0, index).join("/"))) throw workspaceError(`[vitehub] History path is both a file and a directory: ${path}.`);
340
+ }
341
+ const sorted = Object.create(null);
342
+ for (const path of Object.keys(entries).sort((left, right) => left.localeCompare(right))) sorted[path] = entries[path];
343
+ const manifest = {
344
+ ref,
345
+ parentId: options.ifHead,
346
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
347
+ message: options.message ?? null,
348
+ metadata: copyJsonWorkspaceMetadata("history revision", options.metadata) ?? null,
349
+ entries: sorted
350
+ };
351
+ const id = await sha256(manifest);
352
+ const registry = [...contents].map(([digest, bytes]) => ({
353
+ digest,
354
+ size: bytes.byteLength
355
+ }));
356
+ await this.#db.insert(objects).select(sql`
357
+ select ${workspaces.workspace}, json_extract(object.value, '$.digest'), json_extract(object.value, '$.size')
358
+ from ${workspaces}, json_each(${JSON.stringify(registry)}) as object
359
+ where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
360
+ `).onConflictDoNothing();
361
+ await this.#assertActive();
362
+ const upload = async ([digest, bytes]) => {
363
+ const key = `${workspace}/sha256/${digest}`;
364
+ const [headError, object] = await this.options.blob.head(key);
365
+ if (headError && headError.code !== "BLOB_NOT_FOUND") throw headError;
366
+ if (!object) {
367
+ const [uploadError] = await this.options.blob.put(key, bytes, {
368
+ addRandomSuffix: false,
369
+ contentType: "application/octet-stream"
370
+ });
371
+ if (uploadError) {
372
+ const [concurrentError, concurrentObject] = await this.options.blob.head(key);
373
+ if (concurrentError || !concurrentObject) throw uploadError;
374
+ }
375
+ }
376
+ if (await this.#isDeleted()) {
377
+ await this.#removeObject(key);
378
+ this.#deleted();
379
+ }
380
+ };
381
+ const uploads = [...contents];
382
+ for (let offset = 0; offset < uploads.length; offset += 8) {
383
+ const results = await Promise.allSettled(uploads.slice(offset, offset + 8).map(upload));
384
+ for (const result of results) if (result.status === "rejected") throw result.reason;
385
+ }
386
+ const row = {
387
+ ...manifest,
388
+ entries: { ...sorted },
389
+ workspace,
390
+ id,
391
+ sequence: (current?.sequence ?? 0) + 1,
392
+ files: Object.keys(sorted).length,
393
+ bytes: Object.values(sorted).reduce((total, entry) => total + entry.size, 0)
394
+ };
395
+ expectedHeads.map(([name, head]) => sql`(select expected.head from ${refs} as expected where expected.workspace = ${workspace} and expected.ref = ${name}) is ${head}`);
396
+ const [, , changed] = await this.#db.batch([
397
+ this.#db.insert(refs).select(sql`
398
+ select ${workspaces.workspace}, ${ref}, null, 0
399
+ from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
400
+ `).onConflictDoNothing(),
401
+ this.#db.insert(revisions).select(sql`
402
+ select ${row.workspace}, ${row.id}, ${row.ref}, ${row.parentId}, ${row.sequence}, ${row.createdAt},
403
+ ${row.message}, ${row.metadata === null ? null : JSON.stringify(row.metadata)},
404
+ ${row.files}, ${row.bytes}, ${JSON.stringify(row.entries)}, 0
405
+ from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
406
+ `).onConflictDoNothing(),
407
+ this.#db.update(refs).set({
408
+ head: id,
409
+ sequence: sql`${refs.sequence} + 1`
410
+ }).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), sql`${refs.head} is ${options.ifHead}`, ...Object.entries(options.ifHeads ?? {}).map(([expectedRef, expectedHead]) => expectedHead === null ? sql`(not exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef}) or exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is null))` : sql`exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is ${expectedHead})`), this.#active(workspace))).returning({ head: refs.head }),
411
+ this.#db.update(revisions).set({ committed: true }).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${ref} and ${refs.head} = ${id})`, this.#active(workspace)))
412
+ ]);
413
+ if (!changed.length) {
414
+ if (await this.#isDeleted()) this.#deleted();
415
+ for (const [name, expected] of expectedHeads) {
416
+ const actual = (await this.#ref(workspace, name))?.head ?? null;
417
+ if (actual !== expected) throw this.#conflict(name, expected, actual);
418
+ }
419
+ throw this.#conflict(ref, options.ifHead, (await this.#ref(workspace, ref))?.head ?? null);
420
+ }
421
+ return publicRevision({
422
+ ...row,
423
+ committed: true
424
+ });
425
+ }
426
+ #conflict(ref, expected, actual) {
427
+ return historyConflict(ref, expected, actual, { workspace: this.options.workspace });
428
+ }
429
+ async #removeObject(key) {
430
+ const [headError, object] = await this.options.blob.head(key);
431
+ if (headError?.code === "BLOB_NOT_FOUND") return;
432
+ if (headError) throw headError;
433
+ if (!object) return;
434
+ const [error] = await this.options.blob.delete(key);
435
+ if (error && error.code !== "BLOB_NOT_FOUND") throw error;
436
+ }
437
+ async delete() {
438
+ await this.#mutate(() => this.#delete());
439
+ }
440
+ async #delete() {
441
+ const workspace = await this.#key();
442
+ await this.#db.batch([this.#db.update(workspaces).set({ deleted: true }).where(eq(workspaces.workspace, workspace)), this.#db.delete(refs).where(eq(refs.workspace, workspace))]);
443
+ const catalog = await this.#db.select().from(objects).where(eq(objects.workspace, workspace));
444
+ for (const object of catalog) await this.#removeObject(`${workspace}/sha256/${object.digest}`);
445
+ let cursor;
446
+ const cursors = /* @__PURE__ */ new Set();
447
+ const remaining = [];
448
+ do {
449
+ const [error, page] = await this.options.blob.list({
450
+ prefix: `${workspace}/sha256/`,
451
+ cursor,
452
+ limit: 1e3
453
+ });
454
+ if (error) throw error;
455
+ remaining.push(...page.blobs.map((object) => object.pathname));
456
+ cursor = page.hasMore ? page.cursor : void 0;
457
+ if (page.hasMore && (!cursor || cursors.has(cursor))) throw workspaceError("[vitehub] History cleanup received an invalid Blob cursor.");
458
+ if (cursor) cursors.add(cursor);
459
+ } while (cursor);
460
+ for (let offset = 0; offset < remaining.length; offset += 1e3) {
461
+ const [error] = await this.options.blob.delete(remaining.slice(offset, offset + 1e3));
462
+ if (error) throw error;
463
+ }
464
+ await this.#db.batch([
465
+ this.#db.delete(revisions).where(eq(revisions.workspace, workspace)),
466
+ this.#db.delete(objects).where(eq(objects.workspace, workspace)),
467
+ this.#db.delete(metadata).where(eq(metadata.workspace, workspace))
468
+ ]);
469
+ this.#draft = void 0;
470
+ this.#dirty = false;
471
+ }
472
+ async #loadDraft() {
473
+ await this.#assertActive();
474
+ const head = await this.history.head();
475
+ if (this.#draft && !this.#dirty && (await this.#draft).head?.id !== head?.id) this.#draft = void 0;
476
+ this.#draft ??= (async () => {
477
+ const store = createMemoryWorkspaceStore();
478
+ if (head) {
479
+ const view = await this.history.open(head.id);
480
+ for (const entry of await view.list("", { recursive: true })) if (entry.type === "file") await store.writeFile(entry.path, {
481
+ path: entry.path,
482
+ content: await view.readFile(entry.path, { encoding: "binary" }),
483
+ mediaType: entry.mediaType,
484
+ metadata: entry.metadata
485
+ });
486
+ }
487
+ await store.snapshot();
488
+ return {
489
+ store,
490
+ head
491
+ };
492
+ })().catch((error) => {
493
+ this.#draft = void 0;
494
+ throw error;
495
+ });
496
+ return await this.#draft;
497
+ }
498
+ #mutate(operation) {
499
+ const pending = this.#queue.then(operation);
500
+ this.#queue = pending.then(() => {}, () => {});
501
+ return pending;
502
+ }
503
+ async #write(operation) {
504
+ await this.#mutate(async () => {
505
+ const draft = await this.#loadDraft();
506
+ const candidate = forkMemoryWorkspaceStore(draft.store);
507
+ const dirty = this.#dirty;
508
+ this.#dirty = true;
509
+ try {
510
+ await operation(candidate);
511
+ await this.#assertActive();
512
+ this.#draft = Promise.resolve({
513
+ store: candidate,
514
+ head: draft.head
515
+ });
516
+ } catch (error) {
517
+ this.#dirty = dirty;
518
+ throw error;
519
+ }
520
+ });
521
+ }
522
+ async readFile(path) {
523
+ return await (await this.#loadDraft()).store.readFile(normalizeSafeWorkspacePath(path, { allowEmpty: true }));
524
+ }
525
+ async list(path = "", options) {
526
+ return await (await this.#loadDraft()).store.list(path, options);
527
+ }
528
+ async glob(pattern, options) {
529
+ return await (await this.#loadDraft()).store.glob(pattern, options);
530
+ }
531
+ async stat(path) {
532
+ return await (await this.#loadDraft()).store.stat(normalizeSafeWorkspacePath(path, { allowEmpty: true }));
533
+ }
534
+ async writeFile(path, file) {
535
+ await this.#write((store) => store.writeFile(normalizeHistoryPath(path), file));
536
+ }
537
+ async writeFileConditional(path, file, ifDigest) {
538
+ await this.#write((store) => store.writeFileConditional(normalizeHistoryPath(path), file, ifDigest));
539
+ }
540
+ async mkdir(path, options) {
541
+ await this.#write((store) => store.mkdir(normalizeHistoryPath(path), options));
542
+ }
543
+ async rm(path, options) {
544
+ await this.#write((store) => store.rm(normalizeHistoryPath(path), options));
545
+ }
546
+ async removeEmptyDirectory(path) {
547
+ await this.#write((store) => store.removeEmptyDirectory(normalizeHistoryPath(path)));
548
+ }
549
+ async snapshot(options = {}) {
550
+ return await this.#mutate(async () => {
551
+ const draft = await this.#loadDraft();
552
+ const files = Object.create(null);
553
+ for (const entry of await draft.store.list("", { recursive: true })) if (entry.type === "file") files[entry.path] = await draft.store.readFile(entry.path);
554
+ const revision = await this.#commit({
555
+ ifHead: draft.head?.id ?? null,
556
+ files,
557
+ message: options.name,
558
+ ...options.author ? { metadata: { author: options.author } } : {}
559
+ });
560
+ this.#dirty = false;
561
+ this.#draft = void 0;
562
+ this.#baseline = void 0;
563
+ const view = await this.#open(revision.id);
564
+ const snapshot = await createSnapshotFromEntries(await view.list("", { recursive: true }), options.name);
565
+ this.#baseline = {
566
+ ...snapshot,
567
+ id: revision.id,
568
+ createdAt: revision.createdAt
569
+ };
570
+ return this.#baseline;
571
+ });
572
+ }
573
+ async diff(options = {}) {
574
+ const draft = await this.#loadDraft();
575
+ const baseline = options.from ?? this.#baseline ?? (draft.head ? {
576
+ ...await createSnapshotFromEntries(await (await this.#open(draft.head.id)).list("", { recursive: true })),
577
+ id: draft.head.id
578
+ } : void 0);
579
+ return diffSnapshots(baseline, await createSnapshotFromEntries(await draft.store.list("", { recursive: true })));
580
+ }
581
+ async getMeta(key) {
582
+ const workspace = await this.#key();
583
+ const [row] = await this.#db.select().from(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key), this.#active(workspace)));
584
+ return row?.value;
585
+ }
586
+ async setMeta(key, value) {
587
+ await this.#assertActive();
588
+ const workspace = await this.#key();
589
+ if (value === void 0) {
590
+ await this.#db.delete(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key)));
591
+ return;
592
+ }
593
+ await this.#db.insert(metadata).select(this.#db.select({
594
+ workspace: sql`${workspace}`.as("workspace"),
595
+ key: sql`${key}`.as("key"),
596
+ value: sql`${JSON.stringify(value)}`.as("value")
597
+ }).from(workspaces).where(and(eq(workspaces.workspace, workspace), eq(workspaces.deleted, false)))).onConflictDoUpdate({
598
+ target: [metadata.workspace, metadata.key],
599
+ set: { value: sql`${JSON.stringify(value)}` }
600
+ });
601
+ }
602
+ };
603
+ /** Blob stores bytes; Database atomically publishes immutable folder manifests. */
604
+ function createBlobDatabaseWorkspaceStore(options) {
605
+ return new ContentAddressedWorkspaceStore(options);
606
+ }
607
+ //#endregion
608
+ export { createBlobDatabaseWorkspaceStore, workspaceHistorySchema };