@vite-hub/workspace 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +225 -58
  2. package/dist/{ai-CjxvGqM0.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  3. package/dist/{ai-BqCC8BpY.js → ai-BZyLwULx.js} +147 -66
  4. package/dist/ai.d.ts +2 -2
  5. package/dist/ai.js +1 -1
  6. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  7. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  8. package/dist/blob-database.d.ts +521 -0
  9. package/dist/blob-database.js +601 -0
  10. package/dist/cloudflare.d.ts +5 -6
  11. package/dist/cloudflare.js +1 -1
  12. package/dist/config-B7dmzDX3.js +1112 -0
  13. package/dist/{config-DE9xlaIw.d.ts → config-DLKdaFWN.d.ts} +1 -2
  14. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  15. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  16. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  17. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  18. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  19. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  20. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  21. package/dist/file-C0_aPWSS.js +26 -0
  22. package/dist/file-metadata-CxDy-E2H.js +58 -0
  23. package/dist/{files-Q6xZjDHA.js → files-C7Px8uaC.js} +3 -3
  24. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  25. package/dist/{github-DHnjxQIX.js → github-CPxHtFB7.js} +16 -23
  26. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  27. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  28. package/dist/glob--XcLlcml.js +22 -0
  29. package/dist/glob--kNYDbfU.js +30 -0
  30. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  31. package/dist/{host-DJH8cuoU.js → host-CFnrTXTK.js} +97 -41
  32. package/dist/{hosted-RPeJOCFz.js → hosted-acMA5XyL.js} +102 -19
  33. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  34. package/dist/hosted-vercel-blob.d.ts +5 -6
  35. package/dist/hosted-vercel-blob.js +1 -1
  36. package/dist/hosted.d.ts +6 -7
  37. package/dist/hosted.js +1 -1
  38. package/dist/index.d.ts +57 -36
  39. package/dist/index.js +56 -56
  40. package/dist/inspect-BoObD2cJ.js +167 -0
  41. package/dist/internal/path.d.ts +2 -0
  42. package/dist/internal/path.js +2 -0
  43. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  44. package/dist/loader.d.ts +5 -6
  45. package/dist/loader.js +3 -2
  46. package/dist/mcp-resources-BREFCmtn.js +39 -0
  47. package/dist/memory-BbwOqDXl.js +248 -0
  48. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  49. package/dist/mountx.d.ts +4 -6
  50. package/dist/mountx.js +10 -8
  51. package/dist/nitro.d.ts +1 -1
  52. package/dist/nitro.js +1 -1
  53. package/dist/nuxt.d.ts +13 -12
  54. package/dist/nuxt.js +4 -8
  55. package/dist/operations-BcpWr41m.js +159 -0
  56. package/dist/operations-CGqY1XeG.js +965 -0
  57. package/dist/operations-DnOwKsJT.d.ts +136 -0
  58. package/dist/operations.d.ts +53 -0
  59. package/dist/operations.js +2 -0
  60. package/dist/path-CNAwN7pw.js +114 -0
  61. package/dist/path-DrSIenjj.js +59 -0
  62. package/dist/path-zHxQUbqa.d.ts +9 -0
  63. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  64. package/dist/provider-kXjfli9u.js +1457 -0
  65. package/dist/providers/github/store.d.ts +3 -5
  66. package/dist/providers/github/store.js +1 -1
  67. package/dist/{registry-D3yzt8HQ.js → registry-Bp-8UUfG.js} +9 -7
  68. package/dist/{registry-Uj6IVxes.d.ts → registry-Cg1TJVVZ.d.ts} +1 -2
  69. package/dist/{request-execution-B-dSFlGB.js → request-execution-Dk9rY-Yh.js} +19 -19
  70. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-B4iAMlE-.js} +2 -2
  71. package/dist/runtime/assets.d.ts +3 -5
  72. package/dist/runtime/assets.js +7 -6
  73. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  74. package/dist/runtime/empty-registry.d.ts +1 -2
  75. package/dist/runtime/state.d.ts +3 -3
  76. package/dist/runtime/state.js +6 -6
  77. package/dist/runtime/workspace.d.ts +1 -1
  78. package/dist/runtime/workspace.js +1 -1
  79. package/dist/runtime.d.ts +51 -17
  80. package/dist/runtime.js +320 -60
  81. package/dist/{search-BpiCF2Tw.js → search-CrTmXj5h.js} +10 -9
  82. package/dist/server-BNQ-Nbjj.js +290 -0
  83. package/dist/server.d.ts +22 -34
  84. package/dist/server.js +2 -328
  85. package/dist/shared-DalXdP0i.js +2158 -0
  86. package/dist/source-metadata.d.ts +6 -7
  87. package/dist/source-metadata.js +7 -7
  88. package/dist/{state-tYcRWEh2.d.ts → state-B8zbLi5t.d.ts} +3 -3
  89. package/dist/store-CXgmu-uw.js +1729 -0
  90. package/dist/{sync-DnTQwt8r.js → sync-CN6ec-5M.js} +61 -41
  91. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  92. package/dist/test.d.ts +1 -1
  93. package/dist/test.js +1 -1
  94. package/dist/{token-CVzURBxC.js → token-CO62GglH.js} +3 -3
  95. package/dist/{types-CYuwjJ4V.d.ts → types-DeK9GIxy.d.ts} +256 -24
  96. package/dist/{use-BTNDR5Rd.js → use-BQj7nSz6.js} +82 -41
  97. package/dist/{use-BiHzt0xA.d.ts → use-DhwhbAVV.d.ts} +16 -11
  98. package/dist/utils-Blrh4N2n.js +545 -0
  99. package/dist/vite-BEvgU2GY.js +20909 -0
  100. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  101. package/dist/vite.d.ts +2 -2
  102. package/dist/vite.js +2 -2
  103. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  104. package/dist/{workspace-Dq08Yn72.js → workspace-6pxkOuxr.js} +361 -230
  105. package/dist/{workspace-Xddf4G1B.d.ts → workspace-BWJQBK1u.d.ts} +4 -3
  106. package/package.json +89 -55
  107. package/dist/collections/client.d.ts +0 -39
  108. package/dist/collections/client.js +0 -137
  109. package/dist/collections.d.ts +0 -59
  110. package/dist/collections.js +0 -159
  111. package/dist/config-Bc3c4Su1.js +0 -7904
  112. package/dist/config-CHLLWklZ.js +0 -36
  113. package/dist/file-Bc1X7pco.js +0 -23
  114. package/dist/glob-CEZKeZFC.js +0 -18
  115. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  116. package/dist/lifecycle-LrL3sA4n.js +0 -316
  117. package/dist/metadata-target-B0tOmVW7.js +0 -717
  118. package/dist/path-Cp59koVz.js +0 -139
  119. package/dist/provider-B1yLjCJJ.js +0 -746
  120. package/dist/publish.d.ts +0 -35
  121. package/dist/publish.js +0 -112
  122. package/dist/runtime-options-BsPSv5O7.js +0 -13
  123. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  124. package/dist/shared-DTR1Hhma.js +0 -331
  125. package/dist/store-Dt_Jyys3.js +0 -608
  126. package/dist/vite-BptCrpv2.js +0 -4526
  127. package/dist/vite-CtA9guIM.d.ts +0 -66
@@ -0,0 +1,1588 @@
1
+ import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { f as sha256, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, o as isWorkspaceBytes, t as contentStreamChunks } from "./path-CNAwN7pw.js";
3
+ import { n as resolveWorkspaceStoreTarget, t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
+ import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath } from "./config-B7dmzDX3.js";
5
+ import { t as copyJsonFileMetadata } from "./file-metadata-CxDy-E2H.js";
6
+ import { t as searchText } from "./search-CrTmXj5h.js";
7
+ import { posix } from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
10
+ //#region src/storage/identity.ts
11
+ const aliases = /* @__PURE__ */ new WeakMap();
12
+ const stableIdentities = /* @__PURE__ */ new WeakSet();
13
+ function workspaceStoreIdentity(store) {
14
+ let identity = store;
15
+ const seen = /* @__PURE__ */ new Set();
16
+ while (true) {
17
+ const next = aliases.get(identity);
18
+ if (!next || seen.has(next)) return identity;
19
+ seen.add(identity);
20
+ identity = next;
21
+ }
22
+ }
23
+ function registerWorkspaceStoreAlias(alias, store) {
24
+ const aliasIdentity = workspaceStoreIdentity(alias);
25
+ const storeIdentity = workspaceStoreIdentity(store);
26
+ if (aliasIdentity === storeIdentity) return;
27
+ if (stableIdentities.has(aliasIdentity)) aliases.set(storeIdentity, aliasIdentity);
28
+ else {
29
+ aliases.set(aliasIdentity, storeIdentity);
30
+ stableIdentities.add(storeIdentity);
31
+ }
32
+ }
33
+ //#endregion
34
+ //#region src/sources/file-ownership.ts
35
+ const activeCheckpoints = /* @__PURE__ */ new WeakMap();
36
+ const checkpointMetaKey = (path) => `workspace-file-checkpoint:${encodeURIComponent(normalizeWorkspacePath(path))}`;
37
+ const volatileOwners = /* @__PURE__ */ new WeakMap();
38
+ const fileOwnerMetaKey = (path) => `workspace-file-owner:${encodeURIComponent(normalizeWorkspacePath(path))}`;
39
+ function volatileFileOwners(store) {
40
+ const identity = workspaceStoreIdentity(store);
41
+ let owners = volatileOwners.get(identity);
42
+ if (!owners) {
43
+ owners = /* @__PURE__ */ new Map();
44
+ volatileOwners.set(identity, owners);
45
+ }
46
+ return owners;
47
+ }
48
+ async function beginWorkspaceFileCheckpoint(store, path) {
49
+ if (!store.getMeta || !store.setMeta) return void 0;
50
+ const token = crypto.randomUUID();
51
+ const current = await store.getMeta(checkpointMetaKey(path));
52
+ const currentRecord = current && typeof current === "object" ? current : void 0;
53
+ const previous = currentRecord ? Object.hasOwn(currentRecord, "committed") && currentRecord.committed === true && Object.hasOwn(currentRecord, "token") ? currentRecord.token : Object.hasOwn(currentRecord, "previous") ? currentRecord.previous : void 0 : void 0;
54
+ await store.setMeta(checkpointMetaKey(path), {
55
+ token,
56
+ committed: false,
57
+ previous
58
+ });
59
+ const identity = workspaceStoreIdentity(store);
60
+ let checkpoints = activeCheckpoints.get(identity);
61
+ if (!checkpoints) {
62
+ checkpoints = /* @__PURE__ */ new Map();
63
+ activeCheckpoints.set(identity, checkpoints);
64
+ }
65
+ checkpoints.set(normalizeWorkspacePath(path), token);
66
+ return token;
67
+ }
68
+ function endWorkspaceFileCheckpoint(store, path) {
69
+ activeCheckpoints.get(workspaceStoreIdentity(store))?.delete(normalizeWorkspacePath(path));
70
+ }
71
+ async function commitWorkspaceFileCheckpoint(store, path, token) {
72
+ if (token) await store.setMeta(checkpointMetaKey(path), {
73
+ token,
74
+ committed: true
75
+ });
76
+ }
77
+ async function recordWorkspaceFileOwner(store, path, owner) {
78
+ const checkpoint = activeCheckpoints.get(workspaceStoreIdentity(store))?.get(normalizeWorkspacePath(path));
79
+ if (checkpoint) owner = {
80
+ ...owner,
81
+ checkpoint
82
+ };
83
+ if (!store.getMeta || !store.setMeta) {
84
+ volatileFileOwners(store).set(fileOwnerMetaKey(path), owner);
85
+ return;
86
+ }
87
+ try {
88
+ await store.setMeta(fileOwnerMetaKey(path), owner);
89
+ volatileOwners.get(workspaceStoreIdentity(store))?.delete(fileOwnerMetaKey(path));
90
+ } catch (error) {
91
+ volatileFileOwners(store).set(fileOwnerMetaKey(path), owner);
92
+ throw error;
93
+ }
94
+ }
95
+ async function readWorkspaceFileOwner(store, path, retireInvalidRemoval = false) {
96
+ const volatile = volatileOwners.get(workspaceStoreIdentity(store))?.get(fileOwnerMetaKey(path));
97
+ const value = volatile !== void 0 ? volatile : await store.getMeta?.(fileOwnerMetaKey(path));
98
+ const owner = value && typeof value === "object" ? value : void 0;
99
+ if (!owner || !Object.hasOwn(owner, "workspace") || typeof owner.workspace !== "string" || !Object.hasOwn(owner, "source") || typeof owner.source !== "string" || Object.hasOwn(owner, "digest") && owner.digest !== void 0 && typeof owner.digest !== "string") return void 0;
100
+ if (Object.hasOwn(owner, "checkpoint") && owner.checkpoint !== activeCheckpoints.get(workspaceStoreIdentity(store))?.get(normalizeWorkspacePath(path))) {
101
+ const checkpointRecord = await store.getMeta?.(checkpointMetaKey(path));
102
+ if (!checkpointRecord || typeof checkpointRecord !== "object" || !(Object.hasOwn(checkpointRecord, "token") && checkpointRecord.token === owner.checkpoint && Object.hasOwn(checkpointRecord, "committed") && checkpointRecord.committed === true || Object.hasOwn(checkpointRecord, "previous") && checkpointRecord.previous === owner.checkpoint)) {
103
+ if (retireInvalidRemoval) await removeWorkspaceFileOwner(store, path);
104
+ return;
105
+ }
106
+ }
107
+ if (Object.hasOwn(owner, "removing") && owner.removing === true) {
108
+ const current = await store.stat(path);
109
+ if (current?.type === "file" && (!Object.hasOwn(owner, "revision") || !owner.revision || !current.revision)) throw new Error(`[vitehub] Cannot retry interrupted removal without a file revision: ${path}. Inspect the file and remove it explicitly if cleanup is still needed.`);
110
+ const remaining = current?.type === "file" ? await store.readFile(path) : void 0;
111
+ if (current?.type !== "file" || !Object.hasOwn(owner, "revision") || current.revision !== owner.revision || !Object.hasOwn(owner, "digest") || !owner.digest || !remaining || await sha256(remaining.content) !== owner.digest) {
112
+ if (retireInvalidRemoval) await removeWorkspaceFileOwner(store, path);
113
+ return;
114
+ }
115
+ }
116
+ return {
117
+ workspace: owner.workspace,
118
+ source: owner.source,
119
+ digest: Object.hasOwn(owner, "digest") && typeof owner.digest === "string" ? owner.digest : void 0
120
+ };
121
+ }
122
+ async function removeWorkspaceFileOwner(store, path) {
123
+ const owners = volatileFileOwners(store);
124
+ owners.set(fileOwnerMetaKey(path), null);
125
+ if (store.getMeta && store.setMeta) {
126
+ await store.setMeta(fileOwnerMetaKey(path), null);
127
+ owners.delete(fileOwnerMetaKey(path));
128
+ }
129
+ }
130
+ async function markWorkspaceFileRemoval(store, path) {
131
+ const owner = await readWorkspaceFileOwner(store, path);
132
+ if (owner) {
133
+ const revision = (await store.stat(path))?.revision;
134
+ const removal = {
135
+ ...owner,
136
+ removing: true
137
+ };
138
+ if (revision) removal.revision = revision;
139
+ await recordWorkspaceFileOwner(store, path, removal);
140
+ }
141
+ }
142
+ async function removeWorkspaceOwnedFile(store, path) {
143
+ await markWorkspaceFileRemoval(store, path);
144
+ await store.rm(path, { force: true });
145
+ await removeWorkspaceFileOwner(store, path);
146
+ }
147
+ async function withWorkspaceFileCheckpoint(store, path, write, checkpoint, rollbackCheckpoint) {
148
+ const previous = (await store.stat(path))?.type === "file" ? await store.readFile(path) : void 0;
149
+ const owner = await readWorkspaceFileOwner(store, path);
150
+ const token = previous ? await beginWorkspaceFileCheckpoint(store, path) : void 0;
151
+ try {
152
+ const result = await write();
153
+ try {
154
+ await checkpoint(result);
155
+ } catch (error) {
156
+ try {
157
+ if (previous) try {
158
+ await markWorkspaceFileRemoval(store, path);
159
+ } finally {
160
+ endWorkspaceFileCheckpoint(store, path);
161
+ await store.writeFile(path, previous);
162
+ try {
163
+ if (owner) await recordWorkspaceFileOwner(store, path, owner);
164
+ else await removeWorkspaceFileOwner(store, path);
165
+ } finally {
166
+ await rollbackCheckpoint?.();
167
+ }
168
+ }
169
+ else {
170
+ await removeWorkspaceOwnedFile(store, path);
171
+ await rollbackCheckpoint?.();
172
+ }
173
+ } catch (rollbackError) {
174
+ throw new AggregateError([error, rollbackError], `Workspace file checkpoint and rollback failed for "${path}".`);
175
+ }
176
+ throw error;
177
+ }
178
+ await commitWorkspaceFileCheckpoint(store, path, token);
179
+ return result;
180
+ } finally {
181
+ endWorkspaceFileCheckpoint(store, path);
182
+ }
183
+ }
184
+ //#endregion
185
+ //#region src/sources/file-metadata.ts
186
+ function normalizeMetadataValue(value) {
187
+ if (Array.isArray(value)) return value.map(normalizeMetadataValue);
188
+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) return value;
189
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => [key, normalizeMetadataValue(entry)]));
190
+ }
191
+ function normalizeSourceFileMetadata(metadata) {
192
+ return copyJsonFileMetadata("Source", metadata, true);
193
+ }
194
+ //#endregion
195
+ //#region src/sources/source-items.ts
196
+ function normalizeWorkspaceSourceItemPath(source, rawSourcePath, options = {}) {
197
+ const sourcePath = normalizeSafeWorkspacePath(rawSourcePath, {
198
+ allowEmpty: false,
199
+ allowReserved: true
200
+ });
201
+ const label = options.operation ? `${options.operation} item path` : "source item path";
202
+ if (sourcePath.split("/").some((part) => part === ".git" || part === ".vitehub")) throw workspaceError(`[vitehub] Workspace ${label} is reserved: ${rawSourcePath}.`);
203
+ const mountedPath = source.mountPath ? `${source.mountPath}/${sourcePath}` : sourcePath;
204
+ const path = normalizeSafeWorkspacePath(mountedPath, { allowEmpty: false });
205
+ if (source.mountPath && !sourceMountContainsPath(source, path)) throw workspaceError(`[vitehub] Workspace ${label} escapes source mount: ${rawSourcePath}.`);
206
+ return {
207
+ path,
208
+ sourcePath
209
+ };
210
+ }
211
+ function normalizeSourceItemPath(source, item, options = {}) {
212
+ return normalizeWorkspaceSourceItemPath(source, item.path || item.key, options);
213
+ }
214
+ //#endregion
215
+ //#region src/storage/mutation.ts
216
+ const workspaceStoreMutations = /* @__PURE__ */ new WeakMap();
217
+ async function withWorkspaceStoreMutation(store, operation) {
218
+ const identity = workspaceStoreIdentity(store);
219
+ const pending = (workspaceStoreMutations.get(identity) ?? Promise.resolve()).then(operation);
220
+ const settled = pending.then(() => {}, () => {});
221
+ workspaceStoreMutations.set(identity, settled);
222
+ try {
223
+ return await pending;
224
+ } finally {
225
+ if (workspaceStoreMutations.get(identity) === settled) workspaceStoreMutations.delete(identity);
226
+ }
227
+ }
228
+ //#endregion
229
+ //#region src/sources/mount-grants.ts
230
+ /**
231
+ * Proof that one Source owner may change Workspace files inside one Source mount.
232
+ * Only the authority of the owner creates a grant. A grant is request-scoped. Do not persist it.
233
+ */
234
+ var WorkspaceSourceMountGrant = class {
235
+ #mountPath;
236
+ #source;
237
+ constructor(source, mountPath) {
238
+ this.#mountPath = mountPath;
239
+ this.#source = source;
240
+ Object.freeze(this);
241
+ }
242
+ get mountPath() {
243
+ return this.#mountPath;
244
+ }
245
+ get source() {
246
+ return this.#source;
247
+ }
248
+ };
249
+ /** A root Source (empty mount) owns every Workspace path. */
250
+ function sourceMountOwnsPath(source, path) {
251
+ return !source.mountPath || path === source.mountPath || path.startsWith(`${source.mountPath}/`);
252
+ }
253
+ /**
254
+ * Creates the grant authority of one Source owner, for example Source Sync or Source materialization.
255
+ * Keep the authority private to its owner module. Grants from one authority do not unlock another authority.
256
+ */
257
+ function createWorkspaceSourceMountAuthority(owner) {
258
+ const grants = /* @__PURE__ */ new WeakMap();
259
+ return {
260
+ /** Creates a grant bound to the Source key and its normalized mount. */
261
+ grant(source) {
262
+ const mountPath = normalizeSafeWorkspacePath(source.mountPath, { allowEmpty: true });
263
+ const grant = new WorkspaceSourceMountGrant(source.key, mountPath);
264
+ grants.set(grant, {
265
+ mountPath,
266
+ source: source.key
267
+ });
268
+ return grant;
269
+ },
270
+ /**
271
+ * Returns the Store limited to the mount of a grant from this authority.
272
+ * File writes, `mkdir`, and `rm` must stay inside the mount. `removeEmptyDirectory` can also remove
273
+ * an ancestor of the mount, because the owner created it for the mount.
274
+ */
275
+ store(grant, store) {
276
+ const scope = grants.get(grant);
277
+ if (!scope) throw workspaceError(`[vitehub] ${owner} requires a Source mount grant to change Workspace files.`);
278
+ const assertInMount = (path, allowAncestor = false) => {
279
+ const workspacePath = normalizeSafeWorkspacePath(path, {
280
+ allowEmpty: true,
281
+ allowReserved: true
282
+ });
283
+ if (sourceMountOwnsPath(scope, workspacePath) || allowAncestor && scope.mountPath.startsWith(`${workspacePath}/`)) return path;
284
+ throw workspaceError(`[vitehub] ${owner} for Source ${JSON.stringify(scope.source)} cannot change ${path} outside its mount ${JSON.stringify(scope.mountPath)}.`);
285
+ };
286
+ const scoped = {
287
+ readFile: async (path) => await store.readFile(path),
288
+ writeFile: async (path, file) => await store.writeFile(assertInMount(path), file),
289
+ list: async (prefix, options) => await store.list(prefix, options),
290
+ glob: async (pattern, options) => await store.glob(pattern, options),
291
+ stat: async (path) => await store.stat(path),
292
+ mkdir: async (path, options) => await store.mkdir(assertInMount(path), options),
293
+ rm: async (path, options) => await store.rm(assertInMount(path), options),
294
+ snapshot: async (options) => await store.snapshot(options),
295
+ diff: async (options) => await store.diff(options)
296
+ };
297
+ if (store.writeFileConditional) scoped.writeFileConditional = async (path, file, ifDigest) => await store.writeFileConditional(assertInMount(path), file, ifDigest);
298
+ if (store.writeFileStream) scoped.writeFileStream = async (path, file) => await store.writeFileStream(assertInMount(path), file);
299
+ if (store.removeEmptyDirectory) scoped.removeEmptyDirectory = async (path) => await store.removeEmptyDirectory(assertInMount(path, true));
300
+ if (store.getMeta) scoped.getMeta = async (key) => await store.getMeta(key);
301
+ if (store.setMeta) scoped.setMeta = async (key, value) => await store.setMeta(key, value);
302
+ registerWorkspaceStoreAlias(scoped, store);
303
+ forwardWorkspaceStoreTarget(store, scoped);
304
+ return scoped;
305
+ }
306
+ };
307
+ }
308
+ //#endregion
309
+ //#region src/sources/materialization.ts
310
+ const startupSourcesMetaKey = (workspace) => `workspace:${workspace}:startup-sources`;
311
+ const startupWorkspacesMetaKey = "workspace:startup-source-workspaces";
312
+ const volatileSnapshots = /* @__PURE__ */ new WeakMap();
313
+ const volatileStartupIndexes = /* @__PURE__ */ new WeakMap();
314
+ const startupReconciliationByStore = /* @__PURE__ */ new WeakMap();
315
+ const activeStartupSourcesByStore = /* @__PURE__ */ new WeakMap();
316
+ const sourceMaterializationGrants = createWorkspaceSourceMountAuthority("Source materialization");
317
+ function sourceSnapshotMetaKey(workspace, sourceKey) {
318
+ return `workspace:${encodeURIComponent(workspace)}:source:${encodeURIComponent(sourceKey)}:snapshot`;
319
+ }
320
+ function sourceConfigFingerprint(source) {
321
+ return {
322
+ cache: source.cache,
323
+ key: source.key,
324
+ materialize: source.materialize,
325
+ mountPath: source.mountPath,
326
+ source: source.source.fingerprint
327
+ };
328
+ }
329
+ async function sourceConfigHash(source, store) {
330
+ const target = await resolveWorkspaceStoreTarget(store);
331
+ const version = {};
332
+ if (target?.provider === "local") version.fileMetadataVersion = 1;
333
+ return await sha256({
334
+ ...version,
335
+ ...sourceConfigFingerprint(source)
336
+ });
337
+ }
338
+ function isSnapshotFresh(meta, source, configHash) {
339
+ if (!meta || meta.status !== "ready" || meta.configHash !== configHash) return false;
340
+ if (!source.cache) return false;
341
+ const maxAge = source.cache.maxAge ?? NaN;
342
+ if (!Number.isFinite(maxAge)) return false;
343
+ if (!meta.materializedAt) return false;
344
+ return Date.now() - Date.parse(meta.materializedAt) <= maxAge * 1e3;
345
+ }
346
+ async function readSourceSnapshotMetadata(store, workspace, sourceKey, source) {
347
+ const volatile = volatileSnapshots.get(workspaceStoreIdentity(store));
348
+ const key = sourceSnapshotMetaKey(workspace, sourceKey);
349
+ if (volatile?.has(key)) return volatile.get(key);
350
+ const snapshot = await store.getMeta?.(sourceSnapshotMetaKey(workspace, sourceKey));
351
+ const recovery = await store.getMeta?.(`${sourceSnapshotMetaKey(workspace, sourceKey)}:recovery`);
352
+ if (recovery?.status === "ready" && snapshot?.status !== "ready") return recovery;
353
+ if (recovery?.status === "ready" && snapshot?.ownsMount === false && recovery.ownsMount !== false) return recovery;
354
+ if (snapshot?.status === "ready") return snapshot;
355
+ if (snapshot || !source) return snapshot;
356
+ const legacy = await store.getMeta?.(`source:${sourceKey}:snapshot`);
357
+ return legacy?.configHash === await sourceConfigHash(source, store) ? legacy : void 0;
358
+ }
359
+ async function invalidateSourceSnapshot(store, workspace, sourceKey) {
360
+ const snapshot = await readSourceSnapshotMetadata(store, workspace, sourceKey);
361
+ if (snapshot) await writeSourceSnapshotMetadata(store, workspace, {
362
+ ...snapshot,
363
+ status: "updating"
364
+ });
365
+ }
366
+ async function hasCurrentSourceSnapshot(store, workspace, source, verifyOwnership = false, activeSources = []) {
367
+ const configHash = await sourceConfigHash(source, store);
368
+ const meta = await readSourceSnapshotMetadata(store, workspace, source.key, source);
369
+ if (meta?.status !== "ready" || meta.configHash !== configHash) return false;
370
+ if (verifyOwnership === "workspace") {
371
+ if (Object.keys(meta.items || {}).length === 0 && meta.ownsMount !== false && meta.mountPath && (await store.stat(meta.mountPath))?.type !== "directory") return false;
372
+ for (const path of Object.keys(meta.items || {})) {
373
+ const file = await store.readFile(path);
374
+ if (!file) return false;
375
+ const inlineOwner = file.metadata?.workspaceSourceOwner;
376
+ if (inlineOwner !== void 0 && inlineOwner !== workspace) return false;
377
+ const owner = await readWorkspaceFileOwner(store, path);
378
+ if (!owner || owner.workspace === workspace || !owner.digest) continue;
379
+ if (await sha256(file.content) === owner.digest) return false;
380
+ }
381
+ return true;
382
+ }
383
+ return !verifyOwnership || await snapshotHasCurrentOwners(store, workspace, source, meta, activeSources);
384
+ }
385
+ async function snapshotHasCurrentOwners(store, workspace, source, meta, activeSources = []) {
386
+ if (Object.keys(meta.items || {}).length === 0 && meta.mountPath && (await store.stat(meta.mountPath))?.type !== "directory") return false;
387
+ const listed = source.mountPath ? new Map((await store.list(source.mountPath, { recursive: true })).map((entry) => [entry.path, entry])) : void 0;
388
+ for (const path of Object.keys(meta.items || {})) {
389
+ const stat = listed?.get(path) ?? await store.stat(path);
390
+ if (await materializedFileHasCurrentOwner(store, workspace, source.key, path, stat)) continue;
391
+ const owner = await readWorkspaceFileOwner(store, path);
392
+ const currentSource = activeSources.find((item) => item.key === owner?.source && item.materialize === "startup");
393
+ if (source.materialize !== "startup" || owner?.workspace !== workspace || !owner.digest || !currentSource) return false;
394
+ const currentSnapshot = await readCurrentSourceSnapshot(store, workspace, currentSource);
395
+ if (currentSnapshot?.status !== "ready" || !Object.hasOwn(currentSnapshot.items || {}, path)) return false;
396
+ if (!await materializedFileHasCurrentOwner(store, workspace, currentSource.key, path, stat)) return false;
397
+ const file = await store.readFile(path);
398
+ if (!file || await sha256(file.content) !== owner.digest) return false;
399
+ }
400
+ return true;
401
+ }
402
+ async function materializedFileHasCurrentOwner(store, workspace, source, path, stat) {
403
+ if (stat?.type !== "file") return false;
404
+ if (stat.metadata?.workspaceSourceOwner === workspace && stat.metadata.source === source) return true;
405
+ if (stat.metadata?.workspaceSourceOwner !== void 0 && stat.metadata.workspaceSourceOwner !== workspace) return false;
406
+ if (stat.metadata?.source !== void 0 && stat.metadata.source !== source) return false;
407
+ const durable = await readWorkspaceFileOwner(store, path);
408
+ if (durable?.workspace !== workspace || durable.source !== source || !durable.digest) return false;
409
+ const file = await store.readFile(path);
410
+ return !!file && await sha256(file.content) === durable.digest;
411
+ }
412
+ async function hasFreshSourceSnapshot(store, workspace, source) {
413
+ const configHash = await sourceConfigHash(source, store);
414
+ const meta = await readSourceSnapshotMetadata(store, workspace, source.key, source);
415
+ return !!meta && isSnapshotFresh(meta, source, configHash) && await snapshotHasCurrentOwners(store, workspace, source, meta);
416
+ }
417
+ async function readCurrentSourceSnapshot(store, workspace, source) {
418
+ const configHash = await sourceConfigHash(source, store);
419
+ const snapshot = await readSourceSnapshotMetadata(store, workspace, source.key, source);
420
+ return snapshot?.configHash === configHash ? snapshot : void 0;
421
+ }
422
+ async function readSourceSnapshotPaths(store, workspace, sourceKey) {
423
+ const snapshot = await readSourceSnapshotMetadata(store, workspace, sourceKey);
424
+ return Object.keys(snapshot?.items || {});
425
+ }
426
+ async function sourceSnapshotOwnsAnyPath(store, workspace, sourceKey, paths) {
427
+ const meta = await readSourceSnapshotMetadata(store, workspace, sourceKey);
428
+ if (!meta || meta.status !== "ready") return void 0;
429
+ const ownedPaths = new Set(Object.keys(meta.items || {}));
430
+ return [...paths].some((path) => ownedPaths.has(normalizeWorkspacePath(path)));
431
+ }
432
+ async function writeSourceSnapshotMetadata(store, workspace, metadata) {
433
+ let snapshots = volatileSnapshots.get(workspaceStoreIdentity(store));
434
+ if (!snapshots) {
435
+ snapshots = /* @__PURE__ */ new Map();
436
+ volatileSnapshots.set(workspaceStoreIdentity(store), snapshots);
437
+ }
438
+ const key = sourceSnapshotMetaKey(workspace, metadata.source);
439
+ snapshots.set(key, metadata);
440
+ if (store.getMeta && store.setMeta) {
441
+ if (!key.endsWith(":recovery")) await store.setMeta(`${key}:recovery`, void 0);
442
+ await store.setMeta(key, metadata);
443
+ snapshots.delete(key);
444
+ }
445
+ }
446
+ function materializedItemMeta(snapshot, configHash, path) {
447
+ if (!snapshot || snapshot.configHash !== configHash) return void 0;
448
+ if (snapshot.status !== "ready" && snapshot.status !== "updating" && snapshot.status !== "error") return void 0;
449
+ const item = snapshot.items?.[path];
450
+ return item?.migrationPending ? void 0 : item;
451
+ }
452
+ function checkpointItems(items) {
453
+ return Object.keys(items).length ? items : void 0;
454
+ }
455
+ function contentSize(content) {
456
+ return isWorkspaceBytes(content) ? content.byteLength : new TextEncoder().encode(content).byteLength;
457
+ }
458
+ function observableFileMetadata(metadata) {
459
+ return Object.fromEntries(Object.entries(metadata || {}).filter(([key, value]) => key !== "materializedAt" && key !== "validatedAt" && value !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => [key, normalizeMetadataValue(value)]));
460
+ }
461
+ function isDeepStrictEqual(left, right) {
462
+ if (Object.is(left, right)) return true;
463
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
464
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
465
+ const prototype = Object.getPrototypeOf(left);
466
+ if (prototype !== Object.getPrototypeOf(right)) return false;
467
+ if (left instanceof Date) return right instanceof Date && Object.is(left.getTime(), right.getTime());
468
+ if (!Array.isArray(left) && prototype !== Object.prototype && prototype !== null) return false;
469
+ if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
470
+ const leftRecord = left;
471
+ const rightRecord = right;
472
+ const leftKeys = Object.keys(leftRecord);
473
+ const rightKeys = Object.keys(rightRecord);
474
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
475
+ }
476
+ function fileAttributesEqual(previous, previousSnapshot, mediaType, metadata) {
477
+ if (previousSnapshot?.materializedAttributes) return previousSnapshot.materializedMediaType === mediaType && isDeepStrictEqual(observableFileMetadata(previousSnapshot.materializedMetadata), observableFileMetadata(metadata));
478
+ return (previous.mediaType === void 0 || previous.mediaType === mediaType) && (previous.metadata === void 0 || isDeepStrictEqual(observableFileMetadata(previous.metadata), observableFileMetadata(metadata)));
479
+ }
480
+ function sourcePathMatches(path, source, options) {
481
+ if (options?.sources && !options.sources.includes(source.key)) return false;
482
+ const requested = normalizeWorkspacePath(options?.path || "");
483
+ if (!requested) return true;
484
+ return sourceMountIntersectsPath(source, requested);
485
+ }
486
+ function pathContains(container, path) {
487
+ return !container || path === container || path.startsWith(`${container}/`);
488
+ }
489
+ function materializationPathMatches(path, options) {
490
+ return pathContains(normalizeWorkspacePath(options?.path || ""), path);
491
+ }
492
+ function materializesCompleteSource(source, options) {
493
+ const requested = normalizeWorkspacePath(options?.path || "");
494
+ return !requested || Boolean(source.mountPath && pathContains(requested, source.mountPath));
495
+ }
496
+ function shouldMaterializeSource(source, options) {
497
+ if (source.requestOnly || !sourcePathMatches("", source, options)) return false;
498
+ if (source.materialize === "lazy" || source.materialize === "startup") return true;
499
+ return source.materialize === "build" && Boolean(options?.path);
500
+ }
501
+ function throwIfAborted(signal) {
502
+ if (!signal?.aborted) return;
503
+ throw signal.reason instanceof Error ? signal.reason : workspaceError("[vitehub] Workspace source materialization aborted.");
504
+ }
505
+ async function reportMaterializationProgress(options, source, event) {
506
+ await options?.onProgress?.({
507
+ ...event,
508
+ mountPath: source.mountPath,
509
+ path: normalizeWorkspacePath(options?.path || ""),
510
+ provider: source.source.name,
511
+ source: source.key
512
+ });
513
+ }
514
+ function emptyMaterializationCounts() {
515
+ return {
516
+ added: 0,
517
+ removed: 0,
518
+ unchanged: 0,
519
+ updated: 0
520
+ };
521
+ }
522
+ function materializationCacheStatus(source, complete, hit) {
523
+ if (!complete) return "bypassed";
524
+ if (!source.cache) return "disabled";
525
+ return hit ? "hit" : "miss";
526
+ }
527
+ function materializationPaths(options, paths) {
528
+ return options?.details === "paths" ? paths.slice().sort((left, right) => left.path.localeCompare(right.path) || left.status.localeCompare(right.status)) : void 0;
529
+ }
530
+ function contentEquals(left, right) {
531
+ const leftBytes = isWorkspaceBytes(left) ? left : new TextEncoder().encode(left);
532
+ const rightBytes = isWorkspaceBytes(right) ? right : new TextEncoder().encode(right);
533
+ return leftBytes.byteLength === rightBytes.byteLength && leftBytes.every((byte, index) => byte === rightBytes[index]);
534
+ }
535
+ function shouldReportMaterializationUpdate(lastReportedAt, files) {
536
+ return files === 1 || files % 25 === 0 || Date.now() - lastReportedAt >= 1e3;
537
+ }
538
+ function looksLikeConcreteFilePath(path) {
539
+ const name = posix.basename(path);
540
+ return name.includes(".") || [
541
+ "Dockerfile",
542
+ "LICENSE",
543
+ "Makefile",
544
+ "Procfile",
545
+ "README"
546
+ ].includes(name);
547
+ }
548
+ function directMaterializationSourceKey(source, options) {
549
+ const requested = normalizeWorkspacePath(options?.path || "");
550
+ if (!requested || !sourceMountContainsPath(source, requested) || requested === source.mountPath) return;
551
+ const sourcePath = source.mountPath ? requested.slice(source.mountPath.length + 1) : requested;
552
+ return sourcePath && looksLikeConcreteFilePath(sourcePath) ? sourcePath : void 0;
553
+ }
554
+ function parentDirectoryPaths(path) {
555
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
556
+ const paths = [];
557
+ for (let index = 1; index < parts.length; index++) paths.push(parts.slice(0, index).join("/"));
558
+ return paths;
559
+ }
560
+ function sourceOwnsDirectory(source, path) {
561
+ return !source.mountPath || path === source.mountPath || path.startsWith(`${source.mountPath}/`);
562
+ }
563
+ async function removeStaleMaterializedSourceFiles(store, grant, workspace, source, sources, nextPaths, scope, control, previousSnapshot, ownedDirectories, checkpointDirectoryOwnership, onRemoved) {
564
+ const sourceStore = sourceMaterializationGrants.store(grant, store);
565
+ const previousPaths = new Set(Object.keys(previousSnapshot?.items || {}));
566
+ const scopedPreviousPaths = [...previousPaths].filter((path) => materializationPathMatches(path, scope));
567
+ const nextDirectories = new Set([...nextPaths].flatMap((path) => parentDirectoryPaths(path)));
568
+ const staleDirectories = new Set((previousSnapshot?.ownedDirectories || []).filter((path) => sourceOwnsDirectory(source, path) && materializationPathMatches(path, scope)));
569
+ const retainedMounts = /* @__PURE__ */ new Map();
570
+ if (source.materialize === "startup" && source.mountPath) {
571
+ const workspaces = await readStartupIndex(store, startupWorkspacesMetaKey);
572
+ for (const otherWorkspace of Array.isArray(workspaces) ? workspaces.filter((name) => name !== workspace) : []) {
573
+ const indexedSources = await readStartupIndex(store, startupSourcesMetaKey(otherWorkspace));
574
+ for (const indexedSource of Array.isArray(indexedSources) ? indexedSources.filter(isMaterializedStartupSource) : []) {
575
+ if (indexedSource.mountPath !== source.mountPath) continue;
576
+ const snapshot = await readSourceSnapshotMetadata(store, otherWorkspace, indexedSource.key);
577
+ if (snapshot && snapshot.ownsMount !== false) retainedMounts.set(source.mountPath, snapshot);
578
+ }
579
+ }
580
+ }
581
+ const removedDirectories = /* @__PURE__ */ new Set();
582
+ const entries = source.materialize === "startup" && store.getMeta && store.setMeta && previousSnapshot?.mountPath !== void 0 ? await Promise.all(scopedPreviousPaths.map(async (path) => await store.stat(path))) : source.mountPath ? await store.list(source.mountPath, { recursive: true }) : previousPaths.size || store.getMeta && store.setMeta && (!previousSnapshot || previousSnapshot.items) ? await Promise.all(scopedPreviousPaths.map(async (path) => await store.stat(path))) : await store.list("", { recursive: true });
583
+ for (const path of previousPaths) {
584
+ if (source.mountPath && !sourceMountContainsPath(source, path)) {
585
+ if (previousSnapshot?.mountPath === source.mountPath) throw workspaceError(`[vitehub] Source materialization path ${path} is outside its mount ${source.mountPath}.`);
586
+ continue;
587
+ }
588
+ if (!nextPaths.has(path) && materializationPathMatches(path, scope)) await control.mutate(() => withWorkspaceStoreMutation(store, () => readWorkspaceFileOwner(store, path, true)));
589
+ }
590
+ for (const entry of entries) {
591
+ if (!entry || source.mountPath && !sourceMountContainsPath(source, entry.path) || !materializationPathMatches(entry.path, scope) || nextPaths.has(entry.path) || entry.type !== "file") continue;
592
+ await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
593
+ const file = await store.readFile(entry.path);
594
+ const durableOwner = await readWorkspaceFileOwner(store, entry.path);
595
+ if (file?.metadata?.workspaceSourceOwner !== workspace && durableOwner?.workspace !== workspace) return;
596
+ const currentOwner = file?.metadata?.source ?? durableOwner?.source;
597
+ if (source.materialize === "startup" && store.getMeta && store.setMeta && !previousSnapshot && currentOwner !== void 0) return;
598
+ const recordedDigest = previousSnapshot?.items?.[entry.path]?.materializedContentDigest;
599
+ if (file?.metadata?.source === void 0 && durableOwner?.digest !== void 0 && recordedDigest !== void 0 && durableOwner.digest !== recordedDigest) return;
600
+ if (file?.metadata?.source === void 0 && (!durableOwner?.digest || !file || await sha256(file.content) !== durableOwner.digest)) {
601
+ if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, entry.path);
602
+ return;
603
+ }
604
+ if (previousSnapshot?.items && (!recordedDigest || !file || await sha256(file.content) !== recordedDigest)) {
605
+ if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, entry.path);
606
+ return;
607
+ }
608
+ if (currentOwner === void 0 && previousSnapshot?.items && !recordedDigest) return;
609
+ const overlapsAnotherSource = sources.some((candidate) => candidate.key !== source.key && candidate.mountPath.length >= source.mountPath.length && sourceMountContainsPath(candidate, entry.path));
610
+ if (currentOwner === source.key || currentOwner === void 0 && (previousPaths.has(entry.path) || Boolean(source.mountPath) && !overlapsAnotherSource)) {
611
+ for (const directory of parentDirectoryPaths(entry.path)) if (sourceOwnsDirectory(source, directory) && (directory !== source.mountPath || previousSnapshot?.ownsMount)) staleDirectories.add(directory);
612
+ for (const candidate of sources) {
613
+ if (candidate.key === source.key) continue;
614
+ const retainedSnapshot = await readSourceSnapshotMetadata(store, workspace, candidate.key);
615
+ if (retainedSnapshot?.status !== "ready" || !retainedSnapshot.items?.[entry.path]) continue;
616
+ await writeSourceSnapshotMetadata(store, workspace, {
617
+ ...retainedSnapshot,
618
+ status: "updating"
619
+ });
620
+ }
621
+ await removeWorkspaceOwnedFile(sourceStore, entry.path);
622
+ onRemoved?.(entry.path, file ? contentSize(file.content) : 0);
623
+ }
624
+ }));
625
+ }
626
+ const cleanupDirectories = [...staleDirectories].filter((path) => !nextDirectories.has(path)).sort((a, b) => b.length - a.length);
627
+ for (const path of cleanupDirectories) ownedDirectories.add(path);
628
+ for (const path of cleanupDirectories) {
629
+ if (retainedMounts.has(path)) {
630
+ await checkpointDirectoryOwnership(path, false);
631
+ continue;
632
+ }
633
+ if ((await store.stat(path))?.type === "file") {
634
+ ownedDirectories.delete(path);
635
+ removedDirectories.add(path);
636
+ continue;
637
+ }
638
+ if ((await store.list(path)).length || !sourceStore.removeEmptyDirectory) continue;
639
+ try {
640
+ if (await control.mutate(async () => {
641
+ if ((await store.list(path)).length) return false;
642
+ if ((await store.stat(path))?.type !== "directory") return true;
643
+ await checkpointDirectoryOwnership(path, false);
644
+ try {
645
+ await sourceStore.removeEmptyDirectory(path);
646
+ } catch (error) {
647
+ await checkpointDirectoryOwnership(path, true);
648
+ throw error;
649
+ }
650
+ return true;
651
+ })) {
652
+ ownedDirectories.delete(path);
653
+ removedDirectories.add(path);
654
+ }
655
+ } catch (error) {
656
+ if (!(await store.list(path)).length) throw error;
657
+ }
658
+ }
659
+ return removedDirectories;
660
+ }
661
+ async function reconcileRemovedStartupSources(workspace, store, currentSources, control = {
662
+ isCurrent: () => true,
663
+ async mutate(operation) {
664
+ return await operation();
665
+ },
666
+ async checkpoint(operation) {
667
+ return await operation();
668
+ }
669
+ }, materializationStore = store) {
670
+ const previous = startupReconciliationByStore.get(materializationStore);
671
+ const current = (async () => {
672
+ await previous;
673
+ await reconcileRemovedStartupSourcesInternal(workspace, store, currentSources, control, activeStartupSourcesByStore.get(materializationStore)?.get(workspace));
674
+ })();
675
+ const tail = current.catch(() => {});
676
+ startupReconciliationByStore.set(materializationStore, tail);
677
+ try {
678
+ await current;
679
+ } finally {
680
+ if (startupReconciliationByStore.get(materializationStore) === tail) startupReconciliationByStore.delete(materializationStore);
681
+ }
682
+ }
683
+ async function reconcileRemovedStartupSourcesInternal(workspace, store, currentSources, control, activeSources = /* @__PURE__ */ new Set()) {
684
+ const workspaceIndex = await readStartupIndex(store, startupWorkspacesMetaKey);
685
+ const workspaces = new Set(Array.isArray(workspaceIndex) ? workspaceIndex.filter((name) => typeof name === "string") : []);
686
+ workspaces.add(workspace);
687
+ await control.checkpoint(() => writeStartupIndex(store, startupWorkspacesMetaKey, [...workspaces]));
688
+ const value = await readStartupIndex(store, startupSourcesMetaKey(workspace));
689
+ const previousSources = Array.isArray(value) ? value.filter(isMaterializedStartupSource) : [];
690
+ const currentMounts = new Map(currentSources.map((source) => [source.key, source.mountPath]));
691
+ const activeOwners = [...activeSources];
692
+ const isActive = (source) => activeOwners.some((active) => active.key === source.key && active.mountPath === source.mountPath);
693
+ const retainedSources = currentSources.map((source) => ({
694
+ workspace,
695
+ source
696
+ }));
697
+ for (const otherWorkspace of workspaces) {
698
+ if (otherWorkspace === workspace) continue;
699
+ const sources = await readStartupIndex(store, startupSourcesMetaKey(otherWorkspace));
700
+ if (!Array.isArray(sources)) continue;
701
+ for (const source of sources.filter(isMaterializedStartupSource)) retainedSources.push({
702
+ workspace: otherWorkspace,
703
+ source
704
+ });
705
+ }
706
+ const pendingDirectoryCleanup = [];
707
+ for (const source of previousSources.filter((source) => currentMounts.get(source.key) !== source.mountPath && !isActive(source))) {
708
+ const sourceStore = sourceMaterializationGrants.store(sourceMaterializationGrants.grant(source), store);
709
+ const snapshot = await readSourceSnapshotMetadata(store, workspace, source.key);
710
+ const invalidatedSnapshot = snapshot && snapshot.mountPath === void 0 && snapshot.items === void 0;
711
+ if (snapshot?.mountPath !== source.mountPath && !invalidatedSnapshot) continue;
712
+ const previousPaths = invalidatedSnapshot ? (await store.list(source.mountPath, { recursive: true })).filter((entry) => entry.type === "file").map((entry) => entry.path) : Object.keys(snapshot?.items || {});
713
+ const staleDirectories = /* @__PURE__ */ new Set([...snapshot?.ownedAncestors || [], ...(snapshot?.ownedDirectories || []).filter((path) => sourceOwnsDirectory(source, path))]);
714
+ if (source.mountPath && snapshot?.ownsMount) staleDirectories.add(source.mountPath);
715
+ for (const path of previousPaths) {
716
+ if (source.mountPath && !sourceMountContainsPath(source, path)) continue;
717
+ await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
718
+ const file = await store.readFile(path);
719
+ const durableOwner = await readWorkspaceFileOwner(store, path, true);
720
+ if (!file) return;
721
+ if (file.metadata?.workspaceSourceOwner !== workspace && durableOwner?.workspace !== workspace) return;
722
+ const owner = file.metadata?.source ?? durableOwner?.source;
723
+ const recordedDigest = snapshot?.items?.[path]?.materializedContentDigest;
724
+ if (file.metadata?.source === void 0 && (!durableOwner?.digest || await sha256(file.content) !== durableOwner.digest)) {
725
+ if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, path);
726
+ return;
727
+ }
728
+ if (snapshot?.items && (!recordedDigest || await sha256(file.content) !== recordedDigest)) {
729
+ if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, path);
730
+ return;
731
+ }
732
+ if (owner !== source.key && !(owner === void 0 && recordedDigest && await sha256(file.content) === recordedDigest)) return;
733
+ for (const currentSource of currentSources) {
734
+ const retainedSnapshot = await readSourceSnapshotMetadata(store, workspace, currentSource.key);
735
+ if (retainedSnapshot?.status !== "ready" || !retainedSnapshot.items?.[path]) continue;
736
+ await writeSourceSnapshotMetadata(store, workspace, {
737
+ ...retainedSnapshot,
738
+ status: "updating"
739
+ });
740
+ }
741
+ await removeWorkspaceOwnedFile(sourceStore, path);
742
+ }));
743
+ }
744
+ let directoryCleanupUnavailable = false;
745
+ let cleanupSnapshot = snapshot;
746
+ const retireDirectory = async (path) => {
747
+ if (!cleanupSnapshot) return;
748
+ const previous = cleanupSnapshot;
749
+ const retired = {
750
+ ...cleanupSnapshot,
751
+ ownsMount: path === source.mountPath ? false : cleanupSnapshot.ownsMount,
752
+ ownedAncestors: cleanupSnapshot.ownedAncestors?.filter((directory) => directory !== path),
753
+ ownedDirectories: cleanupSnapshot.ownedDirectories?.filter((directory) => directory !== path)
754
+ };
755
+ try {
756
+ await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, retired));
757
+ } catch (error) {
758
+ try {
759
+ await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, previous));
760
+ } catch {
761
+ if (store.setMeta) await store.setMeta(`${sourceSnapshotMetaKey(workspace, source.key)}:recovery`, previous);
762
+ }
763
+ throw error;
764
+ }
765
+ cleanupSnapshot = retired;
766
+ };
767
+ for (const path of [...staleDirectories].sort((a, b) => b.length - a.length)) {
768
+ let ownershipTransferred = false;
769
+ const retainedMount = path === source.mountPath ? retainedSources.find(({ workspace: retainedWorkspace, source: retainedSource }) => retainedWorkspace !== workspace && retainedSource.mountPath === path) : void 0;
770
+ if (retainedMount) {
771
+ await retireDirectory(path);
772
+ const retainedSnapshot = await readSourceSnapshotMetadata(store, retainedMount.workspace, retainedMount.source.key);
773
+ if (retainedSnapshot) await control.checkpoint(() => writeSourceSnapshotMetadata(store, retainedMount.workspace, {
774
+ ...retainedSnapshot,
775
+ ownsMount: true
776
+ }));
777
+ continue;
778
+ }
779
+ for (const { workspace: retainedWorkspace, source: currentSource } of retainedSources) {
780
+ const retainedSnapshot = await readSourceSnapshotMetadata(store, retainedWorkspace, currentSource.key);
781
+ if (retainedSnapshot?.mountPath !== currentSource.mountPath) continue;
782
+ const containsMount = pathContains(path, currentSource.mountPath);
783
+ if (!containsMount && !Object.keys(retainedSnapshot.items || {}).some((item) => pathContains(path, item))) continue;
784
+ if (!ownershipTransferred) await retireDirectory(path);
785
+ await control.checkpoint(() => writeSourceSnapshotMetadata(store, retainedWorkspace, {
786
+ ...retainedSnapshot,
787
+ ...path === currentSource.mountPath ? { ownsMount: true } : containsMount ? { ownedAncestors: [.../* @__PURE__ */ new Set([...retainedSnapshot.ownedAncestors || [], path])] } : { ownedDirectories: [.../* @__PURE__ */ new Set([...retainedSnapshot.ownedDirectories || [], path])] }
788
+ }));
789
+ ownershipTransferred = true;
790
+ }
791
+ if (ownershipTransferred) continue;
792
+ if ((await store.stat(path))?.type !== "directory" || (await store.list(path)).length) continue;
793
+ if (!sourceStore.removeEmptyDirectory) {
794
+ directoryCleanupUnavailable = true;
795
+ continue;
796
+ }
797
+ await control.mutate(async () => {
798
+ if ((await store.list(path)).length || (await store.stat(path))?.type !== "directory") return;
799
+ const previousSnapshot = cleanupSnapshot;
800
+ await retireDirectory(path);
801
+ try {
802
+ await sourceStore.removeEmptyDirectory(path);
803
+ } catch (error) {
804
+ if (previousSnapshot) {
805
+ try {
806
+ await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, previousSnapshot));
807
+ } catch {
808
+ if (store.setMeta) await store.setMeta(`${sourceSnapshotMetaKey(workspace, source.key)}:recovery`, previousSnapshot);
809
+ }
810
+ cleanupSnapshot = previousSnapshot;
811
+ }
812
+ throw error;
813
+ }
814
+ });
815
+ }
816
+ if (directoryCleanupUnavailable) {
817
+ pendingDirectoryCleanup.push(source);
818
+ continue;
819
+ }
820
+ await control.checkpoint(async () => {
821
+ const key = sourceSnapshotMetaKey(workspace, source.key);
822
+ if (!store.getMeta || !store.setMeta) {
823
+ let snapshots = volatileSnapshots.get(workspaceStoreIdentity(store));
824
+ if (!snapshots) {
825
+ snapshots = /* @__PURE__ */ new Map();
826
+ volatileSnapshots.set(workspaceStoreIdentity(store), snapshots);
827
+ }
828
+ snapshots.set(key, void 0);
829
+ return;
830
+ }
831
+ await store.setMeta(key, {});
832
+ });
833
+ }
834
+ const trackedSources = [
835
+ ...currentSources,
836
+ ...activeOwners,
837
+ ...previousSources.filter(isActive),
838
+ ...pendingDirectoryCleanup
839
+ ];
840
+ const uniqueSources = trackedSources.filter((source, index) => trackedSources.findIndex((candidate) => candidate.key === source.key && candidate.mountPath === source.mountPath) === index);
841
+ await control.checkpoint(() => writeStartupIndex(store, startupSourcesMetaKey(workspace), uniqueSources.map(({ key, mountPath }) => ({
842
+ key,
843
+ mountPath
844
+ }))));
845
+ if (!uniqueSources.length) {
846
+ workspaces.delete(workspace);
847
+ await control.checkpoint(() => writeStartupIndex(store, startupWorkspacesMetaKey, [...workspaces]));
848
+ }
849
+ }
850
+ async function readStartupIndex(store, key) {
851
+ return volatileStartupIndexes.get(workspaceStoreIdentity(store))?.get(key) ?? await store.getMeta?.(key);
852
+ }
853
+ async function writeStartupIndex(store, key, value) {
854
+ if (!store.getMeta || !store.setMeta) {
855
+ let indexes = volatileStartupIndexes.get(workspaceStoreIdentity(store));
856
+ if (!indexes) {
857
+ indexes = /* @__PURE__ */ new Map();
858
+ volatileStartupIndexes.set(workspaceStoreIdentity(store), indexes);
859
+ }
860
+ indexes.set(key, value);
861
+ return;
862
+ }
863
+ await store.setMeta(key, value);
864
+ }
865
+ function isMaterializedStartupSource(value) {
866
+ if (!hasRuntimeType(value, "object") || value === null) return false;
867
+ const source = value;
868
+ return readStringMeta(source, "key") !== void 0 && readStringMeta(source, "mountPath") !== void 0;
869
+ }
870
+ async function* iterateSourceItems(source, ctx) {
871
+ if (source.source.getItems) {
872
+ yield* await source.source.getItems(ctx);
873
+ return;
874
+ }
875
+ for (const key of await source.source.getKeys(ctx)) yield await source.source.getItem(key, ctx);
876
+ }
877
+ function createMaterializationEntry(source, item, upstreamMeta) {
878
+ const { path, sourcePath } = normalizeSourceItemPath(source, item, { operation: "source materialization" });
879
+ return {
880
+ item,
881
+ metadata: createLazyMaterializedMetadata({
882
+ sourceKey: source.key,
883
+ sourcePath,
884
+ validate: source.validate
885
+ }, item, upstreamMeta),
886
+ path,
887
+ ...sourceItemContent(item)
888
+ };
889
+ }
890
+ function sourceItemContent(item) {
891
+ if (item.contentStream) {
892
+ if (item.content !== void 0 || item.data !== void 0) throw workspaceError("[vitehub] Workspace source items cannot define contentStream with content or data.");
893
+ return { contentStream: item.contentStream };
894
+ }
895
+ return { content: item.content ?? (item.data === void 0 ? "" : JSON.stringify(item.data, null, 2)) };
896
+ }
897
+ async function* iterateMaterializationEntries(source, ctx, store, snapshot, configHash, options, workspace) {
898
+ const directKey = directMaterializationSourceKey(source, options);
899
+ if (directKey) {
900
+ const entry = createMaterializationEntry(source, await source.source.getItem(directKey, ctx), void 0);
901
+ if (materializationPathMatches(entry.path, options)) yield entry;
902
+ return;
903
+ }
904
+ if (source.source.getItems) {
905
+ for await (const item of iterateSourceItems(source, ctx)) {
906
+ const entry = createMaterializationEntry(source, item, item.metadata ?? await source.source.getMeta?.(item.key, ctx));
907
+ if (materializationPathMatches(entry.path, options)) yield entry;
908
+ }
909
+ return;
910
+ }
911
+ for (const key of await source.source.getKeys(ctx)) {
912
+ const upstreamMeta = await source.source.getMeta?.(key, ctx);
913
+ const { path, sourcePath } = normalizeWorkspaceSourceItemPath(source, key, { operation: "source materialization" });
914
+ if (!materializationPathMatches(path, options)) continue;
915
+ const previous = materializedItemMeta(snapshot, configHash, path);
916
+ if (upstreamMeta && previous?.source === source.key && previous.sourcePath === sourcePath && !hasSourceMetaChanged(previous, upstreamMeta)) {
917
+ const stat = await store.stat(path);
918
+ if (stat && await materializedFileHasCurrentOwner(store, workspace, source.key, path, stat)) {
919
+ yield {
920
+ metadata: previous,
921
+ path,
922
+ reused: stat
923
+ };
924
+ continue;
925
+ }
926
+ }
927
+ yield createMaterializationEntry(source, await source.source.getItem(key, ctx), upstreamMeta);
928
+ }
929
+ }
930
+ async function materializeWorkspaceSources(definition, store, options = {}, control = {
931
+ isCurrent: () => true,
932
+ async mutate(operation) {
933
+ return await operation();
934
+ },
935
+ async checkpoint(operation) {
936
+ return await operation();
937
+ }
938
+ }) {
939
+ const activeByWorkspace = activeStartupSourcesByStore.get(store) ?? /* @__PURE__ */ new Map();
940
+ const activeSources = activeByWorkspace.get(definition.name) ?? /* @__PURE__ */ new Set();
941
+ const selectedSources = normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "startup" && shouldMaterializeSource(source, options));
942
+ for (const source of selectedSources) activeSources.add(source);
943
+ activeByWorkspace.set(definition.name, activeSources);
944
+ activeStartupSourcesByStore.set(store, activeByWorkspace);
945
+ try {
946
+ return await materializeWorkspaceSourcesInternal(definition, store, options, control);
947
+ } finally {
948
+ for (const source of selectedSources) activeSources.delete(source);
949
+ if (!activeSources.size) activeByWorkspace.delete(definition.name);
950
+ if (!activeByWorkspace.size) activeStartupSourcesByStore.delete(store);
951
+ }
952
+ }
953
+ async function materializeWorkspaceSourcesInternal(definition, store, options, control) {
954
+ const workspace = definition.name;
955
+ const assertCurrent = () => {
956
+ if (!control.isCurrent()) throw options.abortSignal?.reason ?? workspaceError("[vitehub] Workspace source materialization was superseded.");
957
+ };
958
+ const started = Date.now();
959
+ const configuredSources = normalizeWorkspaceSources(definition.sources);
960
+ const sources = configuredSources.filter((source) => shouldMaterializeSource(source, options));
961
+ const startupSources = configuredSources.filter((source) => source.materialize === "startup");
962
+ const rootMaterialization = !normalizeWorkspacePath(options.path || "");
963
+ if (sources.some((source) => source.materialize === "startup") || rootMaterialization && !options.sources?.length) await reconcileRemovedStartupSources(definition.name, store, startupSources, control);
964
+ const resultSources = [];
965
+ let files = 0;
966
+ let directories = 0;
967
+ let bytes = 0;
968
+ for (const source of sources) {
969
+ throwIfAborted(options.abortSignal);
970
+ const sourceStarted = Date.now();
971
+ await reportMaterializationProgress(options, source, { status: "started" });
972
+ let configHash;
973
+ let existing;
974
+ try {
975
+ configHash = await sourceConfigHash(source, store);
976
+ existing = await readSourceSnapshotMetadata(store, workspace, source.key, source);
977
+ if (existing && !await store.getMeta?.(sourceSnapshotMetaKey(workspace, source.key))) {
978
+ const adopted = existing;
979
+ await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, adopted));
980
+ }
981
+ } catch (error) {
982
+ const durationMs = Date.now() - sourceStarted;
983
+ const message = error instanceof Error ? error.message : String(error);
984
+ const failed = {
985
+ counts: emptyMaterializationCounts(),
986
+ durationMs,
987
+ error: message,
988
+ mountPath: source.mountPath,
989
+ provider: source.source.name,
990
+ source: source.key,
991
+ status: "error"
992
+ };
993
+ resultSources.push(failed);
994
+ await reportMaterializationProgress(options, source, {
995
+ counts: failed.counts,
996
+ durationMs,
997
+ error: message,
998
+ status: "failed"
999
+ });
1000
+ if (options.abortSignal?.aborted) throw error;
1001
+ continue;
1002
+ }
1003
+ const completeSource = materializesCompleteSource(source, options);
1004
+ const cacheHit = completeSource && !!existing && isSnapshotFresh(existing, source, configHash) && await snapshotHasCurrentOwners(store, workspace, source, existing);
1005
+ const cacheStatus = materializationCacheStatus(source, completeSource, cacheHit);
1006
+ if (cacheHit) {
1007
+ const durationMs = Date.now() - sourceStarted;
1008
+ const cachedPaths = Object.keys(existing?.items || {});
1009
+ const cachedFiles = cachedPaths.length || existing?.files || 0;
1010
+ const counts = {
1011
+ ...emptyMaterializationCounts(),
1012
+ unchanged: cachedFiles
1013
+ };
1014
+ const ready = {
1015
+ cacheStatus,
1016
+ counts,
1017
+ durationMs,
1018
+ source: source.key,
1019
+ mountPath: source.mountPath,
1020
+ provider: source.source.name,
1021
+ status: "ready",
1022
+ revision: existing?.revision,
1023
+ materializedAt: existing?.materializedAt,
1024
+ files: existing?.files,
1025
+ bytes: existing?.bytes
1026
+ };
1027
+ const paths = materializationPaths(options, cachedPaths.map((path) => ({
1028
+ path,
1029
+ status: "unchanged"
1030
+ })));
1031
+ if (paths) ready.paths = paths;
1032
+ resultSources.push(ready);
1033
+ files += cachedFiles;
1034
+ bytes += existing?.bytes || 0;
1035
+ await reportMaterializationProgress(options, source, {
1036
+ bytes: existing?.bytes || 0,
1037
+ cacheStatus,
1038
+ counts,
1039
+ durationMs,
1040
+ files: cachedFiles,
1041
+ revision: existing?.revision,
1042
+ status: "completed"
1043
+ });
1044
+ continue;
1045
+ }
1046
+ let ownsMount = Boolean(source.mountPath) && existing?.mountPath === source.mountPath && existing.ownsMount === true && Boolean(await store.stat(source.mountPath));
1047
+ const ownedAncestors = [...existing?.mountPath === source.mountPath ? existing.ownedAncestors || [] : []];
1048
+ const ownedDirectories = new Set(existing?.mountPath === source.mountPath ? existing.ownedDirectories : []);
1049
+ let revision = existing?.revision;
1050
+ const retainPriorItems = existing?.configHash === configHash || !completeSource && source.materialize === "startup" && existing?.mountPath === source.mountPath;
1051
+ const itemMetadata = existing?.configHash === configHash ? { ...existing.items } : Object.fromEntries(Object.entries(existing?.items || {}).map(([path, metadata]) => [path, {
1052
+ ...metadata,
1053
+ migrationPending: true
1054
+ }]));
1055
+ if (completeSource) {
1056
+ assertCurrent();
1057
+ await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, {
1058
+ configHash,
1059
+ source: source.key,
1060
+ mountPath: source.mountPath,
1061
+ ownsMount,
1062
+ ownedAncestors,
1063
+ ownedDirectories: [...ownedDirectories],
1064
+ status: "updating",
1065
+ revision,
1066
+ items: checkpointItems(itemMetadata),
1067
+ cacheMaxAge: source.cache ? source.cache.maxAge : void 0
1068
+ }));
1069
+ }
1070
+ const grant = sourceMaterializationGrants.grant(source);
1071
+ const sourceStore = sourceMaterializationGrants.store(grant, store);
1072
+ let sourceFiles = 0;
1073
+ let sourceBytes = 0;
1074
+ let persistedBytesDelta = 0;
1075
+ let lastProgressAt = 0;
1076
+ const counts = emptyMaterializationCounts();
1077
+ const paths = [];
1078
+ try {
1079
+ const ctx = createSourceContext(definition, source, store, { abortSignal: options.abortSignal });
1080
+ throwIfAborted(options.abortSignal);
1081
+ await prepareWorkspaceSource(source.source, ctx);
1082
+ throwIfAborted(options.abortSignal);
1083
+ if (source.mountPath) await control.mutate(async () => {
1084
+ const mountExists = Boolean(await store.stat(source.mountPath));
1085
+ const missingAncestors = [];
1086
+ for (const path of parentDirectoryPaths(source.mountPath)) if (!await store.stat(path)) missingAncestors.push(path);
1087
+ await sourceStore.mkdir(source.mountPath, { recursive: true });
1088
+ ownsMount = ownsMount || !mountExists;
1089
+ for (const path of missingAncestors) if (!ownedAncestors.includes(path)) ownedAncestors.push(path);
1090
+ });
1091
+ revision = ctx.revision;
1092
+ const directorySet = new Set(source.mountPath ? [source.mountPath] : []);
1093
+ const nextPaths = /* @__PURE__ */ new Set();
1094
+ for await (const entry of iterateMaterializationEntries(source, ctx, store, existing, configHash, options, workspace)) {
1095
+ throwIfAborted(options.abortSignal);
1096
+ const path = entry.path;
1097
+ nextPaths.add(path);
1098
+ const parts = path.split("/");
1099
+ for (let index = 1; index < parts.length; index++) directorySet.add(parts.slice(0, index).join("/"));
1100
+ if (entry.reused) {
1101
+ itemMetadata[path] = entry.metadata;
1102
+ sourceFiles++;
1103
+ const reusedFile = entry.reused.size === void 0 ? await store.readFile(path) : void 0;
1104
+ sourceBytes += entry.reused.size ?? (reusedFile ? contentSize(reusedFile.content) : 0);
1105
+ counts.unchanged++;
1106
+ paths.push({
1107
+ path,
1108
+ status: "unchanged"
1109
+ });
1110
+ if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
1111
+ await reportMaterializationProgress(options, source, {
1112
+ bytes: sourceBytes,
1113
+ cacheStatus,
1114
+ counts: { ...counts },
1115
+ files: sourceFiles,
1116
+ revision,
1117
+ status: "updating"
1118
+ });
1119
+ lastProgressAt = Date.now();
1120
+ }
1121
+ continue;
1122
+ }
1123
+ const item = entry.item;
1124
+ const metadata = normalizeSourceFileMetadata(item.metadata || {});
1125
+ const previousStat = await store.stat(path);
1126
+ const previous = entry.contentStream && store.writeFileStream ? void 0 : await store.readFile(path);
1127
+ const previousExists = previousStat?.type === "file" || Boolean(previous);
1128
+ const fileMetadata = normalizeSourceFileMetadata({
1129
+ ...metadata,
1130
+ ...entry.metadata,
1131
+ source: source.key,
1132
+ workspaceSourceOwner: workspace
1133
+ });
1134
+ const missingDirectories = [];
1135
+ for (const directory of parentDirectoryPaths(path)) if (directory !== source.mountPath && sourceOwnsDirectory(source, directory) && !await store.stat(directory)) missingDirectories.push(directory);
1136
+ const tracked = Object.hasOwn(itemMetadata, path);
1137
+ const previousItemMetadata = itemMetadata[path];
1138
+ const written = await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
1139
+ const write = () => writeMaterializedFile(sourceStore, path, {
1140
+ path,
1141
+ content: entry.content,
1142
+ contentStream: entry.contentStream,
1143
+ mediaType: item.mediaType,
1144
+ metadata: fileMetadata
1145
+ }, previous?.content);
1146
+ const checkpoint = async (result) => {
1147
+ for (const directory of missingDirectories) ownedDirectories.add(directory);
1148
+ itemMetadata[path] = {
1149
+ ...entry.metadata,
1150
+ materializedAttributes: true,
1151
+ materializedContentDigest: result.digest,
1152
+ materializedBytes: result.size || 0,
1153
+ materializedMediaType: item.mediaType,
1154
+ materializedMetadata: observableFileMetadata(fileMetadata)
1155
+ };
1156
+ await recordWorkspaceFileOwner(store, path, {
1157
+ workspace,
1158
+ source: source.key,
1159
+ digest: result.digest
1160
+ });
1161
+ };
1162
+ if (source.materialize !== "startup") {
1163
+ const result = await write();
1164
+ await checkpoint(result);
1165
+ return result;
1166
+ }
1167
+ return await withWorkspaceFileCheckpoint(sourceStore, path, write, checkpoint, async () => {
1168
+ if (previousItemMetadata) itemMetadata[path] = previousItemMetadata;
1169
+ else delete itemMetadata[path];
1170
+ });
1171
+ }));
1172
+ sourceFiles++;
1173
+ sourceBytes += written.size || 0;
1174
+ persistedBytesDelta += (written.size || 0) - (tracked ? previousItemMetadata?.materializedBytes ?? previousStat?.size ?? (previous ? contentSize(previous.content) : 0) : 0);
1175
+ const status = (entry.contentStream ? store.writeFileStream ? previousStat?.type === "file" && previousStat.digest !== void 0 && previousStat.digest === written.storeDigest : written.contentEqual === true : previous !== void 0 && contentEquals(previous.content, entry.content ?? "")) && fileAttributesEqual(previous ?? previousStat ?? {}, previousItemMetadata, item.mediaType, fileMetadata) ? "unchanged" : previousExists ? "updated" : "added";
1176
+ counts[status]++;
1177
+ paths.push({
1178
+ path,
1179
+ status
1180
+ });
1181
+ if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
1182
+ await reportMaterializationProgress(options, source, {
1183
+ bytes: sourceBytes,
1184
+ cacheStatus,
1185
+ counts: { ...counts },
1186
+ files: sourceFiles,
1187
+ revision,
1188
+ status: "updating"
1189
+ });
1190
+ lastProgressAt = Date.now();
1191
+ }
1192
+ }
1193
+ throwIfAborted(options.abortSignal);
1194
+ const removedDirectories = await removeStaleMaterializedSourceFiles(store, grant, workspace, source, configuredSources, nextPaths, options, control, existing, ownedDirectories, async (path, owned) => {
1195
+ const previouslyOwned = ownedDirectories.has(path);
1196
+ const previouslyOwnedMount = ownsMount;
1197
+ if (owned) ownedDirectories.add(path);
1198
+ else ownedDirectories.delete(path);
1199
+ if (path === source.mountPath) ownsMount = owned;
1200
+ try {
1201
+ await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, {
1202
+ configHash,
1203
+ source: source.key,
1204
+ mountPath: source.mountPath,
1205
+ ownsMount,
1206
+ ownedAncestors,
1207
+ ownedDirectories: [...ownedDirectories],
1208
+ status: "updating",
1209
+ revision,
1210
+ items: checkpointItems(itemMetadata),
1211
+ cacheMaxAge: source.cache ? source.cache.maxAge : void 0
1212
+ }));
1213
+ } catch (error) {
1214
+ if (!owned) {
1215
+ if (previouslyOwned) ownedDirectories.add(path);
1216
+ else ownedDirectories.delete(path);
1217
+ ownsMount = previouslyOwnedMount;
1218
+ }
1219
+ throw error;
1220
+ }
1221
+ }, (path, removedBytes) => {
1222
+ counts.removed++;
1223
+ if (Object.hasOwn(itemMetadata, path)) persistedBytesDelta -= itemMetadata[path]?.materializedBytes ?? removedBytes;
1224
+ delete itemMetadata[path];
1225
+ paths.push({
1226
+ path,
1227
+ status: "removed"
1228
+ });
1229
+ });
1230
+ if (removedDirectories.has(source.mountPath)) ownsMount = false;
1231
+ for (const directory of removedDirectories) ownedDirectories.delete(directory);
1232
+ const readyItems = Object.fromEntries([...nextPaths].flatMap((path) => {
1233
+ const metadata = itemMetadata[path];
1234
+ return metadata ? [[path, metadata]] : [];
1235
+ }));
1236
+ const ready = {
1237
+ configHash,
1238
+ source: source.key,
1239
+ mountPath: source.mountPath,
1240
+ ownsMount,
1241
+ ownedAncestors,
1242
+ ownedDirectories: [...ownedDirectories],
1243
+ status: "ready",
1244
+ revision,
1245
+ materializedAt: (/* @__PURE__ */ new Date()).toISOString(),
1246
+ files: sourceFiles,
1247
+ bytes: sourceBytes,
1248
+ items: readyItems,
1249
+ cacheMaxAge: source.cache ? source.cache.maxAge : void 0
1250
+ };
1251
+ if (completeSource) await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, ready));
1252
+ else if (existing?.configHash === configHash) {
1253
+ const scopedItems = checkpointItems(itemMetadata);
1254
+ await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, {
1255
+ ...existing,
1256
+ ownsMount,
1257
+ ownedAncestors,
1258
+ ownedDirectories: [...ownedDirectories],
1259
+ bytes: Math.max(0, (existing.bytes || 0) + persistedBytesDelta),
1260
+ files: scopedItems ? Object.keys(scopedItems).length : 0,
1261
+ items: scopedItems
1262
+ }));
1263
+ } else if (existing || source.materialize === "startup") {
1264
+ const migratedItems = checkpointItems(itemMetadata);
1265
+ await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, {
1266
+ ...ready,
1267
+ status: "updating",
1268
+ items: migratedItems,
1269
+ files: migratedItems ? Object.keys(migratedItems).length : 0,
1270
+ bytes: retainPriorItems ? Math.max(0, (existing?.bytes || 0) + persistedBytesDelta) : sourceBytes
1271
+ }));
1272
+ }
1273
+ const durationMs = Date.now() - sourceStarted;
1274
+ const resultSource = {
1275
+ ...ready,
1276
+ cacheStatus,
1277
+ counts: { ...counts },
1278
+ durationMs,
1279
+ provider: source.source.name
1280
+ };
1281
+ const reportedPaths = materializationPaths(options, paths);
1282
+ if (reportedPaths) resultSource.paths = reportedPaths;
1283
+ resultSources.push(resultSource);
1284
+ files += sourceFiles;
1285
+ bytes += sourceBytes;
1286
+ directories += directorySet.size;
1287
+ await reportMaterializationProgress(options, source, {
1288
+ bytes: sourceBytes,
1289
+ cacheStatus,
1290
+ counts: { ...counts },
1291
+ directories: directorySet.size,
1292
+ durationMs,
1293
+ files: sourceFiles,
1294
+ revision,
1295
+ status: "completed"
1296
+ });
1297
+ } catch (error) {
1298
+ const checkpointItemsMetadata = checkpointItems(itemMetadata);
1299
+ const resumesExistingSnapshot = existing?.configHash === configHash;
1300
+ const failed = {
1301
+ configHash,
1302
+ source: source.key,
1303
+ mountPath: source.mountPath,
1304
+ ownsMount,
1305
+ ownedAncestors,
1306
+ ownedDirectories: [...ownedDirectories],
1307
+ status: "error",
1308
+ revision,
1309
+ error: error instanceof Error ? error.message : String(error),
1310
+ files: resumesExistingSnapshot && checkpointItemsMetadata ? Object.keys(checkpointItemsMetadata).length : sourceFiles,
1311
+ bytes: resumesExistingSnapshot ? Math.max(0, (existing?.bytes || 0) + persistedBytesDelta) : sourceBytes,
1312
+ items: checkpointItemsMetadata,
1313
+ cacheMaxAge: source.cache ? source.cache.maxAge : void 0
1314
+ };
1315
+ const checkpoint = options.abortSignal?.aborted ? completeSource ? {
1316
+ ...failed,
1317
+ status: "updating",
1318
+ error: void 0
1319
+ } : existing?.configHash === configHash ? {
1320
+ ...existing,
1321
+ ownsMount,
1322
+ ownedAncestors,
1323
+ ownedDirectories: [...ownedDirectories],
1324
+ items: checkpointItemsMetadata
1325
+ } : source.materialize === "startup" ? {
1326
+ ...failed,
1327
+ status: "updating",
1328
+ error: void 0
1329
+ } : void 0 : failed;
1330
+ if (checkpoint && control.isCurrent()) await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, checkpoint));
1331
+ const durationMs = Date.now() - sourceStarted;
1332
+ const failedSource = {
1333
+ ...failed,
1334
+ cacheStatus,
1335
+ counts: { ...counts },
1336
+ durationMs,
1337
+ provider: source.source.name
1338
+ };
1339
+ const reportedPaths = materializationPaths(options, paths);
1340
+ if (reportedPaths) failedSource.paths = reportedPaths;
1341
+ resultSources.push(failedSource);
1342
+ await reportMaterializationProgress(options, source, {
1343
+ bytes: sourceBytes,
1344
+ cacheStatus,
1345
+ counts: { ...counts },
1346
+ durationMs,
1347
+ error: failed.error,
1348
+ files: sourceFiles,
1349
+ revision,
1350
+ status: "failed"
1351
+ });
1352
+ if (options.abortSignal?.aborted) throw error;
1353
+ }
1354
+ }
1355
+ return {
1356
+ bytes,
1357
+ directories,
1358
+ durationMs: Date.now() - started,
1359
+ files,
1360
+ path: normalizeWorkspacePath(options.path || ""),
1361
+ sources: resultSources
1362
+ };
1363
+ }
1364
+ async function readResolvedSourceFile(resolution, store, ctx, options) {
1365
+ const file = await store.readFile(resolution.workspacePath);
1366
+ if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${resolution.workspacePath}.`);
1367
+ return decodeFile(file.content, options);
1368
+ }
1369
+ async function writeMaterializedFile(store, path, file, previousContent) {
1370
+ if (file.contentStream) {
1371
+ if (store.writeFileStream) {
1372
+ let size = 0;
1373
+ const hash = createHash("sha256");
1374
+ const content = (async function* () {
1375
+ for await (const chunk of contentStreamChunks(file.contentStream)) {
1376
+ size += chunk.byteLength;
1377
+ hash.update(chunk);
1378
+ yield chunk;
1379
+ }
1380
+ })();
1381
+ const write = () => store.writeFileStream(path, {
1382
+ path: file.path,
1383
+ content,
1384
+ mediaType: file.mediaType,
1385
+ metadata: file.metadata
1386
+ });
1387
+ const written = await write();
1388
+ if (!written.digest) throw workspaceError("[vitehub] Workspace Store writeFileStream() must return a content digest.");
1389
+ return {
1390
+ digest: hash.digest("hex"),
1391
+ storeDigest: written.digest,
1392
+ size
1393
+ };
1394
+ }
1395
+ const content = await contentStreamToBytes(file.contentStream);
1396
+ await store.writeFile(path, {
1397
+ path: file.path,
1398
+ content,
1399
+ mediaType: file.mediaType,
1400
+ metadata: file.metadata
1401
+ });
1402
+ return {
1403
+ contentEqual: previousContent !== void 0 && contentEquals(previousContent, content),
1404
+ digest: await sha256(content),
1405
+ size: content.byteLength
1406
+ };
1407
+ }
1408
+ const content = file.content ?? "";
1409
+ await store.writeFile(path, {
1410
+ path: file.path,
1411
+ content,
1412
+ mediaType: file.mediaType,
1413
+ metadata: file.metadata
1414
+ });
1415
+ return {
1416
+ digest: await sha256(content),
1417
+ size: contentSize(content)
1418
+ };
1419
+ }
1420
+ async function statVirtualSourcePath(source, workspacePath, store, ctx) {
1421
+ const stored = await store.stat(workspacePath);
1422
+ if (stored) return stored;
1423
+ const keys = await source.source.getKeys(ctx);
1424
+ const sourcePath = normalizeSourcePath(source, workspacePath);
1425
+ if (!sourcePath && keys.length > 0) return {
1426
+ path: source.mountPath,
1427
+ type: "directory"
1428
+ };
1429
+ if (keys.includes(sourcePath)) return {
1430
+ path: workspacePath,
1431
+ type: "file",
1432
+ digest: readDigest(await source.source.getMeta?.(sourcePath, ctx))
1433
+ };
1434
+ if (keys.some((key) => key.startsWith(`${sourcePath}/`))) return {
1435
+ path: workspacePath,
1436
+ type: "directory"
1437
+ };
1438
+ }
1439
+ async function searchMaterializedStore(store, query) {
1440
+ const limit = query.limit ?? 100;
1441
+ const result = [];
1442
+ const entries = query.paths?.length ? (await Promise.all(query.paths.map(async (path) => {
1443
+ const [stat, nested] = await Promise.all([store.stat(path), store.glob(`${path}/**/*`)]);
1444
+ return [...stat?.type === "file" ? [stat] : [], ...nested];
1445
+ }))).flat() : await store.glob("**/*");
1446
+ for (const entry of entries) {
1447
+ if (entry.type !== "file") continue;
1448
+ const file = await store.readFile(entry.path);
1449
+ if (!file) continue;
1450
+ const text = isWorkspaceBytes(file.content) ? new TextDecoder().decode(file.content) : file.content;
1451
+ result.push(...searchText(entry.path, text, {
1452
+ ...query,
1453
+ limit: limit - result.length
1454
+ }));
1455
+ if (result.length >= limit) break;
1456
+ }
1457
+ return result.slice(0, limit);
1458
+ }
1459
+ function createLazyMaterializedMetadata(resolution, item, upstreamMeta) {
1460
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1461
+ const metadata = {
1462
+ source: resolution.sourceKey,
1463
+ sourcePath: resolution.sourcePath,
1464
+ materializedAt: now,
1465
+ validatedAt: resolution.validate === "request" ? now : void 0,
1466
+ etag: readStringMeta(upstreamMeta, "etag"),
1467
+ sha: readStringMeta(upstreamMeta, "sha"),
1468
+ digest: readStringMeta(upstreamMeta, "digest") || readStringMeta(item.metadata, "digest"),
1469
+ ref: readStringMeta(upstreamMeta, "ref")
1470
+ };
1471
+ for (const key of [
1472
+ "validatedAt",
1473
+ "etag",
1474
+ "sha",
1475
+ "digest",
1476
+ "ref"
1477
+ ]) if (metadata[key] === void 0) delete metadata[key];
1478
+ return metadata;
1479
+ }
1480
+ function hasSourceMetaChanged(current, upstreamMeta) {
1481
+ const next = {
1482
+ etag: readStringMeta(upstreamMeta, "etag"),
1483
+ sha: readStringMeta(upstreamMeta, "sha"),
1484
+ digest: readStringMeta(upstreamMeta, "digest"),
1485
+ ref: readStringMeta(upstreamMeta, "ref")
1486
+ };
1487
+ return current.etag !== next.etag || current.sha !== next.sha || current.digest !== next.digest || current.ref !== next.ref;
1488
+ }
1489
+ function normalizeSourcePath(source, workspacePath) {
1490
+ if (workspacePath === source.mountPath) return "";
1491
+ return source.mountPath && workspacePath.startsWith(`${source.mountPath}/`) ? normalizeWorkspacePath(workspacePath.slice(source.mountPath.length + 1)) : normalizeWorkspacePath(workspacePath);
1492
+ }
1493
+ function readStringMeta(meta, key) {
1494
+ const value = meta?.[key];
1495
+ return Object.prototype.toString.call(value) === "[object String]" ? String(value) : void 0;
1496
+ }
1497
+ function readDigest(meta) {
1498
+ return readStringMeta(meta, "digest") || readStringMeta(meta, "sha");
1499
+ }
1500
+ //#endregion
1501
+ //#region src/storage/metadata-target.ts
1502
+ /** Internal capability used only by Source Sync through wrapped writable facades. */
1503
+ const workspaceInternalMetadataCapability = Symbol("vitehub.workspace.internalMetadata");
1504
+ const metadataTargetResolvers = /* @__PURE__ */ new WeakMap();
1505
+ const metadataTargetsByStore = /* @__PURE__ */ new WeakMap();
1506
+ const metadataSetters = /* @__PURE__ */ new WeakMap();
1507
+ const facadeMetadataTargets = /* @__PURE__ */ new WeakMap();
1508
+ const privateMetadataTargets = /* @__PURE__ */ new WeakMap();
1509
+ function createWorkspaceMetadataTarget(store, workspaceName) {
1510
+ const targets = metadataTargetsByStore.get(store) ?? /* @__PURE__ */ new Map();
1511
+ const existing = targets.get(workspaceName);
1512
+ if (existing) return existing;
1513
+ const setMeta = store.setMeta?.bind(store);
1514
+ const target = {
1515
+ workspaceName,
1516
+ readFile: store.readFile?.bind(store),
1517
+ writeFile: store.writeFile?.bind(store),
1518
+ mkdir: store.mkdir?.bind(store),
1519
+ rm: store.rm?.bind(store),
1520
+ getMeta: store.getMeta?.bind(store),
1521
+ list: store.list?.bind(store)
1522
+ };
1523
+ if (setMeta) metadataSetters.set(target, setMeta);
1524
+ const publicTarget = {
1525
+ workspaceName,
1526
+ readFile: target.readFile,
1527
+ getMeta: target.getMeta,
1528
+ list: target.list
1529
+ };
1530
+ privateMetadataTargets.set(publicTarget, target);
1531
+ forwardWorkspaceStoreTarget(store, target);
1532
+ forwardWorkspaceStoreTarget(store, publicTarget);
1533
+ targets.set(workspaceName, publicTarget);
1534
+ metadataTargetsByStore.set(store, targets);
1535
+ return publicTarget;
1536
+ }
1537
+ /** Writes internal metadata without exposing the privileged setter on a facade. */
1538
+ async function setWorkspaceMetadata(target, key, value) {
1539
+ const setter = metadataSetters.get(target) || metadataSetters.get(privateMetadataTargets.get(target) ?? target);
1540
+ if (!setter) return false;
1541
+ await setter(key, value, workspaceInternalMetadataCapability);
1542
+ return true;
1543
+ }
1544
+ function attachWorkspaceMetadataTarget(carrier, resolve) {
1545
+ metadataTargetResolvers.set(carrier, resolve);
1546
+ if ("fs" in carrier) facadeMetadataTargets.set(carrier.fs, async () => await resolve());
1547
+ }
1548
+ function forwardWorkspaceMetadataTarget(source, target) {
1549
+ const resolve = metadataTargetResolver(source);
1550
+ if (resolve) attachWorkspaceMetadataTarget(target, resolve);
1551
+ }
1552
+ async function resolveWorkspaceMetadataTarget(source) {
1553
+ return await metadataTargetResolver(source)?.();
1554
+ }
1555
+ /**
1556
+ * Attaches a read-only metadata view of `source` to `target`.
1557
+ * The view has the Workspace name, `getMeta`, `list`, and the Store target. It never has Store writes.
1558
+ * `filterEntries` limits the listed entries, for example to an access scope.
1559
+ * Internal: `@vite-hub/agent` uses this for its Workspace facades.
1560
+ */
1561
+ function forwardWorkspaceMetadataView(source, target, filterEntries) {
1562
+ const resolve = metadataTargetResolver(source);
1563
+ if (!resolve) return;
1564
+ metadataTargetResolvers.set(target, async () => {
1565
+ const metadata = await resolve();
1566
+ if (!metadata) return;
1567
+ const list = metadata.list?.bind(metadata);
1568
+ const view = {
1569
+ workspaceName: metadata.workspaceName,
1570
+ getMeta: metadata.getMeta?.bind(metadata),
1571
+ list: list ? async (path, options) => {
1572
+ const entries = await list(path, options);
1573
+ return filterEntries ? filterEntries(entries) : entries;
1574
+ } : void 0
1575
+ };
1576
+ forwardWorkspaceStoreTarget(metadata, view);
1577
+ return view;
1578
+ });
1579
+ }
1580
+ function metadataTargetResolver(source) {
1581
+ if (source === null || !(hasRuntimeType(source, "object") || hasRuntimeType(source, "function"))) return void 0;
1582
+ return metadataTargetResolvers.get(source) ?? ("fs" in source && source.fs !== null && hasRuntimeType(source.fs, "object") ? facadeMetadataTargets.get(source.fs) : void 0);
1583
+ }
1584
+ function resolveWorkspaceMetadataMutationTarget(target) {
1585
+ return privateMetadataTargets.get(target) ?? target;
1586
+ }
1587
+ //#endregion
1588
+ export { removeWorkspaceOwnedFile as A, withWorkspaceStoreMutation as C, readWorkspaceFileOwner as D, normalizeSourceFileMetadata as E, registerWorkspaceStoreAlias as M, workspaceStoreIdentity as N, recordWorkspaceFileOwner as O, sourceMountOwnsPath as S, normalizeMetadataValue as T, reconcileRemovedStartupSources as _, resolveWorkspaceMetadataMutationTarget as a, statVirtualSourcePath as b, workspaceInternalMetadataCapability as c, invalidateSourceSnapshot as d, materializeWorkspaceSources as f, readSourceSnapshotPaths as g, readResolvedSourceFile as h, forwardWorkspaceMetadataView as i, withWorkspaceFileCheckpoint as j, removeWorkspaceFileOwner as k, hasCurrentSourceSnapshot as l, readCurrentSourceSnapshot as m, createWorkspaceMetadataTarget as n, resolveWorkspaceMetadataTarget as o, materializesCompleteSource as p, forwardWorkspaceMetadataTarget as r, setWorkspaceMetadata as s, attachWorkspaceMetadataTarget as t, hasFreshSourceSnapshot as u, searchMaterializedStore as v, normalizeSourceItemPath as w, createWorkspaceSourceMountAuthority as x, sourceSnapshotOwnsAnyPath as y };