@vite-hub/workspace 0.0.1 → 0.0.3

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 (95) hide show
  1. package/README.md +225 -17
  2. package/dist/{ai-Bk3LLnit.js → ai-Ce3PtWFW.js} +160 -29
  3. package/dist/ai-nmHdzjCM.d.ts +162 -0
  4. package/dist/ai.d.ts +2 -85
  5. package/dist/ai.js +1 -1
  6. package/dist/asset-registry-CaG9b7tf.js +19 -0
  7. package/dist/cloudflare.d.ts +18 -0
  8. package/dist/cloudflare.js +2 -0
  9. package/dist/collections/client.d.ts +39 -0
  10. package/dist/collections/client.js +137 -0
  11. package/dist/collections.d.ts +59 -0
  12. package/dist/collections.js +159 -0
  13. package/dist/config-3I1BnsdO.d.ts +28 -0
  14. package/dist/config-CDoyls2X.js +30 -0
  15. package/dist/config-CZLO0m9h.js +7811 -0
  16. package/dist/file-CHfsZpso.js +23 -0
  17. package/dist/{files-DbsIjBya.js → files-QRV55OCx.js} +6 -5
  18. package/dist/github-CfA5vpJ5.js +189 -0
  19. package/dist/glob-D0vD_wRY.js +17 -0
  20. package/dist/host-CAnbugpI.js +370 -0
  21. package/dist/hosted-C1-tTTTf.js +581 -0
  22. package/dist/{providers/vercel/blob-store.js → hosted-vercel-blob-CWBILDVo.js} +100 -19
  23. package/dist/hosted-vercel-blob.d.ts +15 -0
  24. package/dist/hosted-vercel-blob.js +2 -0
  25. package/dist/hosted.d.ts +18 -0
  26. package/dist/hosted.js +2 -0
  27. package/dist/index.d.ts +129 -102
  28. package/dist/index.js +477 -599
  29. package/dist/lifecycle-BYoa9hVb.js +176 -0
  30. package/dist/loader.d.ts +1 -1
  31. package/dist/loader.js +1 -1
  32. package/dist/mountx.d.ts +10 -0
  33. package/dist/mountx.js +143 -0
  34. package/dist/nitro.d.ts +2 -31
  35. package/dist/nitro.js +2 -2
  36. package/dist/nuxt.d.ts +26 -0
  37. package/dist/nuxt.js +36 -0
  38. package/dist/path-CNI6wKIU.js +115 -0
  39. package/dist/{provider-BZuKAV4e.js → provider-C3_elpEh.js} +142 -37
  40. package/dist/providers/github/store.d.ts +6 -0
  41. package/dist/providers/github/store.js +2 -0
  42. package/dist/publish.d.ts +3 -2
  43. package/dist/publish.js +48 -142
  44. package/dist/{registry-D4Qzq26I.d.ts → registry-BIQVCBWI.d.ts} +3 -2
  45. package/dist/registry-CqyDTW9Y.js +74 -0
  46. package/dist/request-execution-u9mgUXKX.js +80 -0
  47. package/dist/runtime/assets.d.ts +2 -1
  48. package/dist/runtime/assets.js +5 -5
  49. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  50. package/dist/runtime/empty-registry.d.ts +1 -1
  51. package/dist/runtime/state.d.ts +4 -21
  52. package/dist/runtime/state.js +7 -4
  53. package/dist/runtime/workspace.d.ts +2 -0
  54. package/dist/runtime/workspace.js +2 -0
  55. package/dist/runtime-options-BsPSv5O7.js +13 -0
  56. package/dist/runtime.d.ts +38 -0
  57. package/dist/runtime.js +626 -0
  58. package/dist/{search-DtaEyjpO.js → search-C4REyHj9.js} +2 -2
  59. package/dist/server.d.ts +65 -0
  60. package/dist/server.js +355 -0
  61. package/dist/shared-jfogBrd5.js +273 -0
  62. package/dist/source-metadata.d.ts +2 -0
  63. package/dist/source-metadata.js +2 -0
  64. package/dist/state-TTqa3x3Y.d.ts +25 -0
  65. package/dist/store-Bs1SLh55.js +414 -0
  66. package/dist/sync-DiuDmSGk.js +269 -0
  67. package/dist/target-D4Bqb1eH.js +11 -0
  68. package/dist/test.d.ts +1 -1
  69. package/dist/test.js +1 -1
  70. package/dist/types-60Yn149G.d.ts +612 -0
  71. package/dist/use-CUFSnFCS.d.ts +86 -0
  72. package/dist/use-CsV3oIxH.js +336 -0
  73. package/dist/vite-tbfDxtlu.js +2191 -0
  74. package/dist/vite.d.ts +33 -5
  75. package/dist/vite.js +2 -131
  76. package/dist/workspace-66SKyiec.d.ts +6 -0
  77. package/dist/workspace-C4k92Ow8.js +1460 -0
  78. package/package.json +143 -62
  79. package/dist/asset-registry-CMuQbyvl.js +0 -14
  80. package/dist/cloudflare-env-DL94Uvpz.js +0 -12
  81. package/dist/config-CvS-7sre.js +0 -49
  82. package/dist/errors-BUL8SoFS.js +0 -21
  83. package/dist/lifecycle-uD82JeGh.js +0 -92
  84. package/dist/module-8LZUMEXC.js +0 -922
  85. package/dist/path-BVv9OXhg.js +0 -63
  86. package/dist/providers/cloudflare/artifacts-store.d.ts +0 -6
  87. package/dist/providers/cloudflare/artifacts-store.js +0 -384
  88. package/dist/providers/vercel/blob-store.d.ts +0 -6
  89. package/dist/registry-Cnr0NoKv.js +0 -932
  90. package/dist/runtime/nitro-plugin.d.ts +0 -6
  91. package/dist/runtime/nitro-plugin.js +0 -14
  92. package/dist/sandbox-DtGXCWRq.js +0 -198
  93. package/dist/types-CwNcWTdt.d.ts +0 -378
  94. package/dist/utils-BtAm_K5P.js +0 -51
  95. /package/dist/{chunk-DrSxFLj_.js → chunk-8H4AJuhK.js} +0 -0
@@ -0,0 +1,414 @@
1
+ import { a as matchesAny, c as normalizeWorkspacePath, d as sha256, n as contentStreamToBytes, o as normalizeSafeWorkspacePath, p as workspaceError, s as normalizeSafeWorkspacePattern } from "./path-CNI6wKIU.js";
2
+ import { r as workspaceStoreTarget } from "./target-D4Bqb1eH.js";
3
+ import { c as readGitHubBlob, d as resolveGitHubBranchOption, h as resolveGitHubTokenOption, i as gitBlobSha, l as readGitHubBranchState, m as resolveGitHubRootOption, n as createGitHubBlob, o as joinGitPath, p as resolveGitHubRepositoryOption, r as createGitHubFileUpdate, t as commitGitHubChanges, u as requireGitHubOption } from "./shared-jfogBrd5.js";
4
+ import { posix } from "node:path";
5
+ //#region src/storage/utils.ts
6
+ async function createCurrentSnapshotFromStore(store, name) {
7
+ return await createSnapshotFromEntries(await store.list("", { recursive: true }), name);
8
+ }
9
+ async function createSnapshotFromEntries(entries, name) {
10
+ const snapshotEntries = {};
11
+ for (const entry of entries) snapshotEntries[entry.path] = {
12
+ digest: entry.digest,
13
+ metadata: entry.metadata,
14
+ size: entry.size,
15
+ type: entry.type
16
+ };
17
+ return {
18
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
19
+ entries: snapshotEntries,
20
+ id: await sha256({
21
+ entries: snapshotEntries,
22
+ name,
23
+ createdAt: Date.now()
24
+ }),
25
+ name
26
+ };
27
+ }
28
+ function diffSnapshots(from, to) {
29
+ const entries = [];
30
+ const keys = new Set([...Object.keys(from?.entries || {}), ...Object.keys(to.entries)]);
31
+ for (const path of [...keys].sort()) {
32
+ const before = from?.entries[path];
33
+ const after = to.entries[path];
34
+ if (!before && after) entries.push({
35
+ path,
36
+ type: "added",
37
+ after
38
+ });
39
+ else if (before && !after) entries.push({
40
+ path,
41
+ type: "removed",
42
+ before
43
+ });
44
+ else if (before && after && (before.digest !== after.digest || before.type !== after.type || before.size !== after.size || JSON.stringify(before.metadata) !== JSON.stringify(after.metadata))) entries.push({
45
+ path,
46
+ type: "modified",
47
+ before,
48
+ after
49
+ });
50
+ }
51
+ return {
52
+ from: from?.id,
53
+ to: to.id,
54
+ entries
55
+ };
56
+ }
57
+ //#endregion
58
+ //#region src/providers/github/store.ts
59
+ function isReservedWorkspacePath(path) {
60
+ const root = normalizeWorkspacePath(path).split("/")[0];
61
+ return root === ".git" || root === ".vitehub";
62
+ }
63
+ function contentLength(content) {
64
+ return typeof content === "string" ? new TextEncoder().encode(content).byteLength : content.byteLength;
65
+ }
66
+ function gitHubFileMetadata(entry) {
67
+ return entry.mode === "120000" || entry.mode === "100755" ? { gitMode: entry.mode } : void 0;
68
+ }
69
+ function gitHubFileMode(metadata) {
70
+ return metadata?.gitMode === "120000" || metadata?.gitMode === "100755" ? metadata.gitMode : "100644";
71
+ }
72
+ function inheritedGitHubFileMetadata(file, current) {
73
+ if (file.metadata) return file.metadata;
74
+ return current?.metadata?.gitMode === "100755" ? current.metadata : void 0;
75
+ }
76
+ function parentDirectories(path) {
77
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
78
+ const directories = [];
79
+ for (let index = 1; index < parts.length; index++) directories.push(parts.slice(0, index).join("/"));
80
+ return directories;
81
+ }
82
+ function resolveSymlinkTarget(path, bytes) {
83
+ const target = gitSymlinkTargetFromBytes(bytes);
84
+ if (!target || target.startsWith("/")) return;
85
+ const base = path.split("/").slice(0, -1).join("/");
86
+ const resolved = posix.normalize(base ? `${base}/${target}` : target);
87
+ if (!resolved || resolved === "." || resolved === ".." || resolved.startsWith("../")) return;
88
+ return normalizeSafeWorkspacePath(resolved);
89
+ }
90
+ function gitSymlinkTargetFromBytes(bytes) {
91
+ return new TextDecoder().decode(bytes).replace(/\0/g, "");
92
+ }
93
+ var GitHubWorkspaceStore = class {
94
+ workspaceName;
95
+ #baseline;
96
+ #baselineRefSha;
97
+ #baselineTreeSha;
98
+ #branch;
99
+ #dirty = false;
100
+ #files = /* @__PURE__ */ new Map();
101
+ #ready;
102
+ #remoteFiles = /* @__PURE__ */ new Map();
103
+ #repository;
104
+ #root;
105
+ #token;
106
+ constructor(options, workspaceName) {
107
+ this.workspaceName = workspaceName;
108
+ this.#repository = requireGitHubOption("store", "a repository", resolveGitHubRepositoryOption(options));
109
+ this.#branch = resolveGitHubBranchOption(options);
110
+ this.#root = resolveGitHubRootOption(options, workspaceName);
111
+ this.#token = requireGitHubOption("store", "a token", resolveGitHubTokenOption(options));
112
+ }
113
+ [workspaceStoreTarget]() {
114
+ return {
115
+ provider: "github",
116
+ branch: this.#branch,
117
+ repository: this.#repository
118
+ };
119
+ }
120
+ async readFile(path) {
121
+ const normalized = normalizeSafeWorkspacePath(path);
122
+ await this.#ensure({ refresh: true });
123
+ return await this.#readWorkspaceFile(normalized);
124
+ }
125
+ async writeFile(path, file) {
126
+ const normalized = normalizeSafeWorkspacePath(path);
127
+ await this.#ensure({ refresh: false });
128
+ const current = this.#files.get(normalized);
129
+ const metadata = inheritedGitHubFileMetadata(file, current);
130
+ const content = gitHubFileMode(metadata) === "120000" && typeof metadata?.symlinkTarget === "string" ? metadata.symlinkTarget : file.content;
131
+ const update = await createGitHubFileUpdate(normalized, this.#root, content);
132
+ if (current?.gitSha === update.gitSha) {
133
+ if (gitHubFileMode(current.metadata) !== gitHubFileMode(metadata)) this.#dirty = true;
134
+ this.#files.set(normalized, {
135
+ ...current,
136
+ mediaType: file.mediaType,
137
+ metadata,
138
+ size: contentLength(content)
139
+ });
140
+ return;
141
+ }
142
+ await createGitHubBlob({
143
+ bytes: update.bytes,
144
+ kind: "store",
145
+ repository: this.#repository,
146
+ token: this.#token
147
+ });
148
+ this.#files.set(normalized, {
149
+ gitSha: update.gitSha,
150
+ mediaType: file.mediaType,
151
+ metadata,
152
+ path: normalized,
153
+ size: contentLength(content)
154
+ });
155
+ this.#dirty = true;
156
+ }
157
+ async writeFileStream(path, file) {
158
+ const content = await contentStreamToBytes(file.content);
159
+ await this.writeFile(path, {
160
+ path: file.path,
161
+ content,
162
+ mediaType: file.mediaType,
163
+ metadata: file.metadata
164
+ });
165
+ return {
166
+ digest: await gitBlobSha(content),
167
+ mediaType: file.mediaType,
168
+ path: normalizeSafeWorkspacePath(path),
169
+ size: content.byteLength,
170
+ type: "file"
171
+ };
172
+ }
173
+ async list(prefix = "", options = {}) {
174
+ const normalizedPrefix = normalizeSafeWorkspacePath(prefix, { allowEmpty: true });
175
+ await this.#ensure({ refresh: true });
176
+ return await this.#listEntries(normalizedPrefix, options);
177
+ }
178
+ async glob(pattern, _options = {}) {
179
+ const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
180
+ return (await this.list("", { recursive: true })).filter((entry) => entry.type === "file" && matchesAny(entry.path, patterns));
181
+ }
182
+ async stat(path) {
183
+ const normalized = normalizeSafeWorkspacePath(path);
184
+ await this.#ensure({ refresh: true });
185
+ const file = this.#files.get(normalized);
186
+ if (file && !isReservedWorkspacePath(normalized)) return this.#fileEntry(file);
187
+ if (this.#directoryExists(normalized)) return {
188
+ path: normalized,
189
+ type: "directory"
190
+ };
191
+ }
192
+ async mkdir(path, _options = {}) {
193
+ normalizeSafeWorkspacePath(path);
194
+ }
195
+ async rm(path, options = {}) {
196
+ const normalized = normalizeSafeWorkspacePath(path);
197
+ await this.#ensure({ refresh: false });
198
+ if (this.#files.get(normalized) && !isReservedWorkspacePath(normalized)) {
199
+ this.#files.delete(normalized);
200
+ this.#dirty = true;
201
+ return;
202
+ }
203
+ const children = this.#publicDescendants(normalized);
204
+ if (!(children.length > 0)) {
205
+ if (options.force) return;
206
+ throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
207
+ }
208
+ if (children.length && !options.recursive) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
209
+ for (const child of children) this.#files.delete(child);
210
+ this.#dirty = true;
211
+ }
212
+ async snapshot(options = {}) {
213
+ await this.#ensure({ refresh: false });
214
+ const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
215
+ if (!this.#dirty) {
216
+ this.#baseline = snapshot;
217
+ return snapshot;
218
+ }
219
+ const remote = await readGitHubBranchState({
220
+ branch: this.#branch,
221
+ kind: "store",
222
+ repository: this.#repository,
223
+ root: this.#root,
224
+ token: this.#token
225
+ });
226
+ if (this.#baselineRefSha && remote.refSha !== this.#baselineRefSha) throw workspaceError(`[vitehub] GitHub Workspace Store conflict for ${this.#repository}@${this.#branch}: the branch changed after this Workspace Store loaded. Snapshotting requires a Workspace Store loaded from the current branch head.`);
227
+ this.#remoteFiles = remote.files;
228
+ this.#baselineRefSha = remote.refSha;
229
+ this.#baselineTreeSha = remote.treeSha;
230
+ const changedFiles = [...this.#files.values()].filter((file) => {
231
+ const remote = this.#remoteFiles.get(file.path);
232
+ return remote?.sha !== file.gitSha || (remote.mode || "100644") !== gitHubFileMode(file.metadata);
233
+ });
234
+ const deletePaths = [...this.#remoteFiles].filter(([path]) => !this.#files.has(path)).map(([, entry]) => entry.path);
235
+ if (!changedFiles.length && !deletePaths.length) {
236
+ this.#dirty = false;
237
+ this.#baseline = snapshot;
238
+ return snapshot;
239
+ }
240
+ const files = changedFiles.map((file) => {
241
+ return {
242
+ bytes: file.bytes,
243
+ fullPath: joinGitPath(this.#root, file.path),
244
+ gitSha: file.gitSha,
245
+ mode: gitHubFileMode(file.metadata)
246
+ };
247
+ });
248
+ const commit = await commitGitHubChanges({
249
+ baseTreeSha: this.#baselineTreeSha,
250
+ branch: this.#branch,
251
+ branchExists: remote.branchExists,
252
+ deletePaths,
253
+ files,
254
+ message: options.name || "chore: update workspace snapshot",
255
+ parentSha: this.#baselineRefSha,
256
+ repository: this.#repository,
257
+ token: this.#token
258
+ });
259
+ this.#dirty = false;
260
+ this.#baselineRefSha = commit.commitSha;
261
+ this.#baselineTreeSha = commit.treeSha;
262
+ this.#remoteFiles = this.#toRemoteFiles();
263
+ this.#baseline = {
264
+ ...snapshot,
265
+ id: commit.commitSha
266
+ };
267
+ return this.#baseline;
268
+ }
269
+ async diff(options = {}) {
270
+ await this.#ensure({ refresh: true });
271
+ return diffSnapshots(options.from || this.#baseline, await createSnapshotFromEntries(await this.#listEntries("", { recursive: true })));
272
+ }
273
+ async getMeta(key) {
274
+ await this.#ensure({ refresh: true });
275
+ const file = await this.#readWorkspaceFile(this.#metaPath(key));
276
+ if (!file) return void 0;
277
+ return JSON.parse(new TextDecoder().decode(file.bytes));
278
+ }
279
+ async setMeta(key, value) {
280
+ const path = this.#metaPath(key);
281
+ const content = JSON.stringify(value);
282
+ const bytes = new TextEncoder().encode(content);
283
+ await this.#ensure({ refresh: false });
284
+ this.#files.set(path, {
285
+ bytes,
286
+ gitSha: await gitBlobSha(bytes),
287
+ path,
288
+ size: bytes.byteLength
289
+ });
290
+ this.#dirty = true;
291
+ }
292
+ async #ensure(options) {
293
+ const wasReady = !!this.#ready;
294
+ this.#ready ||= this.#load();
295
+ await this.#ready;
296
+ if (wasReady && options.refresh && !this.#dirty) await this.#load();
297
+ }
298
+ async #load() {
299
+ const remote = await readGitHubBranchState({
300
+ branch: this.#branch,
301
+ kind: "store",
302
+ repository: this.#repository,
303
+ root: this.#root,
304
+ token: this.#token
305
+ });
306
+ this.#baselineRefSha = remote.refSha;
307
+ this.#baselineTreeSha = remote.treeSha;
308
+ this.#remoteFiles = remote.files;
309
+ if (!this.#dirty) {
310
+ this.#files = new Map([...remote.files].map(([path, entry]) => [path, {
311
+ gitSha: entry.sha,
312
+ metadata: gitHubFileMetadata(entry),
313
+ path,
314
+ size: entry.size
315
+ }]));
316
+ this.#baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), "github-workspace-store-load");
317
+ }
318
+ }
319
+ async #readWorkspaceFile(path, seen = /* @__PURE__ */ new Set()) {
320
+ const current = this.#files.get(path);
321
+ if (!current) return void 0;
322
+ const currentBytes = await this.#readFileBytes(current);
323
+ if (gitHubFileMode(current.metadata) === "120000" && !seen.has(path)) {
324
+ const target = resolveSymlinkTarget(path, currentBytes);
325
+ if (target && this.#files.has(target)) {
326
+ seen.add(path);
327
+ const resolved = await this.#readWorkspaceFile(target, seen);
328
+ if (resolved) return {
329
+ ...resolved,
330
+ mediaType: current.mediaType ?? resolved.mediaType,
331
+ metadata: await this.#fileMetadata(current) ?? resolved.metadata,
332
+ path
333
+ };
334
+ }
335
+ }
336
+ return {
337
+ content: currentBytes,
338
+ bytes: currentBytes,
339
+ mediaType: current.mediaType,
340
+ metadata: await this.#fileMetadata(current),
341
+ path
342
+ };
343
+ }
344
+ async #readFileBytes(file) {
345
+ if (!file.bytes) {
346
+ file.bytes = await readGitHubBlob({
347
+ kind: "store",
348
+ repository: this.#repository,
349
+ sha: file.gitSha,
350
+ token: this.#token
351
+ });
352
+ file.size = file.bytes.byteLength;
353
+ }
354
+ return file.bytes;
355
+ }
356
+ async #fileMetadata(file) {
357
+ if (gitHubFileMode(file.metadata) !== "120000" || typeof file.metadata?.symlinkTarget === "string") return file.metadata;
358
+ return {
359
+ ...file.metadata,
360
+ symlinkTarget: gitSymlinkTargetFromBytes(await this.#readFileBytes(file))
361
+ };
362
+ }
363
+ async #listEntries(prefix, options) {
364
+ const entries = /* @__PURE__ */ new Map();
365
+ for (const file of this.#files.values()) {
366
+ if (isReservedWorkspacePath(file.path)) continue;
367
+ for (const dir of parentDirectories(file.path)) if (this.#entryInPrefix(dir, prefix, options)) entries.set(dir, {
368
+ path: dir,
369
+ type: "directory"
370
+ });
371
+ if (this.#entryInPrefix(file.path, prefix, options)) entries.set(file.path, await this.#fileEntry(file));
372
+ }
373
+ return [...entries.values()].sort((a, b) => a.path.localeCompare(b.path));
374
+ }
375
+ #entryInPrefix(path, prefix, options) {
376
+ if (!prefix) return options.recursive || !path.includes("/");
377
+ if (path === prefix) return false;
378
+ if (!path.startsWith(`${prefix}/`)) return false;
379
+ return options.recursive || !path.slice(prefix.length + 1).includes("/");
380
+ }
381
+ async #fileEntry(file) {
382
+ return {
383
+ digest: file.gitSha,
384
+ mediaType: file.mediaType,
385
+ metadata: await this.#fileMetadata(file),
386
+ path: file.path,
387
+ size: file.size,
388
+ type: "file"
389
+ };
390
+ }
391
+ #directoryExists(path) {
392
+ return this.#publicDescendants(path).length > 0;
393
+ }
394
+ #publicDescendants(path) {
395
+ return [...this.#files.keys()].filter((key) => !isReservedWorkspacePath(key) && key.startsWith(`${path}/`));
396
+ }
397
+ #metaPath(key) {
398
+ return normalizeSafeWorkspacePath(`.vitehub/meta/${normalizeSafeWorkspacePath(key.endsWith(".json") ? key : `${key}.json`, { allowReserved: true })}`, { allowReserved: true });
399
+ }
400
+ #toRemoteFiles() {
401
+ return new Map([...this.#files.values()].map((file) => [file.path, {
402
+ path: joinGitPath(this.#root, file.path),
403
+ sha: file.gitSha,
404
+ size: file.size,
405
+ type: "blob",
406
+ mode: gitHubFileMode(file.metadata)
407
+ }]));
408
+ }
409
+ };
410
+ function createGitHubWorkspaceStore(options, workspaceName) {
411
+ return new GitHubWorkspaceStore(options, workspaceName);
412
+ }
413
+ //#endregion
414
+ export { diffSnapshots as i, createCurrentSnapshotFromStore as n, createSnapshotFromEntries as r, createGitHubWorkspaceStore as t };
@@ -0,0 +1,269 @@
1
+ import { d as sha256, n as contentStreamToBytes, p as workspaceError } from "./path-CNI6wKIU.js";
2
+ import { a as normalizeWorkspaceSources, n as createSourceContext, s as sourceMountContainsPath } from "./config-CZLO0m9h.js";
3
+ import { a as sourceSyncMetaKey, c as normalizeSourceItemPath, i as readWorkspaceSourceSyncState, o as workspaceSourceSyncStateEquals } from "./workspace-C4k92Ow8.js";
4
+ //#region src/sources/sync.ts
5
+ const sourceSyncLocks = /* @__PURE__ */ new Map();
6
+ function zeroCounts() {
7
+ return {
8
+ added: 0,
9
+ removed: 0,
10
+ unchanged: 0,
11
+ updated: 0
12
+ };
13
+ }
14
+ function countPath(counts, status) {
15
+ counts[status]++;
16
+ }
17
+ async function contentFromItem(item) {
18
+ if (item.contentStream) {
19
+ if (typeof item.content !== "undefined" || typeof item.data !== "undefined") throw workspaceError("[vitehub] Workspace source items cannot define contentStream with content or data.");
20
+ return await contentStreamToBytes(item.contentStream);
21
+ }
22
+ return item.content ?? (typeof item.data === "undefined" ? "" : JSON.stringify(item.data, null, 2));
23
+ }
24
+ async function sourceConfigHash(source) {
25
+ return await sha256({
26
+ key: source.key,
27
+ mountPath: source.mountPath,
28
+ source: source.source.fingerprint,
29
+ sync: source.sync
30
+ });
31
+ }
32
+ function sourceLockKey(definition, source) {
33
+ return `${definition.name}\0${source.key}`;
34
+ }
35
+ function lockSkippedStatus(source) {
36
+ return {
37
+ counts: zeroCounts(),
38
+ mountPath: source.mountPath,
39
+ source: source.key,
40
+ status: "skipped"
41
+ };
42
+ }
43
+ function resultStatus(sources) {
44
+ if (sources.some((source) => source.status === "error")) return sources.some((source) => source.status === "ready") ? "partial" : "error";
45
+ if (sources.every((source) => source.status === "skipped")) return "skipped";
46
+ return "ready";
47
+ }
48
+ function selectedSyncSources(definition, options) {
49
+ const sources = normalizeWorkspaceSources(definition.sources).filter((source) => source.sync);
50
+ if (options.sources === "all") return sources;
51
+ return [...new Set(options.sources)].map((key) => {
52
+ const source = sources.find((item) => item.key === key);
53
+ if (!source) throw workspaceError(normalizeWorkspaceSources(definition.sources).some((item) => item.key === key) ? `[vitehub] Workspace source ${JSON.stringify(key)} is not configured for Source Sync. Add sync: true to the source binding.` : `[vitehub] Workspace source ${JSON.stringify(key)} does not exist.`);
54
+ return source;
55
+ });
56
+ }
57
+ async function getSourceItems(source, ctx) {
58
+ await source.source.prepare?.(ctx);
59
+ if (source.source.getItems) return await source.source.getItems(ctx);
60
+ return await Promise.all((await source.source.getKeys(ctx)).map(async (key) => await source.source.getItem(key, ctx)));
61
+ }
62
+ async function shouldRemoveStalePath(store, path, metadata) {
63
+ const file = await store.readFile(path);
64
+ if (!file) return false;
65
+ return await sha256(file.content) === metadata.digest;
66
+ }
67
+ async function planSourceSync(definition, store, source) {
68
+ const ctx = createSourceContext(definition, source);
69
+ const [previousState, configHash, items] = await Promise.all([
70
+ store.getMeta?.(sourceSyncMetaKey(source.key)).then(readWorkspaceSourceSyncState),
71
+ sourceConfigHash(source),
72
+ getSourceItems(source, ctx)
73
+ ]);
74
+ const counts = zeroCounts();
75
+ const paths = [];
76
+ const files = [];
77
+ const nextPaths = {};
78
+ for (const item of items) {
79
+ const { path, sourcePath } = normalizeSourceItemPath(source, item, { operation: "Source Sync" });
80
+ if (nextPaths[path]) throw workspaceError(`[vitehub] Workspace Source Sync produced duplicate path: ${path}.`);
81
+ const content = await contentFromItem(item);
82
+ const digest = await sha256(content);
83
+ const existing = await store.readFile(path);
84
+ const existingDigest = existing ? await sha256(existing.content) : void 0;
85
+ const status = existing ? existingDigest === digest ? "unchanged" : "updated" : "added";
86
+ countPath(counts, status);
87
+ paths.push({
88
+ path,
89
+ sourcePath,
90
+ status
91
+ });
92
+ nextPaths[path] = {
93
+ digest,
94
+ mediaType: item.mediaType,
95
+ sourcePath
96
+ };
97
+ files.push({
98
+ path,
99
+ content,
100
+ mediaType: item.mediaType,
101
+ metadata: {
102
+ ...item.metadata,
103
+ source: source.key,
104
+ sourcePath
105
+ }
106
+ });
107
+ }
108
+ const removals = [];
109
+ if (source.sync && source.sync.stale === "remove" && previousState) for (const [path, metadata] of Object.entries(previousState.paths)) {
110
+ if (nextPaths[path]) continue;
111
+ if (!await shouldRemoveStalePath(store, path, metadata)) continue;
112
+ const removal = {
113
+ path,
114
+ sourcePath: metadata.sourcePath,
115
+ status: "removed"
116
+ };
117
+ removals.push(removal);
118
+ paths.push(removal);
119
+ countPath(counts, "removed");
120
+ }
121
+ const nextState = {
122
+ configHash,
123
+ mountPath: source.mountPath,
124
+ paths: nextPaths,
125
+ source: source.key
126
+ };
127
+ return {
128
+ counts,
129
+ files,
130
+ nextState,
131
+ paths,
132
+ removals,
133
+ source,
134
+ stateChanged: !workspaceSourceSyncStateEquals(previousState, nextState)
135
+ };
136
+ }
137
+ async function applySourceSyncPlan(store, plan) {
138
+ if (plan.source.mountPath) await store.mkdir(plan.source.mountPath, { recursive: true });
139
+ for (const file of plan.files) await store.writeFile(file.path, file);
140
+ for (const removal of plan.removals) await store.rm(removal.path, { force: true });
141
+ await pruneEmptySourceDirectories(store, plan.source, plan.removals);
142
+ if (plan.stateChanged) await store.setMeta?.(sourceSyncMetaKey(plan.source.key), plan.nextState);
143
+ }
144
+ async function pruneEmptySourceDirectories(store, source, removals) {
145
+ const directories = /* @__PURE__ */ new Set();
146
+ for (const removal of removals) for (const directory of parentDirectories(removal.path)) {
147
+ if (directory === source.mountPath) continue;
148
+ if (source.mountPath && !sourceMountContainsPath(source, directory)) continue;
149
+ directories.add(directory);
150
+ }
151
+ for (const directory of [...directories].sort((left, right) => right.length - left.length)) {
152
+ if ((await store.stat(directory))?.type !== "directory") continue;
153
+ if ((await store.list(directory)).length > 0) continue;
154
+ await store.rm(directory, {
155
+ force: true,
156
+ recursive: true
157
+ });
158
+ }
159
+ }
160
+ function parentDirectories(path) {
161
+ const parts = path.split("/").filter(Boolean);
162
+ const directories = [];
163
+ for (let index = parts.length - 1; index > 0; index--) directories.push(parts.slice(0, index).join("/"));
164
+ return directories;
165
+ }
166
+ function statusFromPlan(plan, details) {
167
+ return {
168
+ counts: plan.counts,
169
+ mountPath: plan.source.mountPath,
170
+ paths: details === "paths" ? plan.paths : void 0,
171
+ source: plan.source.key,
172
+ status: "ready"
173
+ };
174
+ }
175
+ async function snapshotSyncedWorkspace(definition, store, options) {
176
+ if (!(!!options.snapshot || !!options.publish)) return;
177
+ const snapshotOptions = typeof options.snapshot === "object" ? options.snapshot : {};
178
+ const snapshot = await store.snapshot(normalizeSnapshotOptions(snapshotOptions));
179
+ if (options.publish) {
180
+ const { publishWorkspaceSnapshot } = await import("./lifecycle-BYoa9hVb.js").then((n) => n.t);
181
+ await publishWorkspaceSnapshot(definition, store, snapshot);
182
+ }
183
+ return snapshot;
184
+ }
185
+ function normalizeSnapshotOptions(options) {
186
+ if (!options || typeof options !== "object") return { name: "source-sync" };
187
+ return { name: options.name || options.message || "source-sync" };
188
+ }
189
+ async function syncWorkspaceSourcesUnlocked(definition, store, options, sources, initialStatuses, started) {
190
+ const statuses = [...initialStatuses];
191
+ const plans = [];
192
+ for (const source of sources) try {
193
+ plans.push(await planSourceSync(definition, store, source));
194
+ } catch (error) {
195
+ statuses.push({
196
+ counts: zeroCounts(),
197
+ error: error instanceof Error ? error.message : String(error),
198
+ mountPath: source.mountPath,
199
+ source: source.key,
200
+ status: "error"
201
+ });
202
+ }
203
+ if (statuses.some((status) => status.status === "error") && !options.publishPartial) return {
204
+ durationMs: Date.now() - started,
205
+ published: false,
206
+ sources: [...statuses, ...plans.map((plan) => ({
207
+ counts: plan.counts,
208
+ mountPath: plan.source.mountPath,
209
+ paths: options.details === "paths" ? plan.paths : void 0,
210
+ source: plan.source.key,
211
+ status: "skipped"
212
+ }))],
213
+ status: resultStatus(statuses)
214
+ };
215
+ for (const plan of plans) await applySourceSyncPlan(store, plan);
216
+ const planStatuses = plans.map((plan) => statusFromPlan(plan, options.details));
217
+ const resultSources = [...statuses, ...planStatuses];
218
+ const snapshot = resultStatus(resultSources) === "ready" || options.publishPartial && planStatuses.length > 0 ? await snapshotSyncedWorkspace(definition, store, options) : void 0;
219
+ return {
220
+ durationMs: Date.now() - started,
221
+ published: !!options.publish && !!snapshot,
222
+ snapshot,
223
+ sources: resultSources,
224
+ status: resultStatus(resultSources)
225
+ };
226
+ }
227
+ async function syncWorkspaceSources(definition, store, options) {
228
+ if (!options || !options.sources) throw workspaceError("[vitehub] workspace.sync({ sources }) requires an explicit Source selection.");
229
+ if (!store.getMeta || !store.setMeta) throw workspaceError("[vitehub] Workspace Source Sync requires a Workspace Store with metadata support.");
230
+ const started = Date.now();
231
+ const sources = selectedSyncSources(definition, options);
232
+ if (sources.length === 0) return {
233
+ durationMs: 0,
234
+ published: false,
235
+ sources: [],
236
+ status: "skipped"
237
+ };
238
+ const statuses = [];
239
+ const runnableSources = [];
240
+ for (const source of sources) {
241
+ const key = sourceLockKey(definition, source);
242
+ let existing = sourceSyncLocks.get(key);
243
+ while (existing) {
244
+ if (source.sync && source.sync.concurrency === "skip") {
245
+ statuses.push(lockSkippedStatus(source));
246
+ break;
247
+ }
248
+ await existing.catch(() => void 0);
249
+ existing = sourceSyncLocks.get(key);
250
+ }
251
+ if (!statuses.some((status) => status.source === source.key)) runnableSources.push(source);
252
+ }
253
+ if (runnableSources.length === 0) return {
254
+ durationMs: Date.now() - started,
255
+ published: false,
256
+ sources: statuses,
257
+ status: resultStatus(statuses)
258
+ };
259
+ const lockKeys = runnableSources.map((source) => sourceLockKey(definition, source)).sort();
260
+ const promise = syncWorkspaceSourcesUnlocked(definition, store, options, runnableSources, statuses, started);
261
+ for (const key of lockKeys) sourceSyncLocks.set(key, promise);
262
+ try {
263
+ return await promise;
264
+ } finally {
265
+ for (const key of lockKeys) if (sourceSyncLocks.get(key) === promise) sourceSyncLocks.delete(key);
266
+ }
267
+ }
268
+ //#endregion
269
+ export { syncWorkspaceSources };
@@ -0,0 +1,11 @@
1
+ //#region src/storage/target.ts
2
+ const workspaceStoreTarget = Symbol.for("vitehub.workspace.storeTarget");
3
+ function forwardWorkspaceStoreTarget(source, target) {
4
+ const resolveTarget = source[workspaceStoreTarget];
5
+ if (resolveTarget) target[workspaceStoreTarget] = resolveTarget.bind(source);
6
+ }
7
+ async function resolveWorkspaceStoreTarget(source) {
8
+ return await source[workspaceStoreTarget]?.();
9
+ }
10
+ //#endregion
11
+ export { resolveWorkspaceStoreTarget as n, workspaceStoreTarget as r, forwardWorkspaceStoreTarget as t };
package/dist/test.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as registerWorkspace } from "./registry-D4Qzq26I.js";
1
+ import { n as registerWorkspace } from "./registry-BIQVCBWI.js";
2
2
  export { registerWorkspace };
package/dist/test.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as registerWorkspace } from "./registry-Cnr0NoKv.js";
1
+ import { n as registerWorkspace } from "./registry-CqyDTW9Y.js";
2
2
  export { registerWorkspace };