@vite-hub/workspace 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -58
  3. package/dist/{ai-nmHdzjCM.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  4. package/dist/{ai-Ce3PtWFW.js → ai-BZyLwULx.js} +147 -66
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-DfBV5kmw.js} +3 -2
  8. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  9. package/dist/blob-database.d.ts +521 -0
  10. package/dist/blob-database.js +601 -0
  11. package/dist/cloudflare.d.ts +5 -6
  12. package/dist/cloudflare.js +1 -1
  13. package/dist/config-B7dmzDX3.js +1112 -0
  14. package/dist/{config-3I1BnsdO.d.ts → config-DLKdaFWN.d.ts} +1 -2
  15. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  16. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  17. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  18. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  19. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  20. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  21. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  22. package/dist/file-C0_aPWSS.js +26 -0
  23. package/dist/file-metadata-CxDy-E2H.js +58 -0
  24. package/dist/{files-QRV55OCx.js → files-C7Px8uaC.js} +21 -10
  25. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  26. package/dist/{github-CfA5vpJ5.js → github-CPxHtFB7.js} +36 -34
  27. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  28. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  29. package/dist/glob--XcLlcml.js +22 -0
  30. package/dist/glob--kNYDbfU.js +30 -0
  31. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  32. package/dist/host-CFnrTXTK.js +1086 -0
  33. package/dist/{hosted-C1-tTTTf.js → hosted-acMA5XyL.js} +216 -43
  34. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  35. package/dist/hosted-vercel-blob.d.ts +5 -6
  36. package/dist/hosted-vercel-blob.js +1 -1
  37. package/dist/hosted.d.ts +6 -7
  38. package/dist/hosted.js +1 -1
  39. package/dist/index.d.ts +76 -64
  40. package/dist/index.js +162 -457
  41. package/dist/inspect-BoObD2cJ.js +167 -0
  42. package/dist/internal/path.d.ts +2 -0
  43. package/dist/internal/path.js +2 -0
  44. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  45. package/dist/loader.d.ts +5 -6
  46. package/dist/loader.js +3 -2
  47. package/dist/mcp-resources-BREFCmtn.js +39 -0
  48. package/dist/memory-BbwOqDXl.js +248 -0
  49. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  50. package/dist/mountx.d.ts +4 -6
  51. package/dist/mountx.js +10 -8
  52. package/dist/nitro.d.ts +1 -1
  53. package/dist/nitro.js +1 -1
  54. package/dist/nuxt.d.ts +13 -12
  55. package/dist/nuxt.js +10 -8
  56. package/dist/operations-BcpWr41m.js +159 -0
  57. package/dist/operations-CGqY1XeG.js +965 -0
  58. package/dist/operations-DnOwKsJT.d.ts +136 -0
  59. package/dist/operations.d.ts +53 -0
  60. package/dist/operations.js +2 -0
  61. package/dist/{path-CNI6wKIU.js → path-CNAwN7pw.js} +34 -35
  62. package/dist/path-DrSIenjj.js +59 -0
  63. package/dist/path-zHxQUbqa.d.ts +9 -0
  64. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  65. package/dist/provider-kXjfli9u.js +1457 -0
  66. package/dist/providers/github/store.d.ts +3 -5
  67. package/dist/providers/github/store.js +1 -1
  68. package/dist/registry-Bp-8UUfG.js +129 -0
  69. package/dist/{registry-BIQVCBWI.d.ts → registry-Cg1TJVVZ.d.ts} +3 -4
  70. package/dist/{request-execution-u9mgUXKX.js → request-execution-Dk9rY-Yh.js} +24 -20
  71. package/dist/rolldown-runtime-B4iAMlE-.js +35 -0
  72. package/dist/runtime/assets.d.ts +3 -5
  73. package/dist/runtime/assets.js +9 -6
  74. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  75. package/dist/runtime/empty-registry.d.ts +1 -2
  76. package/dist/runtime/state.d.ts +4 -4
  77. package/dist/runtime/state.js +10 -7
  78. package/dist/runtime/workspace.d.ts +1 -1
  79. package/dist/runtime/workspace.js +1 -1
  80. package/dist/runtime.d.ts +84 -15
  81. package/dist/runtime.js +561 -108
  82. package/dist/{search-C4REyHj9.js → search-CrTmXj5h.js} +10 -9
  83. package/dist/server-BNQ-Nbjj.js +290 -0
  84. package/dist/server.d.ts +22 -34
  85. package/dist/server.js +2 -355
  86. package/dist/shared-DalXdP0i.js +2158 -0
  87. package/dist/source-metadata.d.ts +7 -1
  88. package/dist/source-metadata.js +34 -2
  89. package/dist/{state-TTqa3x3Y.d.ts → state-B8zbLi5t.d.ts} +14 -13
  90. package/dist/store-CXgmu-uw.js +1729 -0
  91. package/dist/{sync-DiuDmSGk.js → sync-CN6ec-5M.js} +62 -41
  92. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  93. package/dist/test.d.ts +1 -1
  94. package/dist/test.js +1 -1
  95. package/dist/token-CO62GglH.js +61 -0
  96. package/dist/{types-60Yn149G.d.ts → types-DeK9GIxy.d.ts} +348 -49
  97. package/dist/{use-CsV3oIxH.js → use-BQj7nSz6.js} +200 -45
  98. package/dist/{use-CUFSnFCS.d.ts → use-DhwhbAVV.d.ts} +34 -12
  99. package/dist/utils-Blrh4N2n.js +545 -0
  100. package/dist/vite-BEvgU2GY.js +20909 -0
  101. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  102. package/dist/vite.d.ts +2 -50
  103. package/dist/vite.js +2 -2
  104. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  105. package/dist/workspace-6pxkOuxr.js +1286 -0
  106. package/dist/workspace-BWJQBK1u.d.ts +7 -0
  107. package/package.json +90 -59
  108. package/dist/chunk-8H4AJuhK.js +0 -14
  109. package/dist/collections/client.d.ts +0 -39
  110. package/dist/collections/client.js +0 -137
  111. package/dist/collections.d.ts +0 -59
  112. package/dist/collections.js +0 -159
  113. package/dist/config-CDoyls2X.js +0 -30
  114. package/dist/config-CZLO0m9h.js +0 -7811
  115. package/dist/file-CHfsZpso.js +0 -23
  116. package/dist/glob-D0vD_wRY.js +0 -17
  117. package/dist/host-CAnbugpI.js +0 -370
  118. package/dist/hosted-vercel-blob-CWBILDVo.js +0 -257
  119. package/dist/lifecycle-BYoa9hVb.js +0 -176
  120. package/dist/provider-C3_elpEh.js +0 -599
  121. package/dist/publish.d.ts +0 -35
  122. package/dist/publish.js +0 -112
  123. package/dist/registry-CqyDTW9Y.js +0 -74
  124. package/dist/runtime-options-BsPSv5O7.js +0 -13
  125. package/dist/shared-jfogBrd5.js +0 -273
  126. package/dist/store-Bs1SLh55.js +0 -414
  127. package/dist/vite-tbfDxtlu.js +0 -2191
  128. package/dist/workspace-66SKyiec.d.ts +0 -6
  129. package/dist/workspace-C4k92Ow8.js +0 -1460
package/dist/runtime.js CHANGED
@@ -1,13 +1,22 @@
1
- import { c as normalizeWorkspacePath, p as workspaceError } from "./path-CNI6wKIU.js";
2
- import { a as copyWorkspacePath, i as appendWorkspaceFile, n as getWorkspaceDependencyRuntimeLoaders, r as setWorkspaceDependencyRuntimeLoaders, t as createWorkspaceTools } from "./ai-Ce3PtWFW.js";
3
- import { a as normalizeWorkspaceSources, f as getWorkspaceSourceRequestDescriptor, g as markLiveWorkspaceSource, h as workspaceSourceRequestDescriptorPath, i as normalizeWorkspaceSourceMetadata, l as workspaceSourceGrantPaths, m as isWorkspaceSourceRequestOnly, o as normalizeWorkspaceSourcesMetadata, r as normalizeWorkspaceSource, t as copyWorkspaceSourceMetadata } from "./config-CZLO0m9h.js";
4
- import { n as createWorkspaceSourceRequestExecution, r as getWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-u9mgUXKX.js";
5
- import { c as getWorkspaceHostedStoreLoader, d as setWorkspaceRuntimeConfig, l as setWorkspaceHostedStoreLoader, s as createMemoryWorkspaceStore, u as getWorkspaceRuntimeConfig } from "./provider-C3_elpEh.js";
6
- import { t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
7
- import { d as createBasicWorkspaceSession, l as createWorkspaceWritePolicy, n as resetWorkspaceStoreCache, r as createWorkspaceSourceView, s as resolveWorkspacePath } from "./workspace-C4k92Ow8.js";
8
- import { n as registerWorkspace, r as resolveRegisteredWorkspaceDefinition } from "./registry-CqyDTW9Y.js";
9
- import { t as useWorkspace } from "./use-CsV3oIxH.js";
10
- import { setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeRegistry } from "./runtime/state.js";
1
+ import { s as workspaceError } from "./path-DrSIenjj.js";
2
+ import { l as normalizeWorkspacePath } from "./path-CNAwN7pw.js";
3
+ import { n as resolveWorkspaceStoreTarget, r as workspaceStoreTarget, t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
+ import { a as copyWorkspacePath, i as appendWorkspaceFile, n as getWorkspaceDependencyRuntimeLoaders, r as setWorkspaceDependencyRuntimeLoaders, t as createWorkspaceTools } from "./ai-BZyLwULx.js";
5
+ import { _ as isWorkspaceSourceRequestOnly, a as normalizeWorkspaceSources, b as markLiveWorkspaceSource, f as prepareWorkspaceSource, h as getWorkspaceSourceRequestDescriptor, i as normalizeWorkspaceSourceMetadata, l as workspaceSourceGrantPaths, o as normalizeWorkspaceSourcesMetadata, r as normalizeWorkspaceSource, t as copyWorkspaceSourceMetadata, u as ownSourceOption, v as workspaceSourceRequestDescriptorPath } from "./config-B7dmzDX3.js";
6
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
7
+ import { i as workspaceSourceRequestMatches, n as createWorkspaceSourceRequestExecution, r as getWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-Dk9rY-Yh.js";
8
+ import { t as createMemoryWorkspaceStore } from "./memory-BbwOqDXl.js";
9
+ import { a as createWorkspaceHistoryReader, c as forwardWorkspaceHistoryMerge, g as registerWorkspacePlugin, i as createWorkspaceHistory, m as createWorkspaceWritePolicy, s as forwardWorkspaceHistoryFiles } from "./utils-Blrh4N2n.js";
10
+ import { d as getWorkspaceRuntimeConfig, f as setWorkspaceRuntimeConfig, l as getWorkspaceHostedStoreLoader, u as setWorkspaceHostedStoreLoader } from "./provider-kXjfli9u.js";
11
+ import { a as isInternalWorkspaceMetaKey, c as isWorkspaceSourceSyncMetaKey, m as createBasicWorkspaceSession, o as createWorkspaceSourceView, p as resolveWorkspacePath, r as resetWorkspaceStoreCache } from "./workspace-6pxkOuxr.js";
12
+ import { M as registerWorkspaceStoreAlias, a as resolveWorkspaceMetadataMutationTarget, i as forwardWorkspaceMetadataView, n as createWorkspaceMetadataTarget, o as resolveWorkspaceMetadataTarget, r as forwardWorkspaceMetadataTarget, s as setWorkspaceMetadata, t as attachWorkspaceMetadataTarget } from "./metadata-target-DZEZQGHA.js";
13
+ import { n as registerWorkspace, r as resolveRegisteredWorkspaceDefinition } from "./registry-Bp-8UUfG.js";
14
+ import { t as useWorkspace } from "./use-BQj7nSz6.js";
15
+ import { invalidateWorkspaceStore, setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeRegistry } from "./runtime/state.js";
16
+ import { join, resolve } from "node:path";
17
+ import { randomUUID } from "node:crypto";
18
+ import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
19
+ import { lstat, readdir, rename, rm } from "node:fs/promises";
11
20
  //#region src/sources/resolution.ts
12
21
  function hasWorkspaceSourceResolvers(definition) {
13
22
  return normalizeWorkspaceSources(definition?.sources).some((source) => typeof source.source.resolve === "function");
@@ -15,6 +24,71 @@ function hasWorkspaceSourceResolvers(definition) {
15
24
  function isWritableWorkspaceFacade(workspace) {
16
25
  return typeof workspace.fs.writeFile === "function";
17
26
  }
27
+ const sourceBindingLineage = /* @__PURE__ */ new WeakMap();
28
+ function sameWorkspaceSourceBinding(key, left, right) {
29
+ if (left === right) return true;
30
+ if (!left || !right) return false;
31
+ if (typeof left !== "object" || typeof right !== "object") return false;
32
+ if ((sourceBindingLineage.get(left) ?? left) !== (sourceBindingLineage.get(right) ?? right)) return false;
33
+ const leftBinding = normalizeWorkspaceSource(key, left);
34
+ const rightBinding = normalizeWorkspaceSource(key, right);
35
+ if (leftBinding.source.fingerprint === void 0 || rightBinding.source.fingerprint === void 0) return false;
36
+ return sameWorkspaceSourceValue({
37
+ cache: leftBinding.cache,
38
+ materialize: leftBinding.materialize,
39
+ mountPath: leftBinding.mountPath,
40
+ source: leftBinding.source.fingerprint,
41
+ sync: leftBinding.sync
42
+ }, {
43
+ cache: rightBinding.cache,
44
+ materialize: rightBinding.materialize,
45
+ mountPath: rightBinding.mountPath,
46
+ source: rightBinding.source.fingerprint,
47
+ sync: rightBinding.sync
48
+ });
49
+ }
50
+ function sameWorkspaceSourceValue(left, right, ancestors = /* @__PURE__ */ new Set()) {
51
+ try {
52
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return Object.is(left, right);
53
+ const leftProxy = isWorkspaceSourceProxy(left);
54
+ const rightProxy = isWorkspaceSourceProxy(right);
55
+ if (leftProxy !== false || rightProxy !== false) return false;
56
+ const prototype = Object.getPrototypeOf(left);
57
+ if (Array.isArray(left) !== Array.isArray(right) || prototype !== Object.getPrototypeOf(right) || prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null || "toJSON" in left || "toJSON" in right || ancestors.has(left) || ancestors.has(right)) return false;
58
+ const leftKeys = Reflect.ownKeys(left);
59
+ const rightKeys = Reflect.ownKeys(right);
60
+ if (leftKeys.length !== rightKeys.length) return false;
61
+ const leftProperties = leftKeys.map((key) => Object.getOwnPropertyDescriptor(left, key));
62
+ const rightProperties = rightKeys.map((key) => Object.getOwnPropertyDescriptor(right, key));
63
+ if (leftProperties.some((property) => !property || !("value" in property)) || rightProperties.some((property) => !property || !("value" in property))) return false;
64
+ ancestors.add(left);
65
+ ancestors.add(right);
66
+ try {
67
+ return leftKeys.every((key, index) => {
68
+ if (key !== rightKeys[index]) return false;
69
+ const leftProperty = leftProperties[index];
70
+ const rightProperty = rightProperties[index];
71
+ return !!leftProperty && !!rightProperty && "value" in leftProperty && "value" in rightProperty && leftProperty.enumerable === rightProperty.enumerable && sameWorkspaceSourceValue(leftProperty.value, rightProperty.value, ancestors);
72
+ });
73
+ } finally {
74
+ ancestors.delete(left);
75
+ ancestors.delete(right);
76
+ }
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+ const isWorkspaceSourceProxy = (() => {
82
+ try {
83
+ const process = globalThis.process;
84
+ const getBuiltinModule = process?.getBuiltinModule;
85
+ if (typeof getBuiltinModule !== "function") return (_value) => void 0;
86
+ const util = getBuiltinModule.call(process, "util");
87
+ return typeof util?.types?.isProxy === "function" ? util.types.isProxy : (_value) => void 0;
88
+ } catch {
89
+ return (_value) => void 0;
90
+ }
91
+ })();
18
92
  function workspaceSessionStarter(workspace) {
19
93
  return typeof workspace.startSession === "function" ? workspace : void 0;
20
94
  }
@@ -28,35 +102,43 @@ function writeOperations(options) {
28
102
  writeFile: options?.writeFile !== false
29
103
  };
30
104
  }
31
- function createOverlaySourceStore(workspace, fallback) {
105
+ function createOverlaySourceStore(workspace, fallback, backingMetadataTarget) {
32
106
  const memory = createMemoryWorkspaceStore();
107
+ const tombstones = /* @__PURE__ */ new Set();
108
+ function isTombstoned(path) {
109
+ return [...tombstones].some((tombstone) => path === tombstone || path.startsWith(`${tombstone}/`));
110
+ }
111
+ function restorePath(path) {
112
+ for (const tombstone of tombstones) if (path === tombstone || path.startsWith(`${tombstone}/`)) tombstones.delete(tombstone);
113
+ }
33
114
  async function readBaseFile(path) {
34
- if (!fallback(path)) return;
115
+ if (!fallback(path) || isTombstoned(path)) return;
35
116
  if (!await workspace.fs.exists(path)) return;
36
117
  const stat = await workspace.fs.stat(path).catch(() => void 0);
37
118
  if (stat?.type === "directory") return;
38
119
  return {
39
120
  content: await workspace.fs.readFile(path, { encoding: "binary" }),
40
121
  mediaType: stat?.mediaType,
122
+ metadata: stat?.metadata,
41
123
  path
42
124
  };
43
125
  }
44
126
  async function baseEntries(path = "", options) {
45
127
  try {
46
- return (await workspace.fs.list(path, options)).filter((entry) => fallback(entry.path));
128
+ return (await workspace.fs.list(path, options)).filter((entry) => fallback(entry.path) && !isTombstoned(entry.path));
47
129
  } catch {
48
130
  return [];
49
131
  }
50
132
  }
51
133
  async function baseGlob(pattern, options) {
52
134
  try {
53
- return (await workspace.fs.glob(pattern, options)).filter((entry) => fallback(entry.path));
135
+ return (await workspace.fs.glob(pattern, options)).filter((entry) => fallback(entry.path) && !isTombstoned(entry.path));
54
136
  } catch {
55
137
  return [];
56
138
  }
57
139
  }
58
140
  async function baseStat(path) {
59
- if (!fallback(path)) return;
141
+ if (!fallback(path) || isTombstoned(path)) return;
60
142
  try {
61
143
  return await workspace.fs.stat(path);
62
144
  } catch {
@@ -64,10 +146,13 @@ function createOverlaySourceStore(workspace, fallback) {
64
146
  }
65
147
  }
66
148
  return {
149
+ [workspaceStoreTarget]: async () => await resolveWorkspaceStoreTarget(workspace) ?? { provider: "memory" },
150
+ isTombstoned,
67
151
  async readFile(path) {
68
152
  return await memory.readFile(path) || await readBaseFile(path);
69
153
  },
70
154
  async writeFile(path, file) {
155
+ restorePath(path);
71
156
  await memory.writeFile(path, file);
72
157
  },
73
158
  async list(path, options) {
@@ -80,10 +165,14 @@ function createOverlaySourceStore(workspace, fallback) {
80
165
  return await memory.stat(path) || await baseStat(path);
81
166
  },
82
167
  async mkdir(path, options) {
168
+ restorePath(path);
83
169
  await memory.mkdir(path, options);
84
170
  },
85
171
  async rm(path, options) {
172
+ const removedBaseEntries = options?.recursive ? await baseEntries(path, { recursive: true }) : [];
86
173
  await memory.rm(path, options);
174
+ tombstones.add(path);
175
+ for (const entry of removedBaseEntries) tombstones.add(entry.path);
87
176
  },
88
177
  async snapshot(options) {
89
178
  return await memory.snapshot(options);
@@ -92,24 +181,41 @@ function createOverlaySourceStore(workspace, fallback) {
92
181
  return await memory.diff(options);
93
182
  },
94
183
  async getMeta(key) {
95
- return await memory.getMeta?.(key);
184
+ const internalMetadata = await resolveWorkspaceMetadataTarget(workspace);
185
+ return await memory.getMeta?.(key) ?? await internalMetadata?.getMeta?.(key) ?? await workspace.getMeta?.(key);
96
186
  },
97
187
  async setMeta(key, value) {
188
+ if (isInternalWorkspaceMetaKey(key) && isWorkspaceSourceSyncMetaKey(key)) {
189
+ const mutationTarget = backingMetadataTarget ? resolveWorkspaceMetadataMutationTarget(backingMetadataTarget) : void 0;
190
+ if (mutationTarget && await setWorkspaceMetadata(mutationTarget, key, value)) return;
191
+ }
98
192
  await memory.setMeta?.(key, value);
99
193
  }
100
194
  };
101
195
  }
102
- function createWritableFacadeStore(workspace) {
196
+ const sourceSyncStores = /* @__PURE__ */ new WeakMap();
197
+ /** Preserve internal Source Sync routing when wrapping a writable facade. */
198
+ function forwardWorkspaceFacade(source, target) {
199
+ forwardWorkspaceMetadataTarget(source, target);
200
+ const syncStore = sourceSyncStores.get(source.fs);
201
+ if (syncStore) sourceSyncStores.set(target.fs, syncStore);
202
+ }
203
+ function createWritableFacadeStore(workspace, sourceSync) {
204
+ const backingSyncStore = sourceSync ? sourceSyncStores.get(workspace.fs)?.(sourceSync) : void 0;
205
+ if (backingSyncStore) return backingSyncStore;
103
206
  const meta = /* @__PURE__ */ new Map();
104
207
  const metadata = workspace;
105
208
  const store = {
106
209
  async readFile(path) {
210
+ const target = sourceSync ? resolveWorkspaceMetadataMutationTarget(await resolveWorkspaceMetadataTarget(workspace) ?? {}) : void 0;
211
+ if (target?.readFile) return await target.readFile(path);
107
212
  try {
108
213
  const stat = await workspace.fs.stat(path);
109
214
  if (stat.type === "directory") return;
110
215
  return {
111
216
  content: await workspace.fs.readFile(path, { encoding: "binary" }),
112
217
  mediaType: stat.mediaType,
218
+ metadata: stat.metadata,
113
219
  path
114
220
  };
115
221
  } catch {
@@ -117,7 +223,12 @@ function createWritableFacadeStore(workspace) {
117
223
  }
118
224
  },
119
225
  async writeFile(path, file) {
120
- await workspace.fs.writeFile(path, file.content, { mediaType: file.mediaType });
226
+ const target = sourceSync ? resolveWorkspaceMetadataMutationTarget(await resolveWorkspaceMetadataTarget(workspace) ?? {}) : void 0;
227
+ if (target?.writeFile) return await target.writeFile(path, file);
228
+ await workspace.fs.writeFile(path, file.content, {
229
+ mediaType: file.mediaType,
230
+ metadata: file.metadata
231
+ });
121
232
  },
122
233
  async list(path, options) {
123
234
  return await workspace.fs.list(path, options);
@@ -133,14 +244,21 @@ function createWritableFacadeStore(workspace) {
133
244
  }
134
245
  },
135
246
  async mkdir(path, options) {
247
+ const target = sourceSync ? resolveWorkspaceMetadataMutationTarget(await resolveWorkspaceMetadataTarget(workspace) ?? {}) : void 0;
248
+ if (target?.mkdir) return await target.mkdir(path, options);
136
249
  await workspace.fs.mkdir(path, options);
137
250
  },
138
251
  async rm(path, options) {
252
+ const target = sourceSync ? resolveWorkspaceMetadataMutationTarget(await resolveWorkspaceMetadataTarget(workspace) ?? {}) : void 0;
253
+ if (target?.rm) return await target.rm(path, options);
139
254
  await workspace.fs.rm(path, options);
140
255
  },
141
256
  async snapshot(options) {
142
257
  return await workspace.snapshot(options);
143
258
  },
259
+ async rebase(options) {
260
+ await workspace.history.rebase(options);
261
+ },
144
262
  async diff(options) {
145
263
  return await workspace.diff(options);
146
264
  },
@@ -149,7 +267,12 @@ function createWritableFacadeStore(workspace) {
149
267
  return meta.get(key);
150
268
  },
151
269
  async setMeta(key, value) {
270
+ const target = sourceSync ? resolveWorkspaceMetadataMutationTarget(await resolveWorkspaceMetadataTarget(workspace) ?? {}) : void 0;
271
+ if (target) {
272
+ if (await setWorkspaceMetadata(target, key, value)) return;
273
+ }
152
274
  if (metadata.setMeta) {
275
+ if (isInternalWorkspaceMetaKey(key)) throw workspaceError("[vitehub] Source Sync cannot write internal metadata without a private metadata target.");
153
276
  await metadata.setMeta(key, value);
154
277
  return;
155
278
  }
@@ -162,7 +285,7 @@ function createWritableFacadeStore(workspace) {
162
285
  async function startOverlayWorkspaceSession(_definition, workspace, options) {
163
286
  const host = options?.host;
164
287
  if (host) {
165
- const { createHostedWorkspaceSession } = await import("./host-CAnbugpI.js");
288
+ const { createHostedWorkspaceSession } = await import("./host-CFnrTXTK.js").then((n) => n.n);
166
289
  return await createHostedWorkspaceSession(workspace, {
167
290
  ...options,
168
291
  host
@@ -172,7 +295,7 @@ async function startOverlayWorkspaceSession(_definition, workspace, options) {
172
295
  }
173
296
  async function resolveWorkspaceSources(definition, options) {
174
297
  if (!hasWorkspaceSourceResolvers(definition) && !options.selectedWorkspaceScope) return definition;
175
- const sources = {};
298
+ const sources = Object.create(null);
176
299
  for (const [key, source] of Object.entries(definition.sources || {})) {
177
300
  const resolved = await resolveWorkspaceSource(definition, key, source, options);
178
301
  if (resolved) sources[key] = resolved;
@@ -185,48 +308,58 @@ async function resolveWorkspaceSources(definition, options) {
185
308
  async function createWorkspaceSourceResolutionFacade(workspace, definition, options) {
186
309
  const resolvedDefinition = await resolveWorkspaceSources(definition, options);
187
310
  const sourceRequestExecution = createWorkspaceSourceRequestExecution(resolvedDefinition, { selectedWorkspaceScope: options.selectedWorkspaceScope }) ?? getWorkspaceSourceRequestExecution(workspace.fs);
188
- if (!options.overlay && resolvedDefinition === definition && !sourceRequestExecution) return {
311
+ if (!options.overlay && resolvedDefinition === definition && !sourceRequestExecution && (!options.selectedWorkspaceScope || options.selectedWorkspaceScope.all)) return {
189
312
  definition,
190
313
  workspace
191
314
  };
192
315
  const selectedWorkspaceScope = options.selectedWorkspaceScope;
193
- const sourceView = createWorkspaceSourceView(createScopedSourceViewDefinition(resolvedDefinition, selectedWorkspaceScope), createOverlaySourceStore(workspace, (path) => !isLazySourcePath(resolvedDefinition, path)));
316
+ const sourceViewDefinition = createScopedSourceViewDefinition(resolvedDefinition, selectedWorkspaceScope);
317
+ const overlayStore = createOverlaySourceStore(workspace, (path) => !isLazySourcePath(resolvedDefinition, path) || selectedScopeCanSee(selectedWorkspaceScope, path) && isUnchangedStartupSourcePath(definition, resolvedDefinition, path), await resolveWorkspaceMetadataTarget(workspace));
318
+ const sourceView = createWorkspaceSourceView(sourceViewDefinition, overlayStore, { reuseStartupSnapshots: true });
319
+ function requireCompleteHistory() {
320
+ if (selectedWorkspaceScope && !selectedWorkspaceScope.all) throw workspaceErrorDiagnostics.WORKSPACE_R0069({ message: "[vitehub] Retained folder history requires access to the complete Workspace. A selected path or Source scope cannot inspect or replace its full history." });
321
+ return workspace.history;
322
+ }
323
+ const history = createWorkspaceHistoryReader(workspace.history, !selectedWorkspaceScope || selectedWorkspaceScope.all);
194
324
  const materializeSources = async (options = {}) => await sourceView.materializeSources(options);
325
+ const canUseBase = (path) => !overlayStore.isTombstoned(normalizeWorkspacePath(path));
195
326
  let readWorkspace;
196
327
  const fs = attachWorkspaceSourceRequestExecution({
197
328
  async readFile(path, options) {
198
329
  if (isSourcePath(resolvedDefinition, path)) return await sourceView.readFile(path, options);
199
330
  if (selectedScopeCanRead(selectedWorkspaceScope, path) && await sourceViewHasPath(resolvedDefinition, sourceView, path)) return await sourceView.readFile(path, options);
200
- return await workspace.fs.readFile(path, options);
331
+ if (selectedScopeCanRead(selectedWorkspaceScope, path) && canUseBase(path)) return await workspace.fs.readFile(path, options);
332
+ return await sourceView.readFile(path, options);
201
333
  },
202
334
  async stat(path) {
203
335
  if (isSourcePath(resolvedDefinition, path)) return await sourceView.stat(path);
204
336
  if (selectedScopeCanSee(selectedWorkspaceScope, path) && await sourceViewHasPath(resolvedDefinition, sourceView, path)) return await sourceView.stat(path);
205
- return await workspace.fs.stat(path);
337
+ if (selectedScopeCanSee(selectedWorkspaceScope, path) && canUseBase(path)) return await workspace.fs.stat(path);
338
+ return await sourceView.stat(path);
206
339
  },
207
340
  async exists(path) {
208
341
  if (isSourcePath(resolvedDefinition, path)) return await sourceView.exists(path);
209
- return selectedScopeCanSee(selectedWorkspaceScope, path) && await sourceViewHasPath(resolvedDefinition, sourceView, path) || await workspace.fs.exists(path);
342
+ return selectedScopeCanSee(selectedWorkspaceScope, path) && (await sourceViewHasPath(resolvedDefinition, sourceView, path) || canUseBase(path) && await workspace.fs.exists(path));
210
343
  },
211
344
  async list(path = "", options = {}) {
212
345
  const normalized = normalizeWorkspacePath(path);
213
346
  if (normalized && isSourcePath(resolvedDefinition, normalized)) return filterScopedEntries(selectedWorkspaceScope, await sourceView.list(normalized, options));
214
347
  const [baseEntries, sourceEntries] = await Promise.all([workspace.fs.list(path, options), selectedScopeCanSee(selectedWorkspaceScope, normalized) && sourcePathIntersects(resolvedDefinition, normalized) ? sourceView.list(normalized, options) : Promise.resolve([])]);
215
- return mergeEntries(filterBaseEntries(resolvedDefinition, baseEntries), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
348
+ return mergeEntries(filterScopedEntries(selectedWorkspaceScope, filterBaseEntries(resolvedDefinition, baseEntries).filter((entry) => canUseBase(entry.path))), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
216
349
  },
217
350
  async glob(pattern, options) {
218
351
  const [baseEntries, sourceEntries] = await Promise.all([workspace.fs.glob(pattern, options), sourceView.glob(pattern, options)]);
219
- return mergeEntries(filterBaseEntries(resolvedDefinition, baseEntries), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
352
+ return mergeEntries(filterScopedEntries(selectedWorkspaceScope, filterBaseEntries(resolvedDefinition, baseEntries).filter((entry) => canUseBase(entry.path))), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
220
353
  },
221
354
  async search(query) {
222
355
  const scopedToSource = searchQueryTargetsSource(resolvedDefinition, query);
223
356
  const [baseHits, sourceHits] = await Promise.all([scopedToSource ? Promise.resolve([]) : workspace.fs.search(query), sourceView.search(query)]);
224
- return mergeHits(filterBaseHits(resolvedDefinition, baseHits), filterScopedHits(selectedWorkspaceScope, sourceHits)).slice(0, query.limit ?? 100);
357
+ return mergeHits(filterScopedHits(selectedWorkspaceScope, filterBaseHits(resolvedDefinition, baseHits).filter((hit) => canUseBase(hit.path))), filterScopedHits(selectedWorkspaceScope, sourceHits)).slice(0, query.limit ?? 100);
225
358
  },
226
359
  materializeSources,
227
360
  startSession: async (options) => {
228
361
  const paths = options?.paths?.length ? options.paths : [""];
229
- await Promise.all(paths.map((path) => materializeSources({ path })));
362
+ if (options?.materializeSources !== false) await Promise.all(paths.map((path) => materializeSources({ path })));
230
363
  return await startOverlayWorkspaceSession(resolvedDefinition, readWorkspace, options);
231
364
  }
232
365
  }, sourceRequestExecution);
@@ -252,6 +385,7 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
252
385
  read: options?.read,
253
386
  search: options?.search
254
387
  },
388
+ sourceRequests: options?.sourceRequests,
255
389
  timeout: options?.timeout
256
390
  });
257
391
  const tools = createTools();
@@ -259,7 +393,8 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
259
393
  tools.none = (() => ({}));
260
394
  if (isWritableWorkspaceFacade(workspace)) {
261
395
  const writePolicy = createWorkspaceWritePolicy(resolvedDefinition);
262
- const syncStore = createWritableFacadeStore(workspace);
396
+ const syncStore = createWritableFacadeStore(workspace, resolvedDefinition);
397
+ if (!sourceSyncStores.has(workspace.fs)) registerWorkspaceStoreAlias(syncStore, overlayStore);
263
398
  let writeWorkspace;
264
399
  async function previousStat(path) {
265
400
  try {
@@ -268,7 +403,34 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
268
403
  return;
269
404
  }
270
405
  }
271
- async function writeWithPolicy(input, write) {
406
+ const writes = {
407
+ writeFile: async (path, content, options) => await workspace.fs.writeFile(path, content, options),
408
+ mkdir: async (path, options) => await workspace.fs.mkdir(path, options),
409
+ rm: async (path, options) => await workspace.fs.rm(path, options)
410
+ };
411
+ const baseWrites = {
412
+ mkdir: sourceView.requireWriteGrant(async (path, options) => await writes.mkdir(path, options)),
413
+ rm: sourceView.requireWriteGrant(async (path, options) => await writes.rm(path, options)),
414
+ writeFile: sourceView.requireWriteGrant(async (path, content, options) => await writes.writeFile(path, content, options))
415
+ };
416
+ const baseRebase = sourceView.requireRebaseGrants(async (options) => await workspace.history.rebase(options));
417
+ const resolvedHistory = createWorkspaceHistory(resolvedDefinition, {
418
+ ...overlayStore,
419
+ history: {
420
+ ...createWorkspaceHistoryReader(workspace.history, true),
421
+ commit: async (options) => await workspace.history.commit(forwardWorkspaceHistoryFiles(options))
422
+ }
423
+ }, sourceView);
424
+ async function commitHistory(options) {
425
+ requireCompleteHistory();
426
+ return await resolvedHistory.commit(options);
427
+ }
428
+ async function rebase(options) {
429
+ const grants = [];
430
+ for (const path of options?.takeRemote ?? []) grants.push(await sourceView.assertWritable(path));
431
+ await baseRebase(grants, options);
432
+ }
433
+ async function writeWithPolicy(input, write, preservePath = false) {
272
434
  await sourceView.assertWritable(input.path);
273
435
  const next = await writePolicy.before({
274
436
  ...input,
@@ -277,41 +439,55 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
277
439
  workspace: resolvedDefinition.name
278
440
  });
279
441
  try {
280
- await sourceView.assertWritable(next.path);
281
- await write(next);
442
+ if (preservePath && next.path !== normalizeWorkspacePath(input.path)) throw workspaceError(`[vitehub] Workspace validator cannot rewrite preserved path: ${normalizeWorkspacePath(input.path)} -> ${next.path}.`);
443
+ const result = await write(next, await sourceView.assertWritable(next.path));
282
444
  await writePolicy.after(next);
445
+ return {
446
+ input: next,
447
+ result
448
+ };
283
449
  } catch (error) {
284
450
  await writePolicy.error(next, error);
285
451
  throw error;
286
452
  }
287
453
  }
288
454
  function withSessionSourceGuards(session) {
455
+ const sessionWrites = {
456
+ mkdir: sourceView.requireWriteGrant(async (path, options) => await session.mkdir(path, options)),
457
+ rm: sourceView.requireWriteGrant(async (path, options) => await session.rm(path, options)),
458
+ writeFile: sourceView.requireWriteGrant(async (path, content, options) => await session.writeFile(path, content, options))
459
+ };
289
460
  return {
290
461
  ...session,
291
462
  async mkdir(path, options) {
292
- await sourceView.assertWritable(path);
293
- await session.mkdir(path, options);
463
+ await sessionWrites.mkdir(await sourceView.assertWritable(path), path, options);
294
464
  },
295
465
  async rm(path, options) {
296
- await sourceView.assertWritable(path);
297
- await session.rm(path, options);
466
+ await sessionWrites.rm(await sourceView.assertWritable(path), path, options);
298
467
  },
299
468
  async writeFile(path, content, options) {
300
- await sourceView.assertWritable(path);
301
- await session.writeFile(path, content, options);
469
+ await sessionWrites.writeFile(await sourceView.assertWritable(path), path, content, options);
302
470
  }
303
471
  };
304
472
  }
305
473
  const writeFs = attachWorkspaceSourceRequestExecution({
306
- appendFile: async (path, content) => await appendWorkspaceFile(writeWorkspace, path, content),
307
- copyPath: async (from, to, options) => await copyWorkspacePath(writeWorkspace, from, to, options?.overwrite),
474
+ appendFile: async (path, content) => {
475
+ await sourceView.assertWritable(path);
476
+ await appendWorkspaceFile(writeWorkspace, path, content);
477
+ },
478
+ copyPath: async (from, to, options) => {
479
+ await sourceView.assertWritable(to);
480
+ await copyWorkspacePath(writeWorkspace, from, to, options?.overwrite);
481
+ },
308
482
  exists: fs.exists,
309
483
  glob: fs.glob,
310
484
  list: fs.list,
311
- mkdir: async (path, options) => await writeWithPolicy({
312
- operation: "mkdir",
313
- path
314
- }, async (input) => await workspace.fs.mkdir(input.path, options)),
485
+ mkdir: async (path, options) => {
486
+ await writeWithPolicy({
487
+ operation: "mkdir",
488
+ path
489
+ }, async (input, grant) => await baseWrites.mkdir(grant, input.path, options));
490
+ },
315
491
  movePath: async (from, to, options) => {
316
492
  await sourceView.assertWritable(from);
317
493
  await sourceView.assertWritable(to);
@@ -322,55 +498,59 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
322
498
  });
323
499
  },
324
500
  readFile: fs.readFile,
325
- rm: async (path, options) => await writeWithPolicy({
326
- operation: "rm",
327
- path
328
- }, async (input) => await workspace.fs.rm(input.path, options)),
501
+ rm: async (path, options) => {
502
+ await writeWithPolicy({
503
+ operation: "rm",
504
+ path
505
+ }, async (input, grant) => await baseWrites.rm(grant, input.path, options));
506
+ },
329
507
  search: fs.search,
330
508
  stat: fs.stat,
331
- writeFile: async (path, content, options) => await writeWithPolicy({
332
- content,
333
- mediaType: options?.mediaType,
334
- metadata: options?.metadata,
335
- operation: "writeFile",
336
- path
337
- }, async (input) => {
338
- const writeOptions = options === void 0 && input.mediaType === void 0 && input.metadata === void 0 ? void 0 : {
339
- ...options,
340
- mediaType: input.mediaType,
341
- metadata: input.metadata
342
- };
343
- await workspace.fs.writeFile(input.path, input.content ?? content, writeOptions);
344
- })
509
+ writeFile: async (path, content, options) => {
510
+ const { input, result } = await writeWithPolicy({
511
+ content,
512
+ mediaType: options?.mediaType,
513
+ metadata: options?.metadata,
514
+ operation: "writeFile",
515
+ path
516
+ }, async (next, grant) => {
517
+ const writeOptions = options === void 0 && next.mediaType === void 0 && next.metadata === void 0 ? void 0 : {
518
+ ...options,
519
+ mediaType: next.mediaType,
520
+ metadata: next.metadata
521
+ };
522
+ return await baseWrites.writeFile(grant, next.path, next.content ?? content, writeOptions);
523
+ }, options?.preservePath);
524
+ return result || input.path;
525
+ }
345
526
  }, sourceRequestExecution);
346
527
  writeWorkspace = attachWorkspaceSourceRequestExecution({
347
528
  name: resolvedDefinition.name,
529
+ history: {
530
+ ...workspace.history,
531
+ ...history,
532
+ commit: commitHistory
533
+ },
348
534
  diff: workspace.diff,
349
535
  exists: writeFs.exists,
350
536
  glob: writeFs.glob,
351
537
  list: writeFs.list,
352
538
  materializeSources,
353
539
  mkdir: writeFs.mkdir,
354
- publish: async (options) => {
355
- const { publishWorkspace } = await import("./lifecycle-BYoa9hVb.js").then((n) => n.t);
356
- await publishWorkspace(resolvedDefinition, createWritableFacadeStore({
357
- ...workspace,
358
- fs: writeFs
359
- }), options);
360
- },
540
+ rebase,
361
541
  readFile: writeFs.readFile,
362
542
  rm: writeFs.rm,
363
543
  search: writeFs.search,
364
544
  snapshot: workspace.snapshot,
365
545
  startSession: async (options) => {
366
546
  const paths = options?.paths?.length ? options.paths : [""];
367
- await Promise.all(paths.map((path) => materializeSources({ path })));
368
- const startBoxSession = workspace[Symbol.for("vitehub.workspace.start-box-session")];
369
- return withSessionSourceGuards(options?.host ? await startOverlayWorkspaceSession(resolvedDefinition, writeWorkspace, options) : typeof startBoxSession === "function" ? await startBoxSession(writeWorkspace, options) : await startOverlayWorkspaceSession(resolvedDefinition, writeWorkspace, options));
547
+ if (options?.materializeSources !== false) await Promise.all(paths.map((path) => materializeSources({ path })));
548
+ const startSandboxSession = Reflect.get(workspace, Symbol.for("vitehub.workspace.start-sandbox-session"));
549
+ return withSessionSourceGuards(options?.host ? await startOverlayWorkspaceSession(resolvedDefinition, writeWorkspace, options) : typeof startSandboxSession === "function" ? await startSandboxSession(writeWorkspace, options) : await startOverlayWorkspaceSession(resolvedDefinition, writeWorkspace, options));
370
550
  },
371
551
  stat: writeFs.stat,
372
552
  sync: async (options) => {
373
- const { syncWorkspaceSources } = await import("./sync-DiuDmSGk.js");
553
+ const { syncWorkspaceSources } = await import("./sync-CN6ec-5M.js");
374
554
  return await syncWorkspaceSources(resolvedDefinition, syncStore, options);
375
555
  },
376
556
  writeFile: writeFs.writeFile
@@ -387,31 +567,100 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
387
567
  search: options?.search,
388
568
  write: writeOperations(options)
389
569
  },
570
+ sourceRequests: options?.sourceRequests,
390
571
  timeout: options?.timeout
391
572
  });
392
573
  const writeTools = createWriteTools();
393
574
  writeTools.inspect = createTools;
394
575
  writeTools.none = (() => ({}));
395
576
  writeTools.write = createWriteTools;
577
+ const baseHistory = workspace.history;
578
+ const writableHistory = {
579
+ ...history,
580
+ ...baseHistory.merge ? { merge: async (options) => {
581
+ requireCompleteHistory();
582
+ return await baseHistory.merge(forwardWorkspaceHistoryMerge(options, async (commitOptions, apply) => {
583
+ return await createWorkspaceHistory(resolvedDefinition, {
584
+ ...overlayStore,
585
+ history: {
586
+ ...createWorkspaceHistoryReader(workspace.history, true),
587
+ commit: apply
588
+ }
589
+ }, sourceView).commit(commitOptions);
590
+ }));
591
+ } } : {},
592
+ ...baseHistory.openPullRequest ? { openPullRequest: async (options) => {
593
+ requireCompleteHistory();
594
+ return await baseHistory.openPullRequest(options);
595
+ } } : {},
596
+ commit: commitHistory,
597
+ checkpoint: baseHistory.checkpoint.bind(baseHistory),
598
+ rebase
599
+ };
600
+ const writableWorkspace = {
601
+ ...workspace,
602
+ async capabilities() {
603
+ const capabilities = await workspace.capabilities();
604
+ return {
605
+ ...capabilities,
606
+ retainedHistory: capabilities.retainedHistory === true && (!selectedWorkspaceScope || selectedWorkspaceScope.all)
607
+ };
608
+ },
609
+ diff: writeWorkspace.diff,
610
+ fs: writeFs,
611
+ history: writableHistory,
612
+ materializeSources,
613
+ snapshot: writeWorkspace.snapshot,
614
+ startSession: writeWorkspace.startSession,
615
+ sync: writeWorkspace.sync,
616
+ tools: writeTools
617
+ };
618
+ sourceSyncStores.set(writableWorkspace.fs, (childDefinition) => {
619
+ const guardDefinition = {
620
+ ...sourceViewDefinition,
621
+ sources: Object.fromEntries(Object.entries(sourceViewDefinition.sources ?? {}).filter(([key, source]) => {
622
+ const resolvedSource = resolvedDefinition.sources?.[key];
623
+ return childDefinition.name !== resolvedDefinition.name || !sameWorkspaceSourceBinding(key, resolvedSource, childDefinition.sources?.[key]) || !normalizeWorkspaceSource(key, resolvedSource ?? source).sync;
624
+ }))
625
+ };
626
+ const guard = createWorkspaceSourceView(guardDefinition, overlayStore, { reuseStartupSnapshots: true });
627
+ const backing = createWritableFacadeStore(workspace, childDefinition);
628
+ const guarded = {
629
+ ...backing,
630
+ async readFile(path) {
631
+ await guard.assertWritableCurrentPath(normalizeWorkspacePath(path));
632
+ return await backing.readFile(path);
633
+ },
634
+ async writeFile(path, file) {
635
+ await guard.assertWritableCurrentPath(normalizeWorkspacePath(path));
636
+ await backing.writeFile(path, file);
637
+ },
638
+ async mkdir(path, options) {
639
+ await guard.assertWritableCurrentPath(normalizeWorkspacePath(path));
640
+ await backing.mkdir(path, options);
641
+ },
642
+ async rm(path, options) {
643
+ await guard.assertWritableCurrentPath(normalizeWorkspacePath(path));
644
+ await backing.rm(path, options);
645
+ }
646
+ };
647
+ registerWorkspaceStoreAlias(guarded, syncStore);
648
+ return guarded;
649
+ });
650
+ attachWorkspaceMetadataTarget(writableWorkspace, () => createWorkspaceMetadataTarget(overlayStore, resolvedDefinition.name));
651
+ forwardWorkspaceStoreTarget(workspace, writableWorkspace);
396
652
  return {
397
653
  definition: resolvedDefinition,
398
- workspace: {
399
- ...workspace,
400
- diff: writeWorkspace.diff,
401
- fs: writeFs,
402
- materializeSources,
403
- publish: writeWorkspace.publish,
404
- snapshot: writeWorkspace.snapshot,
405
- startSession: writeWorkspace.startSession,
406
- sync: writeWorkspace.sync,
407
- tools: writeTools
408
- }
654
+ workspace: writableWorkspace
409
655
  };
410
656
  }
411
657
  const readonlyWorkspace = {
412
658
  fs,
659
+ history,
413
660
  tools
414
661
  };
662
+ attachWorkspaceMetadataTarget(readonlyWorkspace, () => createWorkspaceMetadataTarget(overlayStore, resolvedDefinition.name));
663
+ forwardWorkspaceStoreTarget(workspace, readonlyWorkspace);
415
664
  const starter = workspaceSessionStarter(workspace);
416
665
  if (starter) readonlyWorkspace.startSession = async (options) => await starter.startSession(options);
417
666
  return {
@@ -443,7 +692,7 @@ async function resolveWorkspaceSource(definition, key, input, options) {
443
692
  const resolvedSource = withResolvedSourceRuntimeDefaults(applyResolvedWorkspaceSourceBinding(input, resolved));
444
693
  const normalized = normalizeWorkspaceSource(key, resolvedSource);
445
694
  if (!selectedScopeIntersectsSource(options.selectedWorkspaceScope, normalized)) return void 0;
446
- return copyWorkspaceSourceMetadata(resolvedSource, {
695
+ const result = copyWorkspaceSourceMetadata(resolvedSource, {
447
696
  ...resolvedSource,
448
697
  fingerprint: {
449
698
  source: resolvedSource.fingerprint,
@@ -456,6 +705,8 @@ async function resolveWorkspaceSource(definition, key, input, options) {
456
705
  } : void 0 }
457
706
  }
458
707
  });
708
+ sourceBindingLineage.set(result, typeof input === "object" ? sourceBindingLineage.get(input) ?? input : input);
709
+ return result;
459
710
  }
460
711
  function applyResolvedWorkspaceSourceBinding(input, source) {
461
712
  if (!isPlainRecord(input)) return source;
@@ -470,11 +721,12 @@ function applyResolvedWorkspaceSourceBinding(input, source) {
470
721
  return next;
471
722
  }
472
723
  function copyDefinedWorkspaceBindingOption(target, input, key) {
473
- if (input[key] !== void 0) target[key] = input[key];
724
+ if (Object.hasOwn(input, key) && input[key] !== void 0) target[key] = input[key];
474
725
  }
475
726
  function withResolvedSourceRuntimeDefaults(source) {
476
- if (source.materialize || source.mount && typeof source.mount === "object" && source.mount.materialize) return source;
477
- if (source.sync) return source;
727
+ const mount = ownSourceOption(source, "mount");
728
+ if (ownSourceOption(source, "materialize") || mount && typeof mount === "object" && ownSourceOption(mount, "materialize")) return source;
729
+ if (ownSourceOption(source, "sync")) return source;
478
730
  return copyWorkspaceSourceMetadata(source, {
479
731
  ...source,
480
732
  materialize: "lazy"
@@ -509,7 +761,12 @@ function sourceDescriptorPathIntersects(definition, path) {
509
761
  }
510
762
  function isLazySourcePath(definition, path) {
511
763
  const normalized = normalizeWorkspacePath(path);
512
- return normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "lazy").some((source) => pathIntersects(source.mountPath, normalized));
764
+ return normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "lazy" || source.materialize === "startup").some((source) => pathIntersects(source.mountPath, normalized));
765
+ }
766
+ function isUnchangedStartupSourcePath(definition, resolvedDefinition, path) {
767
+ const resolved = resolveWorkspacePath(resolvedDefinition, path);
768
+ if (resolved.type === "source") return resolved.materialize === "startup" && resolvedDefinition.sources?.[resolved.sourceKey] === definition.sources?.[resolved.sourceKey];
769
+ return normalizeWorkspaceSources(resolvedDefinition.sources).some((source) => !source.mountPath && source.materialize === "startup" && resolvedDefinition.sources?.[source.key] === definition.sources?.[source.key]);
513
770
  }
514
771
  function searchQueryTargetsSource(definition, query) {
515
772
  return (query.paths?.length ? query.paths : [query.cwd || ""]).every((path) => isSourcePath(definition, path));
@@ -535,7 +792,7 @@ function scopedWorkspaceSource(source, scope) {
535
792
  const scoped = {
536
793
  ...source.source,
537
794
  ...scopedLivePaths ? { async prepare(ctx) {
538
- await source.source.prepare?.(ctx);
795
+ await prepareWorkspaceSource(source.source, ctx);
539
796
  syncScopedLivePaths(scopedLivePaths, source.livePaths, scope);
540
797
  } } : {},
541
798
  ...source.source.getItems ? { getItems: async (ctx) => (await source.source.getItems(ctx)).filter((item) => selectedScopeCanRead(scope, sourceItemWorkspacePath(source, item.path || item.key))) } : {},
@@ -548,14 +805,6 @@ function scopedWorkspaceSource(source, scope) {
548
805
  ...source.source.getMeta ? { getMeta: async (key, ctx) => {
549
806
  if (!selectedScopeCanRead(scope, sourceItemWorkspacePath(source, key))) return void 0;
550
807
  return await source.source.getMeta(key, ctx);
551
- } } : {},
552
- ...source.source.search ? { search: async (query, ctx) => {
553
- const paths = selectedScopeQueryPaths(scope, query).filter((path) => pathIntersects(source.mountPath, path));
554
- if (!paths.length) return [];
555
- return filterScopedHits(scope, await source.source.search({
556
- ...query,
557
- paths
558
- }, ctx));
559
808
  } } : {}
560
809
  };
561
810
  if (!source.requestDescriptor || selectedScopeCanRead(scope, workspaceSourceRequestDescriptorPath(source.key))) copyWorkspaceSourceMetadata(source.source, scoped);
@@ -571,14 +820,6 @@ function sourceItemWorkspacePath(source, sourcePath) {
571
820
  const normalized = normalizeWorkspacePath(sourcePath);
572
821
  return normalizeWorkspacePath(source.mountPath ? `${source.mountPath}/${normalized}` : normalized);
573
822
  }
574
- function selectedScopeQueryPaths(scope, query) {
575
- const requestedPaths = (query.paths?.length ? query.paths : [query.cwd || ""]).map((path) => normalizeWorkspacePath(path));
576
- const scopedPaths = (scope.paths || []).map((path) => normalizeWorkspacePath(path));
577
- const paths = /* @__PURE__ */ new Set();
578
- for (const scopedPath of scopedPaths) for (const requestedPath of requestedPaths) if (pathContains(scopedPath, requestedPath)) paths.add(requestedPath);
579
- else if (pathContains(requestedPath, scopedPath)) paths.add(scopedPath);
580
- return [...paths];
581
- }
582
823
  function selectedScopeCanRead(scope, path) {
583
824
  if (!scope || scope.all) return true;
584
825
  const normalized = normalizeWorkspacePath(path);
@@ -623,4 +864,216 @@ function pathIntersects(left, right) {
623
864
  return pathContains(left, right) || pathContains(right, left);
624
865
  }
625
866
  //#endregion
626
- export { attachWorkspaceSourceRequestExecution, createWorkspaceSourceResolutionFacade, getWorkspaceDependencyRuntimeLoaders, getWorkspaceHostedStoreLoader, getWorkspaceRuntimeConfig, getWorkspaceSourceRequestDescriptor, getWorkspaceSourceRequestExecution, hasWorkspaceSourceResolvers, isWorkspaceSourceRequestOnly, markLiveWorkspaceSource, normalizeWorkspaceSourceMetadata, normalizeWorkspaceSourcesMetadata, registerWorkspace, resetWorkspaceStoreCache, resolveRegisteredWorkspaceDefinition, resolveWorkspaceSources, setWorkspaceDependencyRuntimeLoaders, setWorkspaceHostedStoreLoader, setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeConfig, setWorkspaceRuntimeRegistry, useWorkspace, workspaceSourceGrantPaths, workspaceSourceRequestDescriptorPath };
867
+ //#region src/runtime/preparation.ts
868
+ const MAX_TIMER_DELAY_MS = 2147483647;
869
+ async function waitForAbortable(operation, signal) {
870
+ let removeAbortListener = () => {};
871
+ const aborted = new Promise((_resolve, reject) => {
872
+ const onAbort = () => reject(signal.reason);
873
+ if (signal.aborted) return onAbort();
874
+ signal.addEventListener("abort", onAbort, { once: true });
875
+ removeAbortListener = () => signal.removeEventListener("abort", onAbort);
876
+ });
877
+ try {
878
+ return await Promise.race([operation, aborted]);
879
+ } finally {
880
+ removeAbortListener();
881
+ }
882
+ }
883
+ function createWorkspacePreparation(options) {
884
+ if (!options || !hasRuntimeType(options.workspace, "string") || !options.workspace.trim()) throw workspaceErrorDiagnostics.WORKSPACE_R0034({ message: "[vitehub] Workspace preparation requires a Workspace name." });
885
+ if (options.sources !== void 0 && (!Array.isArray(options.sources) || options.sources.some((source) => !hasRuntimeType(source, "string") || !source.trim()))) throw workspaceErrorDiagnostics.WORKSPACE_R0035({ message: "[vitehub] Workspace preparation sources must be non-empty strings." });
886
+ const retryDelayMs = options.retryDelayMs ?? 1e4;
887
+ if (!Number.isFinite(retryDelayMs) || retryDelayMs < 0 || retryDelayMs > MAX_TIMER_DELAY_MS) throw workspaceErrorDiagnostics.WORKSPACE_R0036({ message: `[vitehub] Workspace preparation retryDelayMs must be between 0 and ${MAX_TIMER_DELAY_MS}.` });
888
+ const workspaceName = options.workspace.trim();
889
+ const sources = options.sources === void 0 ? void 0 : [...new Set(options.sources.map((source) => source.trim()))];
890
+ let workspace = useWorkspace(workspaceName, { mode: "write" });
891
+ let state = Object.freeze({
892
+ stoppedAt: (/* @__PURE__ */ new Date()).toISOString(),
893
+ status: "stopped"
894
+ });
895
+ let active;
896
+ let starting;
897
+ let abortController;
898
+ let retryTimer;
899
+ let started = false;
900
+ let stopped = true;
901
+ let lifecycle = 0;
902
+ const publish = (next) => {
903
+ state = Object.freeze(next);
904
+ try {
905
+ options.onStateChange?.(state);
906
+ } catch {}
907
+ return state;
908
+ };
909
+ const run = async () => {
910
+ if (stopped) return state;
911
+ if (active) return await active;
912
+ const attemptLifecycle = lifecycle;
913
+ const startedAtMs = Date.now();
914
+ const startedAt = new Date(startedAtMs).toISOString();
915
+ const controller = new AbortController();
916
+ abortController = controller;
917
+ let resolveAttempt;
918
+ let rejectAttempt;
919
+ const attempt = new Promise((resolve, reject) => {
920
+ resolveAttempt = resolve;
921
+ rejectAttempt = reject;
922
+ });
923
+ active = attempt;
924
+ publish({
925
+ startedAt,
926
+ status: "preparing"
927
+ });
928
+ (async () => {
929
+ try {
930
+ const definition = await resolveRegisteredWorkspaceDefinition(workspaceName, controller.signal);
931
+ const selectedSources = sources ?? normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "startup").map((source) => source.key);
932
+ const result = await workspace.materializeSources({
933
+ abortSignal: controller.signal,
934
+ sources: selectedSources
935
+ });
936
+ if (!selectedSources.length) throw workspaceErrorDiagnostics.WORKSPACE_R0037({ message: `[vitehub] Workspace "${workspaceName}" has no startup sources to prepare.` });
937
+ const sourceResults = new Map(result.sources.map((source) => [source.source, source]));
938
+ const failures = selectedSources.filter((source) => sourceResults.get(source)?.status !== "ready");
939
+ if (failures.length) throw workspaceErrorDiagnostics.WORKSPACE_R0038({ message: `[vitehub] Workspace "${workspaceName}" sources failed to prepare: ${failures.join(", ")}.` });
940
+ if (options.requireNonEmpty) {
941
+ const empty = selectedSources.filter((source) => !sourceResults.get(source)?.files);
942
+ if (empty.length) throw workspaceErrorDiagnostics.WORKSPACE_R0038({ message: `[vitehub] Workspace "${workspaceName}" sources are empty: ${empty.join(", ")}.` });
943
+ }
944
+ await waitForAbortable(options.validate?.(result), controller.signal);
945
+ if (stopped || attemptLifecycle !== lifecycle) return state;
946
+ const finishedAtMs = Date.now();
947
+ return publish({
948
+ durationMs: finishedAtMs - startedAtMs,
949
+ finishedAt: new Date(finishedAtMs).toISOString(),
950
+ result,
951
+ startedAt,
952
+ status: "ready"
953
+ });
954
+ } catch (error) {
955
+ if (controller.signal.aborted) workspace = useWorkspace(workspaceName, { mode: "write" });
956
+ if (stopped || attemptLifecycle !== lifecycle) return state;
957
+ const finishedAtMs = Date.now();
958
+ const next = publish({
959
+ durationMs: finishedAtMs - startedAtMs,
960
+ error: error instanceof Error ? error.message : String(error),
961
+ finishedAt: new Date(finishedAtMs).toISOString(),
962
+ startedAt,
963
+ status: "error"
964
+ });
965
+ if (!stopped && attemptLifecycle === lifecycle) retryTimer = setTimeout(() => {
966
+ retryTimer = void 0;
967
+ if (!stopped && attemptLifecycle === lifecycle) run();
968
+ }, retryDelayMs);
969
+ return next;
970
+ } finally {
971
+ if (abortController === controller) abortController = void 0;
972
+ }
973
+ })().then(resolveAttempt, rejectAttempt);
974
+ try {
975
+ return await attempt;
976
+ } finally {
977
+ if (active === attempt) active = void 0;
978
+ }
979
+ };
980
+ return Object.freeze({
981
+ getState() {
982
+ return state;
983
+ },
984
+ response(method = "GET") {
985
+ if (method !== "GET" && method !== "HEAD") return new Response(null, {
986
+ status: 405,
987
+ headers: {
988
+ allow: "GET, HEAD",
989
+ "cache-control": "no-store"
990
+ }
991
+ });
992
+ const ready = state.status === "ready";
993
+ return new Response(method === "HEAD" ? null : JSON.stringify({
994
+ ready,
995
+ status: state.status
996
+ }), {
997
+ headers: {
998
+ "cache-control": "no-store",
999
+ "content-type": "application/json; charset=utf-8"
1000
+ },
1001
+ status: ready ? 200 : 503
1002
+ });
1003
+ },
1004
+ async start() {
1005
+ if (started) return starting ? await starting : active ? await active : state;
1006
+ started = true;
1007
+ stopped = false;
1008
+ const startLifecycle = ++lifecycle;
1009
+ const transition = (async () => {
1010
+ if (active) await active;
1011
+ if (!started || stopped || startLifecycle !== lifecycle) return state;
1012
+ return await run();
1013
+ })();
1014
+ starting = transition;
1015
+ try {
1016
+ return await transition;
1017
+ } finally {
1018
+ if (starting === transition) starting = void 0;
1019
+ }
1020
+ },
1021
+ async stop() {
1022
+ started = false;
1023
+ stopped = true;
1024
+ lifecycle++;
1025
+ publish({
1026
+ status: "stopped",
1027
+ stoppedAt: (/* @__PURE__ */ new Date()).toISOString()
1028
+ });
1029
+ if (retryTimer) clearTimeout(retryTimer);
1030
+ retryTimer = void 0;
1031
+ const current = active;
1032
+ abortController?.abort(workspaceErrorDiagnostics.WORKSPACE_R0039({ message: `[vitehub] Workspace "${workspaceName}" preparation stopped.` }));
1033
+ await current;
1034
+ }
1035
+ });
1036
+ }
1037
+ //#endregion
1038
+ //#region src/storage/recover-local-locks.ts
1039
+ /**
1040
+ * Remove abandoned markers from a trusted, exclusively owned local store.
1041
+ * Stop all store users and prevent changes to the store and its ancestor directories
1042
+ * for the entire call. Path checks catch existing symlinks; they do not provide
1043
+ * protection against concurrent filesystem mutation.
1044
+ */
1045
+ async function recoverLocalWorkspaceLocks(options) {
1046
+ if (options.offline !== true) throw workspaceError("[vitehub] Workspace lock recovery requires exclusive offline access.");
1047
+ const root = resolve(options.root);
1048
+ const directory = join(root, ".vitehub", "locks");
1049
+ for (const path of [
1050
+ root,
1051
+ join(root, ".vitehub"),
1052
+ directory
1053
+ ]) {
1054
+ const info = await lstat(path).catch((error) => {
1055
+ if (error.code === "ENOENT") return void 0;
1056
+ throw error;
1057
+ });
1058
+ if (!info) return { removed: 0 };
1059
+ if (!info.isDirectory() || info.isSymbolicLink()) throw workspaceError(`[vitehub] Expected a real Workspace lock recovery directory: ${path}.`);
1060
+ }
1061
+ let removed = 0;
1062
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
1063
+ const markerName = /^[a-f0-9]{64}\.(gate|readers|writers)$/.test(entry.name);
1064
+ const quarantineName = /^\.recovery-[a-f0-9]{64}\.(gate|readers|writers)-[0-9a-f-]+$/.test(entry.name);
1065
+ if (!markerName && !quarantineName) continue;
1066
+ if (markerName && (!entry.isDirectory() || entry.isSymbolicLink())) throw workspaceError(`[vitehub] Expected a real Workspace lock marker directory: ${entry.name}.`);
1067
+ const source = join(directory, entry.name);
1068
+ if (quarantineName) await rm(source, { recursive: true });
1069
+ else {
1070
+ const quarantine = join(directory, `.recovery-${entry.name}-${randomUUID()}`);
1071
+ await rename(source, quarantine);
1072
+ await rm(quarantine, { recursive: true });
1073
+ }
1074
+ removed++;
1075
+ }
1076
+ return { removed };
1077
+ }
1078
+ //#endregion
1079
+ export { attachWorkspaceSourceRequestExecution, createWorkspaceHistoryReader, createWorkspacePreparation, createWorkspaceSourceResolutionFacade, forwardWorkspaceFacade, forwardWorkspaceMetadataView, getWorkspaceDependencyRuntimeLoaders, getWorkspaceHostedStoreLoader, getWorkspaceRuntimeConfig, getWorkspaceSourceRequestDescriptor, getWorkspaceSourceRequestExecution, hasWorkspaceSourceResolvers, invalidateWorkspaceStore, isWorkspaceSourceRequestOnly, markLiveWorkspaceSource, normalizeWorkspaceSourceMetadata, normalizeWorkspaceSourcesMetadata, recoverLocalWorkspaceLocks, registerWorkspace, registerWorkspacePlugin, resetWorkspaceStoreCache, resolveRegisteredWorkspaceDefinition, resolveWorkspaceSources, setWorkspaceDependencyRuntimeLoaders, setWorkspaceHostedStoreLoader, setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeConfig, setWorkspaceRuntimeRegistry, useWorkspace, workspaceSourceGrantPaths, workspaceSourceRequestDescriptorPath, workspaceSourceRequestMatches };