@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
@@ -1,7 +1,11 @@
1
- import { t as WorkspaceError } from "./errors-BUL8SoFS.js";
2
- import { c as resolveInside, l as sha256, o as normalizeWorkspacePath, r as matchesAny, t as contentToBytes } from "./path-BVv9OXhg.js";
1
+ import { a as matchesAny, c as normalizeWorkspacePath, d as sha256, p as workspaceError, r as contentToBytes, t as contentStreamChunks, u as resolveInside } from "./path-CNI6wKIU.js";
2
+ import { t as createGitHubWorkspaceStore } from "./store-Bs1SLh55.js";
3
3
  import { resolve } from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
4
5
  import { defu } from "defu";
6
+ import { createReadStream, createWriteStream } from "node:fs";
7
+ import { Readable, Transform } from "node:stream";
8
+ import { pipeline } from "node:stream/promises";
5
9
  //#region ../internal/src/env.ts
6
10
  function trimmed(value) {
7
11
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
@@ -14,21 +18,29 @@ function readEnv(env, ...names) {
14
18
  }
15
19
  //#endregion
16
20
  //#region src/runtime/config.ts
17
- let workspaceRuntimeConfig = false;
21
+ const workspaceRuntimeConfigKey = Symbol.for("vitehub.workspace.runtimeConfig");
22
+ function workspaceRuntimeConfigGlobal() {
23
+ const scope = globalThis;
24
+ scope[workspaceRuntimeConfigKey] ??= false;
25
+ return scope;
26
+ }
18
27
  function setWorkspaceRuntimeConfig(config) {
19
- workspaceRuntimeConfig = config;
28
+ workspaceRuntimeConfigGlobal()[workspaceRuntimeConfigKey] = config;
20
29
  }
21
30
  function getWorkspaceRuntimeConfig() {
22
- return workspaceRuntimeConfig;
31
+ return workspaceRuntimeConfigGlobal()[workspaceRuntimeConfigKey] ?? false;
23
32
  }
24
33
  //#endregion
25
34
  //#region src/runtime/hosted-store-loader.ts
26
- let workspaceHostedStoreLoader;
35
+ const workspaceHostedStoreLoaderKey = Symbol.for("vitehub.workspace.hostedStoreLoader");
36
+ function workspaceHostedStoreLoaderGlobal() {
37
+ return globalThis;
38
+ }
27
39
  function setWorkspaceHostedStoreLoader(loader) {
28
- workspaceHostedStoreLoader = loader;
40
+ workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey] = loader;
29
41
  }
30
42
  function getWorkspaceHostedStoreLoader() {
31
- return workspaceHostedStoreLoader;
43
+ return workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey];
32
44
  }
33
45
  //#endregion
34
46
  //#region src/storage/local.ts
@@ -43,7 +55,7 @@ async function walk(root, current = root) {
43
55
  for (const dirent of dirents) {
44
56
  const absolute = `${current}/${dirent.name}`;
45
57
  const path = normalizeWorkspacePath(relative(root, absolute));
46
- const { stat, readFile } = await import("node:fs/promises");
58
+ const { stat } = await import("node:fs/promises");
47
59
  const info = await stat(absolute).catch((error) => {
48
60
  if (error.code === "ENOENT") return void 0;
49
61
  throw error;
@@ -58,20 +70,27 @@ async function walk(root, current = root) {
58
70
  entries.push(...await walk(root, absolute));
59
71
  continue;
60
72
  }
61
- if (dirent.isFile()) {
62
- const bytes = await readFile(absolute);
63
- entries.push({
64
- path,
65
- type: "file",
66
- size: info.size,
67
- mtime: info.mtimeMs,
68
- digest: await sha256(bytes)
69
- });
70
- }
73
+ if (dirent.isFile()) entries.push({
74
+ path,
75
+ type: "file",
76
+ size: info.size,
77
+ mtime: info.mtimeMs,
78
+ digest: await fileDigest(absolute)
79
+ });
71
80
  }
72
81
  return entries;
73
82
  }
83
+ async function fileDigest(path) {
84
+ return await new Promise((resolve, reject) => {
85
+ const hash = createHash("sha256");
86
+ const stream = createReadStream(path);
87
+ stream.on("data", (chunk) => hash.update(chunk));
88
+ stream.on("error", reject);
89
+ stream.on("end", () => resolve(hash.digest("hex")));
90
+ });
91
+ }
74
92
  var LocalWorkspaceStore = class {
93
+ root;
75
94
  #baseline;
76
95
  #files = /* @__PURE__ */ new Map();
77
96
  #meta = /* @__PURE__ */ new Map();
@@ -101,13 +120,74 @@ var LocalWorkspaceStore = class {
101
120
  const { dirname } = await import("node:path");
102
121
  const { mkdir, writeFile } = await import("node:fs/promises");
103
122
  const absolute = resolveInside(this.root, path);
123
+ const normalized = normalizeWorkspacePath(path);
124
+ const bytes = contentToBytes(file.content);
125
+ const digest = await sha256(bytes);
126
+ const existing = await this.stat(normalized);
127
+ if (existing?.type === "file" && existing.digest === digest) {
128
+ this.#files.set(normalized, {
129
+ mediaType: file.mediaType,
130
+ metadata: file.metadata
131
+ });
132
+ return;
133
+ }
104
134
  await mkdir(dirname(absolute), { recursive: true });
105
- await writeFile(absolute, contentToBytes(file.content));
106
- this.#files.set(normalizeWorkspacePath(path), {
135
+ await writeFile(absolute, bytes);
136
+ this.#files.set(normalized, {
107
137
  mediaType: file.mediaType,
108
138
  metadata: file.metadata
109
139
  });
110
140
  }
141
+ async writeFileStream(path, file) {
142
+ const { dirname } = await import("node:path");
143
+ const { mkdir, rename, rm } = await import("node:fs/promises");
144
+ const normalized = normalizeWorkspacePath(path);
145
+ const absolute = resolveInside(this.root, path);
146
+ const temp = `${absolute}.${process.pid}.${Date.now()}.tmp`;
147
+ const hash = createHash("sha256");
148
+ let size = 0;
149
+ await mkdir(dirname(absolute), { recursive: true });
150
+ try {
151
+ const hashing = new Transform({ transform(chunk, _encoding, callback) {
152
+ hash.update(chunk);
153
+ size += chunk.byteLength;
154
+ callback(void 0, chunk);
155
+ } });
156
+ await pipeline(Readable.from(contentStreamChunks(file.content)), hashing, createWriteStream(temp));
157
+ const digest = hash.digest("hex");
158
+ const existing = await this.stat(normalized);
159
+ if (existing?.type === "file" && existing.digest === digest) {
160
+ await rm(temp, { force: true });
161
+ this.#files.set(normalized, {
162
+ mediaType: file.mediaType,
163
+ metadata: file.metadata
164
+ });
165
+ return {
166
+ ...existing,
167
+ mediaType: file.mediaType,
168
+ metadata: file.metadata,
169
+ size,
170
+ digest
171
+ };
172
+ }
173
+ await rename(temp, absolute);
174
+ this.#files.set(normalized, {
175
+ mediaType: file.mediaType,
176
+ metadata: file.metadata
177
+ });
178
+ return {
179
+ path: normalized,
180
+ type: "file",
181
+ size,
182
+ mediaType: file.mediaType,
183
+ metadata: file.metadata,
184
+ digest
185
+ };
186
+ } catch (error) {
187
+ await rm(temp, { force: true }).catch(() => void 0);
188
+ throw error;
189
+ }
190
+ }
111
191
  async list(prefix = "", options = {}) {
112
192
  const normalizedPrefix = normalizeWorkspacePath(prefix);
113
193
  return (await walk(this.root)).filter((entry) => {
@@ -117,7 +197,8 @@ var LocalWorkspaceStore = class {
117
197
  return options.recursive || !entry.path.slice(normalizedPrefix.length + 1).includes("/");
118
198
  }).map((entry) => ({
119
199
  ...entry,
120
- mediaType: entry.type === "file" ? this.#files.get(entry.path)?.mediaType : entry.mediaType
200
+ mediaType: entry.type === "file" ? this.#files.get(entry.path)?.mediaType : entry.mediaType,
201
+ metadata: entry.type === "file" ? this.#files.get(entry.path)?.metadata : entry.metadata
121
202
  })).sort((a, b) => a.path.localeCompare(b.path));
122
203
  }
123
204
  async glob(pattern, _options = {}) {
@@ -125,7 +206,7 @@ var LocalWorkspaceStore = class {
125
206
  return (await this.list("", { recursive: true })).filter((entry) => entry.type === "file" && patterns.some((item) => matchesAny(entry.path, item)));
126
207
  }
127
208
  async stat(path) {
128
- const { readFile, stat } = await import("node:fs/promises");
209
+ const { stat } = await import("node:fs/promises");
129
210
  const normalized = normalizeWorkspacePath(path);
130
211
  const absolute = resolveInside(this.root, normalized);
131
212
  const info = await stat(absolute).catch((error) => {
@@ -139,7 +220,8 @@ var LocalWorkspaceStore = class {
139
220
  size: info.isFile() ? info.size : void 0,
140
221
  mtime: info.mtimeMs,
141
222
  mediaType: info.isFile() ? this.#files.get(normalized)?.mediaType : void 0,
142
- digest: info.isFile() ? await sha256(await readFile(absolute)) : void 0
223
+ metadata: info.isFile() ? this.#files.get(normalized)?.metadata : void 0,
224
+ digest: info.isFile() ? await fileDigest(absolute) : void 0
143
225
  };
144
226
  }
145
227
  async mkdir(path, options = {}) {
@@ -183,7 +265,7 @@ var LocalWorkspaceStore = class {
183
265
  type: "removed",
184
266
  before
185
267
  });
186
- else if (before && after && (before.digest !== after.digest || before.type !== after.type || before.size !== after.size)) entries.push({
268
+ 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({
187
269
  path,
188
270
  type: "modified",
189
271
  before,
@@ -210,6 +292,7 @@ var LocalWorkspaceStore = class {
210
292
  for (const entry of await this.list("", { recursive: true })) entries[entry.path] = {
211
293
  type: entry.type,
212
294
  digest: entry.digest,
295
+ metadata: entry.metadata,
213
296
  size: entry.size
214
297
  };
215
298
  return {
@@ -238,13 +321,20 @@ var LocalWorkspaceStore = class {
238
321
  }
239
322
  async #writeMeta() {
240
323
  const { dirname } = await import("node:path");
241
- const { mkdir, writeFile } = await import("node:fs/promises");
324
+ const { mkdir, rename, rm, writeFile } = await import("node:fs/promises");
325
+ const temp = `${this.#metaPath}.${randomUUID()}.tmp`;
242
326
  await mkdir(dirname(this.#metaPath), { recursive: true });
243
- await writeFile(this.#metaPath, JSON.stringify(Object.fromEntries(this.#meta), null, 2));
327
+ try {
328
+ await writeFile(temp, JSON.stringify(Object.fromEntries(this.#meta), null, 2));
329
+ await rename(temp, this.#metaPath);
330
+ } catch (error) {
331
+ await rm(temp, { force: true }).catch(() => void 0);
332
+ throw error;
333
+ }
244
334
  }
245
335
  };
246
336
  function createLocalWorkspaceStore(root) {
247
- if (!root) throw new WorkspaceError("[vitehub] Local workspace store requires a root directory.");
337
+ if (!root) throw workspaceError("[vitehub] Local workspace store requires a root directory.");
248
338
  return new LocalWorkspaceStore(root);
249
339
  }
250
340
  //#endregion
@@ -315,10 +405,10 @@ var MemoryWorkspaceStore = class {
315
405
  const node = this.#nodes.get(normalized);
316
406
  if (!node) {
317
407
  if (options.force) return;
318
- throw new WorkspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
408
+ throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
319
409
  }
320
410
  if (node.type === "directory" && !options.recursive) {
321
- for (const key of this.#nodes.keys()) if (key.startsWith(`${normalized}/`)) throw new WorkspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
411
+ for (const key of this.#nodes.keys()) if (key.startsWith(`${normalized}/`)) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
322
412
  }
323
413
  for (const key of this.#nodes.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#nodes.delete(key);
324
414
  }
@@ -345,7 +435,7 @@ var MemoryWorkspaceStore = class {
345
435
  type: "removed",
346
436
  before
347
437
  });
348
- else if (before && after && (before.digest !== after.digest || before.type !== after.type || before.size !== after.size)) entries.push({
438
+ 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({
349
439
  path,
350
440
  type: "modified",
351
441
  before,
@@ -383,6 +473,7 @@ var MemoryWorkspaceStore = class {
383
473
  size,
384
474
  mtime: node.mtime,
385
475
  mediaType: node.mediaType,
476
+ metadata: node.metadata,
386
477
  digest: node.type === "file" ? await sha256(content) : void 0
387
478
  };
388
479
  }
@@ -394,6 +485,7 @@ var MemoryWorkspaceStore = class {
394
485
  entries[path] = {
395
486
  type: entry.type,
396
487
  digest: entry.digest,
488
+ metadata: entry.metadata,
397
489
  size: entry.size
398
490
  };
399
491
  }
@@ -418,6 +510,9 @@ const MASKED_WORKSPACE_RUNTIME_VALUE = "********";
418
510
  function workspaceRepoName(name) {
419
511
  return name ? name.replace(/[^a-zA-Z0-9_.-]/g, "-") : void 0;
420
512
  }
513
+ function gitHubWorkspaceOption(value) {
514
+ return typeof value === "function" ? value : trimmed(value);
515
+ }
421
516
  function resolveCloudflareArtifactsStore(config = {}, env = process.env) {
422
517
  const repoPrefix = trimmed(config.repoPrefix) ?? readEnv(env, "WORKSPACE_ARTIFACTS_REPO_PREFIX", "VITEHUB_WORKSPACE_ARTIFACTS_REPO_PREFIX") ?? "vitehub-workspace-";
423
518
  const repo = trimmed(config.repo) ?? workspaceRepoName(readEnv(env, "WORKSPACE_ARTIFACTS_REPO", "VITEHUB_WORKSPACE_ARTIFACTS_REPO"));
@@ -429,7 +524,6 @@ function resolveCloudflareArtifactsStore(config = {}, env = process.env) {
429
524
  repoPrefix
430
525
  }, {
431
526
  binding: "WORKSPACE_ARTIFACTS",
432
- branch: "main",
433
527
  namespace: "vitehub",
434
528
  provider: "cloudflare-artifacts"
435
529
  });
@@ -442,6 +536,15 @@ function resolveVercelBlobWorkspaceStore(config = {}, env = process.env) {
442
536
  token: MASKED_WORKSPACE_RUNTIME_VALUE
443
537
  };
444
538
  }
539
+ function resolveGitHubWorkspaceStore(config = {}, env = process.env, input = {}) {
540
+ return {
541
+ branch: gitHubWorkspaceOption(config.branch) ?? readEnv(env, "WORKSPACE_GITHUB_BRANCH", "VITEHUB_WORKSPACE_GITHUB_BRANCH", "GITHUB_BRANCH") ?? "main",
542
+ provider: "github",
543
+ repository: gitHubWorkspaceOption(config.repository) ?? gitHubWorkspaceOption(config.repo) ?? readEnv(env, "WORKSPACE_GITHUB_REPOSITORY", "VITEHUB_WORKSPACE_GITHUB_REPOSITORY", "GITHUB_REPOSITORY"),
544
+ root: gitHubWorkspaceOption(config.root) ?? readEnv(env, "WORKSPACE_GITHUB_ROOT", "VITEHUB_WORKSPACE_GITHUB_ROOT") ?? ".vitehub/workspaces/<workspace>",
545
+ token: input.runtime ? gitHubWorkspaceOption(config.token) ?? "********" : MASKED_WORKSPACE_RUNTIME_VALUE
546
+ };
547
+ }
445
548
  function hasVercelWorkspaceBlobEnv(env) {
446
549
  return Boolean(readEnv(env, "BLOB_READ_WRITE_TOKEN"));
447
550
  }
@@ -451,10 +554,11 @@ function normalizeWorkspaceStoreOptions(store, input = {}) {
451
554
  const env = input.env || process.env;
452
555
  const hosting = input.hosting || "";
453
556
  if (store?.provider === "cloudflare-artifacts") return resolveCloudflareArtifactsStore(store, env);
557
+ if (store?.provider === "github") return resolveGitHubWorkspaceStore(store, env, input);
454
558
  if (store?.provider === "memory") return store;
455
559
  if (store?.provider === "vercel-blob") return resolveVercelBlobWorkspaceStore(store, env);
456
560
  if (store?.provider === "local" || store?.root) return defu(store, { provider: "local" });
457
- if (store && "provider" in store) throw new WorkspaceError(`[vitehub] Unsupported workspace store provider: ${String(store.provider)}.`);
561
+ if (store && "provider" in store) throw workspaceError(`[vitehub] Unsupported workspace store provider: ${String(store.provider)}.`);
458
562
  if (hosting.includes("cloudflare")) return { provider: "memory" };
459
563
  if (hasVercelWorkspaceBlobEnv(env)) return resolveVercelBlobWorkspaceStore({}, env);
460
564
  if (hosting.includes("vercel")) return { provider: "memory" };
@@ -467,14 +571,15 @@ function createWorkspaceStoreFromProvider(definition) {
467
571
  const runtimeStore = runtimeConfig ? runtimeConfig.store : void 0;
468
572
  const store = normalizeWorkspaceStoreOptions(definition.store || runtimeStore, {
469
573
  env: typeof process !== "undefined" ? process.env : {},
470
- hosting: typeof process !== "undefined" ? process.env.VITEHUB_HOSTING || process.env.NITRO_PRESET : void 0,
574
+ hosting: typeof process !== "undefined" ? process.env.VITEHUB_HOSTING : void 0,
471
575
  rootDir,
472
576
  runtime: true
473
577
  });
474
578
  if (store?.provider === "memory") return createMemoryWorkspaceStore();
475
- if (store?.provider === "cloudflare-artifacts" || store?.provider === "vercel-blob") {
579
+ if (store?.provider === "cloudflare-artifacts" || store?.provider === "github" || store?.provider === "vercel-blob") {
476
580
  const loader = getWorkspaceHostedStoreLoader();
477
- if (!loader) throw new WorkspaceError(`[vitehub] Hosted workspace store "${store.provider}" is not available in this runtime.`);
581
+ if (!loader && store.provider === "github") return createGitHubWorkspaceStore(store, definition.name);
582
+ if (!loader) throw workspaceError(`[vitehub] Hosted workspace store "${store.provider}" is not available in this runtime.`);
478
583
  return loader(store, definition.name);
479
584
  }
480
585
  return createLocalWorkspaceStore(store?.root ? resolve(rootDir, store.root) : runtimeConfig ? resolve(runtimeConfig.root, definition.name) : resolve(rootDir, ".vitehub/workspaces", definition.name));
@@ -491,4 +596,4 @@ function resolveRuntimeVercelBlobWorkspaceStore(config, env) {
491
596
  };
492
597
  }
493
598
  //#endregion
494
- export { getWorkspaceHostedStoreLoader as a, setWorkspaceRuntimeConfig as c, createMemoryWorkspaceStore as i, normalizeWorkspaceStoreOptions as n, setWorkspaceHostedStoreLoader as o, resolveRuntimeVercelBlobWorkspaceStore as r, getWorkspaceRuntimeConfig as s, createWorkspaceStoreFromProvider as t };
599
+ export { resolveRuntimeVercelBlobWorkspaceStore as a, getWorkspaceHostedStoreLoader as c, setWorkspaceRuntimeConfig as d, resolveGitHubWorkspaceStore as i, setWorkspaceHostedStoreLoader as l, normalizeWorkspaceStoreOptions as n, resolveVercelBlobWorkspaceStore as o, resolveCloudflareArtifactsStore as r, createMemoryWorkspaceStore as s, createWorkspaceStoreFromProvider as t, getWorkspaceRuntimeConfig as u };
@@ -0,0 +1,6 @@
1
+ import { Jt as WorkspaceStore, o as GitHubWorkspaceStoreOptions } from "../../types-60Yn149G.js";
2
+
3
+ //#region src/providers/github/store.d.ts
4
+ declare function createGitHubWorkspaceStore(options: GitHubWorkspaceStoreOptions, workspaceName: string): WorkspaceStore;
5
+ //#endregion
6
+ export { createGitHubWorkspaceStore };
@@ -0,0 +1,2 @@
1
+ import { t as createGitHubWorkspaceStore } from "../../store-Bs1SLh55.js";
2
+ export { createGitHubWorkspaceStore };
package/dist/publish.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { J as WorkspacePublisher } from "./types-CwNcWTdt.js";
1
+ import { a as GitHubWorkspaceOption, ct as WorkspacePublisher } from "./types-60Yn149G.js";
2
2
 
3
3
  //#region src/publishers/manifest.d.ts
4
4
  interface ManifestPublisherOptions {
@@ -7,9 +7,10 @@ interface ManifestPublisherOptions {
7
7
  declare function manifest(options?: ManifestPublisherOptions): WorkspacePublisher;
8
8
  //#endregion
9
9
  //#region src/publishers/github.d.ts
10
- type GitHubPublisherOption = string | (() => string | undefined);
10
+ type GitHubPublisherOption = GitHubWorkspaceOption;
11
11
  interface GitHubPublisherOptions {
12
12
  branch?: GitHubPublisherOption;
13
+ deleteUntracked?: boolean;
13
14
  message?: GitHubPublisherOption;
14
15
  repo?: GitHubPublisherOption;
15
16
  repository?: GitHubPublisherOption;
package/dist/publish.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as WorkspaceError } from "./errors-BUL8SoFS.js";
2
- import { o as normalizeWorkspacePath, t as contentToBytes } from "./path-BVv9OXhg.js";
3
- import { t as getActiveCloudflareBinding } from "./cloudflare-env-DL94Uvpz.js";
1
+ import { c as normalizeWorkspacePath, p as workspaceError } from "./path-CNI6wKIU.js";
2
+ import { n as resolveWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
3
+ import { a as isWorkspaceFileEntry, d as resolveGitHubBranchOption, f as resolveGitHubOption, h as resolveGitHubTokenOption, l as readGitHubBranchState, m as resolveGitHubRootOption, p as resolveGitHubRepositoryOption, r as createGitHubFileUpdate, t as commitGitHubChanges, u as requireGitHubOption } from "./shared-jfogBrd5.js";
4
4
  import { dirname, resolve } from "node:path";
5
5
  import { mkdir, writeFile } from "node:fs/promises";
6
6
  //#region src/publishers/manifest.ts
@@ -20,163 +20,69 @@ function manifest(options = {}) {
20
20
  }
21
21
  //#endregion
22
22
  //#region src/publishers/github.ts
23
- function processEnv(...keys) {
24
- const env = typeof process !== "undefined" ? process.env : void 0;
25
- return keys.map((key) => env?.[key]).find((value) => typeof value === "string" && value.length > 0);
26
- }
27
- function resolveOption(value) {
28
- return typeof value === "function" ? value() : value;
29
- }
30
- function requireOption(label, value) {
31
- if (!value) throw new WorkspaceError(`[vitehub] GitHub workspace publisher requires ${label}.`);
32
- return value;
33
- }
34
- function splitRepository(repository) {
35
- const [owner, repo] = repository.split("/");
36
- if (!owner || !repo) throw new WorkspaceError("[vitehub] GitHub workspace publisher requires a repository in owner/repo format.");
37
- return {
38
- owner,
39
- repo
40
- };
41
- }
42
- function joinGitPath(...parts) {
43
- return parts.join("/").replaceAll("\\", "/").split("/").filter(Boolean).join("/");
44
- }
45
- function workspacePathFromGitPath(path, root) {
46
- const normalized = joinGitPath(path);
47
- const normalizedRoot = joinGitPath(root);
48
- if (!normalizedRoot) return normalizeWorkspacePath(normalized);
49
- if (!normalized.startsWith(`${normalizedRoot}/`)) return void 0;
50
- return normalizeWorkspacePath(normalized.slice(normalizedRoot.length + 1));
51
- }
52
- function isFileEntry(entry) {
53
- return entry.type === "file";
54
- }
55
- function toHex(bytes) {
56
- return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
57
- }
58
- async function gitBlobSha(bytes) {
59
- const prefix = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
60
- const input = new Uint8Array(prefix.byteLength + bytes.byteLength);
61
- input.set(prefix);
62
- input.set(bytes, prefix.byteLength);
63
- return toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-1", input)));
64
- }
65
- function toBase64(bytes) {
66
- let binary = "";
67
- for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
68
- const encode = globalThis.btoa;
69
- return encode ? encode(binary) : Buffer.from(bytes).toString("base64");
70
- }
71
- function resolveRepository(options) {
72
- return resolveOption(options.repository) || resolveOption(options.repo) || processEnv("WORKSPACE_GITHUB_REPOSITORY", "VITEHUB_WORKSPACE_GITHUB_REPOSITORY", "GITHUB_REPOSITORY");
73
- }
74
- function resolveBranch(options) {
75
- return resolveOption(options.branch) || processEnv("WORKSPACE_GITHUB_BRANCH", "VITEHUB_WORKSPACE_GITHUB_BRANCH", "GITHUB_BRANCH") || "main";
76
- }
77
- function resolveRoot(options, workspaceName) {
78
- return resolveOption(options.root) || processEnv("WORKSPACE_GITHUB_ROOT", "VITEHUB_WORKSPACE_GITHUB_ROOT") || `.vitehub/workspaces/${workspaceName}`;
79
- }
80
- function resolveToken(options) {
81
- return resolveOption(options.token) || getActiveCloudflareBinding("GITHUB_TOKEN") || processEnv("WORKSPACE_GITHUB_TOKEN", "VITEHUB_WORKSPACE_GITHUB_TOKEN", "GITHUB_TOKEN");
82
- }
83
23
  function resolveMessage(options, ctx) {
84
- return ctx.snapshot?.name || resolveOption(options.message) || "chore: update workspace snapshot";
24
+ return ctx.snapshot?.name || resolveGitHubOption(options.message) || "chore: update workspace snapshot";
25
+ }
26
+ async function resolveActiveGitHubStoreTarget(ctx) {
27
+ const target = await resolveWorkspaceStoreTarget(ctx.store);
28
+ if (target) return target.provider === "github" ? target : void 0;
29
+ const configuredStore = ctx.workspace.store;
30
+ if (configuredStore && "provider" in configuredStore && configuredStore.provider === "github") {
31
+ const repository = resolveGitHubRepositoryOption(configuredStore);
32
+ if (repository) return {
33
+ provider: "github",
34
+ branch: resolveGitHubBranchOption(configuredStore),
35
+ repository
36
+ };
37
+ }
85
38
  }
86
39
  async function readFiles(ctx, root) {
87
40
  const entries = await ctx.store.list("", { recursive: true });
88
- return await Promise.all(entries.filter(isFileEntry).map(async (entry) => {
41
+ return await Promise.all(entries.filter(isWorkspaceFileEntry).map(async (entry) => {
89
42
  const file = await ctx.store.readFile(entry.path);
90
- if (!file) throw new WorkspaceError(`[vitehub] Workspace file disappeared before GitHub publish: ${entry.path}.`);
91
- const bytes = contentToBytes(file.content);
43
+ if (!file) throw workspaceError(`[vitehub] Workspace file disappeared before GitHub publish: ${entry.path}.`);
44
+ const update = await createGitHubFileUpdate(entry.path, root, file.content);
92
45
  return {
93
46
  ...file,
94
- bytes,
95
47
  path: normalizeWorkspacePath(entry.path),
96
- fullPath: joinGitPath(root, entry.path),
97
- gitSha: await gitBlobSha(bytes)
48
+ ...update
98
49
  };
99
50
  }));
100
51
  }
101
- async function requestGitHubJson(repo, token, path, init) {
102
- const response = await fetch(`https://api.github.com${path}`, {
103
- ...init,
104
- headers: {
105
- accept: "application/vnd.github+json",
106
- authorization: `Bearer ${token}`,
107
- "content-type": "application/json",
108
- "user-agent": "vitehub-workspace",
109
- "x-github-api-version": "2022-11-28",
110
- ...init?.headers
111
- }
112
- });
113
- if (!response.ok) throw new WorkspaceError(`[vitehub] GitHub workspace publisher request failed for ${repo}: ${response.status} ${response.statusText} ${await response.text().catch(() => "")}`);
114
- return await response.json();
115
- }
116
- function findRemoteFiles(tree, root) {
117
- if (tree.truncated) throw new WorkspaceError("[vitehub] GitHub workspace publisher could not compare the remote tree because GitHub returned a truncated tree.");
118
- const files = /* @__PURE__ */ new Map();
119
- for (const entry of tree.tree) {
120
- if (entry.type !== "blob" || !entry.sha) continue;
121
- const path = workspacePathFromGitPath(entry.path, root);
122
- if (path) files.set(path, entry);
123
- }
124
- return files;
125
- }
126
52
  function github(options = {}) {
127
53
  return {
128
54
  name: "github",
129
55
  async publish(ctx) {
130
- const repository = requireOption("a repository", resolveRepository(options));
131
- const branch = resolveBranch(options);
132
- const root = resolveRoot(options, ctx.workspace.name);
133
- const token = requireOption("a token", resolveToken(options));
56
+ const repository = requireGitHubOption("publisher", "a repository", resolveGitHubRepositoryOption(options));
57
+ const branch = resolveGitHubBranchOption(options);
58
+ const root = resolveGitHubRootOption(options, ctx.workspace.name);
59
+ const token = requireGitHubOption("publisher", "a token", resolveGitHubTokenOption(options));
60
+ const storeTarget = await resolveActiveGitHubStoreTarget(ctx);
61
+ if (!ctx.durable && storeTarget?.repository === repository && storeTarget.branch === branch) throw workspaceError(`[vitehub] GitHub publisher cannot publish to ${repository}@${branch} while it backs the active GitHub Workspace Store. Use workspace.snapshot() for that branch or configure the publisher to use a different repository or branch.`);
134
62
  const files = await readFiles(ctx, root);
135
63
  const nextPaths = new Set(files.map((file) => file.path));
136
- const { owner, repo } = splitRepository(repository);
137
- const refPath = `/repos/${owner}/${repo}/git/ref/heads/${branch}`;
138
- const refsPath = `/repos/${owner}/${repo}/git/refs/heads/${branch}`;
139
- const ref = await requestGitHubJson(repository, token, refPath);
140
- const current = await requestGitHubJson(repository, token, `/repos/${owner}/${repo}/git/commits/${ref.object.sha}`);
141
- const remoteFiles = findRemoteFiles(await requestGitHubJson(repository, token, `/repos/${owner}/${repo}/git/trees/${current.tree.sha}?recursive=1`), root);
142
- const changedFiles = files.filter((file) => remoteFiles.get(file.path)?.sha !== file.gitSha);
143
- const deletedEntries = [...remoteFiles].filter(([path]) => !nextPaths.has(path)).map(([, entry]) => ({
144
- mode: "100644",
145
- path: entry.path,
146
- sha: null,
147
- type: "blob"
148
- }));
149
- if (!changedFiles.length && !deletedEntries.length) return;
150
- const blobs = await Promise.all(changedFiles.map((file) => requestGitHubJson(repository, token, `/repos/${owner}/${repo}/git/blobs`, {
151
- body: JSON.stringify({
152
- content: toBase64(file.bytes),
153
- encoding: "base64"
154
- }),
155
- method: "POST"
156
- })));
157
- const tree = await requestGitHubJson(repository, token, `/repos/${owner}/${repo}/git/trees`, {
158
- body: JSON.stringify({
159
- base_tree: current.tree.sha,
160
- tree: [...changedFiles.map((file, index) => ({
161
- mode: "100644",
162
- path: file.fullPath,
163
- sha: blobs[index].sha,
164
- type: "blob"
165
- })), ...deletedEntries]
166
- }),
167
- method: "POST"
168
- });
169
- const commit = await requestGitHubJson(repository, token, `/repos/${owner}/${repo}/git/commits`, {
170
- body: JSON.stringify({
171
- message: resolveMessage(options, ctx),
172
- parents: [ref.object.sha],
173
- tree: tree.sha
174
- }),
175
- method: "POST"
64
+ const remote = await readGitHubBranchState({
65
+ branch,
66
+ kind: "publisher",
67
+ paths: options.deleteUntracked === false ? files.map((file) => file.path) : void 0,
68
+ repository,
69
+ root,
70
+ token
176
71
  });
177
- await requestGitHubJson(repository, token, refsPath, {
178
- body: JSON.stringify({ sha: commit.sha }),
179
- method: "PATCH"
72
+ const changedFiles = files.filter((file) => remote.files.get(file.path)?.sha !== file.gitSha);
73
+ const deletePaths = options.deleteUntracked === false ? [] : [...remote.files].filter(([path]) => !nextPaths.has(path)).map(([, entry]) => entry.path);
74
+ if (!changedFiles.length && !deletePaths.length) return;
75
+ await commitGitHubChanges({
76
+ baseTreeSha: remote.treeSha,
77
+ branch,
78
+ branchExists: remote.branchExists,
79
+ deletePaths,
80
+ files: changedFiles,
81
+ kind: "publisher",
82
+ message: resolveMessage(options, ctx),
83
+ parentSha: remote.refSha,
84
+ repository,
85
+ token
180
86
  });
181
87
  }
182
88
  };
@@ -1,4 +1,4 @@
1
- import { k as WorkspaceDefinitionInput } from "./types-CwNcWTdt.js";
1
+ import { F as WorkspaceDefinitionInput, P as WorkspaceDefinition } from "./types-60Yn149G.js";
2
2
 
3
3
  //#region src/core/registry.d.ts
4
4
  type WorkspaceRegistryModule = {
@@ -6,5 +6,6 @@ type WorkspaceRegistryModule = {
6
6
  };
7
7
  type WorkspaceRegistry = Record<string, () => Promise<WorkspaceRegistryModule>>;
8
8
  declare function registerWorkspace(name: string, definition: WorkspaceDefinitionInput): void;
9
+ declare function resolveRegisteredWorkspaceDefinition(name: string): Promise<WorkspaceDefinition>;
9
10
  //#endregion
10
- export { registerWorkspace as n, WorkspaceRegistry as t };
11
+ export { registerWorkspace as n, resolveRegisteredWorkspaceDefinition as r, WorkspaceRegistry as t };