@vite-hub/workspace 0.1.0 → 0.3.1

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 (134) hide show
  1. package/README.md +164 -107
  2. package/dist/abort-BCwpdrN0.js +32 -0
  3. package/dist/blob-database.d.ts +70 -117
  4. package/dist/blob-database.js +48 -41
  5. package/dist/checkout.d.ts +128 -0
  6. package/dist/checkout.js +849 -0
  7. package/dist/cloudflare.d.ts +2 -2
  8. package/dist/cloudflare.js +1 -1
  9. package/dist/config-B-863EgC.js +15 -0
  10. package/dist/{config-B7dmzDX3.js → config-BAgL2dtB.js} +48 -84
  11. package/dist/{config-DLKdaFWN.d.ts → config-BQKcPawI.d.ts} +1 -1
  12. package/dist/discard-CNNtCozM.js +8 -0
  13. package/dist/durability.d.ts +22 -0
  14. package/dist/durability.js +70 -0
  15. package/dist/error-diagnostics-CtKjGtGb.js +188 -0
  16. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  17. package/dist/file-2pFYNtsU.js +22 -0
  18. package/dist/{files-C7Px8uaC.js → files-BOo4SbwE.js} +2 -2
  19. package/dist/files.d.ts +38 -0
  20. package/dist/files.js +6 -0
  21. package/dist/{github-CPxHtFB7.js → github-CrYp4v8k.js} +32 -5
  22. package/dist/{glob--XcLlcml.js → glob-B8YGvTrZ.js} +4 -5
  23. package/dist/{glob--kNYDbfU.js → glob-Cjxms1t7.js} +1 -1
  24. package/dist/{host-CFnrTXTK.js → host-BFBpXn0N.js} +58 -47
  25. package/dist/{hosted-acMA5XyL.js → hosted-KcUR_jPv.js} +216 -93
  26. package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
  27. package/dist/hosted-vercel-blob.d.ts +2 -2
  28. package/dist/hosted-vercel-blob.js +1 -1
  29. package/dist/hosted.d.ts +5 -3
  30. package/dist/hosted.js +2 -2
  31. package/dist/index.d.ts +9 -51
  32. package/dist/index.js +21 -91
  33. package/dist/{lifecycle-BwZ7c9hb.js → lifecycle-B-enk_4A.js} +8 -8
  34. package/dist/lineage.d.ts +26 -0
  35. package/dist/lineage.js +76 -0
  36. package/dist/loader.d.ts +1 -1
  37. package/dist/loader.js +2 -2
  38. package/dist/{mcp-resources-BREFCmtn.js → mcp-resources-DF0F5rcL.js} +2 -2
  39. package/dist/{memory-BbwOqDXl.js → memory-BOexthyW.js} +3 -4
  40. package/dist/{metadata-target-DZEZQGHA.js → metadata-target-CWz6KHKq.js} +17 -16
  41. package/dist/object-Da1zyPCR.js +11 -0
  42. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  43. package/dist/operations-C6FpR8Rr.js +389 -0
  44. package/dist/operations-CE2drFih.js +1234 -0
  45. package/dist/operations.d.ts +41 -4
  46. package/dist/operations.js +3 -2
  47. package/dist/{path-CNAwN7pw.js → path--wrT_Azm.js} +2 -3
  48. package/dist/path-AxMho1wo.d.ts +7 -0
  49. package/dist/{plugins-DqQ8b4T5.d.ts → plugins-C8C0auoW.d.ts} +1 -1
  50. package/dist/{provider-kXjfli9u.js → provider-9s4Ufkm5.js} +104 -82
  51. package/dist/providers/github/store.d.ts +1 -1
  52. package/dist/providers/github/store.js +1 -1
  53. package/dist/registry-B3BBm4Ts.d.ts +19 -0
  54. package/dist/{registry-Bp-8UUfG.js → registry-CNphafBx.js} +55 -20
  55. package/dist/registry-CYNN623b.d.ts +9 -0
  56. package/dist/request-scope-Dw5n8bMC.js +83 -0
  57. package/dist/results-DgkZUmTL.js +8 -0
  58. package/dist/{rolldown-runtime-B4iAMlE-.js → rolldown-runtime-rQ84J-ij.js} +2 -3
  59. package/dist/runtime/assets.d.ts +1 -1
  60. package/dist/runtime/assets.js +3 -3
  61. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  62. package/dist/runtime/empty-registry.d.ts +2 -1
  63. package/dist/runtime/registry.d.ts +2 -0
  64. package/dist/runtime/registry.js +23 -0
  65. package/dist/runtime/request.d.ts +4 -0
  66. package/dist/runtime/request.js +8 -0
  67. package/dist/runtime/state.d.ts +5 -4
  68. package/dist/runtime/state.js +8 -18
  69. package/dist/runtime/workspace.d.ts +1 -1
  70. package/dist/runtime/workspace.js +1 -1
  71. package/dist/runtime.d.ts +9 -8
  72. package/dist/runtime.js +23 -26
  73. package/dist/{search-CrTmXj5h.js → search-C_RfoM2j.js} +2 -2
  74. package/dist/{server-BNQ-Nbjj.js → server-8tGltlGz.js} +53 -40
  75. package/dist/server.d.ts +17 -8
  76. package/dist/server.js +1 -1
  77. package/dist/shared-B3_EUk89.js +848 -0
  78. package/dist/source-metadata.d.ts +6 -2
  79. package/dist/source-metadata.js +8 -8
  80. package/dist/state-BISnUf1s.d.ts +35 -0
  81. package/dist/{ai-BZyLwULx.js → state-DbrW-njQ.js} +96 -54
  82. package/dist/{store-CXgmu-uw.js → store-ybhyD38Z.js} +250 -106
  83. package/dist/{sync-CN6ec-5M.js → sync-CCD_VYC8.js} +4 -4
  84. package/dist/target-jWhTdIuF.js +89 -0
  85. package/dist/test.d.ts +1 -1
  86. package/dist/test.js +1 -1
  87. package/dist/{types-DeK9GIxy.d.ts → types-BbtwmBZ5.d.ts} +68 -14
  88. package/dist/use-C6lV3-wC.d.ts +321 -0
  89. package/dist/{use-BQj7nSz6.js → use-CSpT5W87.js} +75 -82
  90. package/dist/{utils-Blrh4N2n.js → utils-CgMZCHsX.js} +112 -41
  91. package/dist/vite.d.ts +585 -2
  92. package/dist/vite.js +21368 -1
  93. package/dist/{workspace-BWJQBK1u.d.ts → workspace-CYB2xZ1T.d.ts} +1 -1
  94. package/dist/{workspace-6pxkOuxr.js → workspace-sPWn2Jxj.js} +125 -40
  95. package/package.json +46 -55
  96. package/dist/ai-BW2ZhizI.d.ts +0 -177
  97. package/dist/ai.d.ts +0 -3
  98. package/dist/ai.js +0 -2
  99. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +0 -19
  100. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  101. package/dist/error-diagnostics-DY5GP47p.js +0 -96
  102. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +0 -354
  103. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +0 -214
  104. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +0 -527
  105. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +0 -248
  106. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +0 -179
  107. package/dist/file-C0_aPWSS.js +0 -26
  108. package/dist/file-metadata-CxDy-E2H.js +0 -58
  109. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +0 -2278
  110. package/dist/github-DtncTfmv-Du2S8lGF.js +0 -4159
  111. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +0 -2530
  112. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +0 -489
  113. package/dist/hosted-vercel-blob-DKntsHaf.js +0 -12603
  114. package/dist/inspect-BoObD2cJ.js +0 -167
  115. package/dist/mountx.d.ts +0 -8
  116. package/dist/mountx.js +0 -145
  117. package/dist/nitro.d.ts +0 -2
  118. package/dist/nitro.js +0 -2
  119. package/dist/nuxt.d.ts +0 -27
  120. package/dist/nuxt.js +0 -38
  121. package/dist/operations-BcpWr41m.js +0 -159
  122. package/dist/operations-CGqY1XeG.js +0 -965
  123. package/dist/operations-DnOwKsJT.d.ts +0 -136
  124. package/dist/registry-Cg1TJVVZ.d.ts +0 -10
  125. package/dist/request-execution-Dk9rY-Yh.js +0 -84
  126. package/dist/shared-DalXdP0i.js +0 -2158
  127. package/dist/state-B8zbLi5t.d.ts +0 -26
  128. package/dist/target-D4Bqb1eH.js +0 -11
  129. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +0 -125
  130. package/dist/token-CO62GglH.js +0 -61
  131. package/dist/use-DhwhbAVV.d.ts +0 -108
  132. package/dist/vite-BEvgU2GY.js +0 -20909
  133. package/dist/vite-CcZmMQ7S.d.ts +0 -476
  134. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +0 -1565
@@ -1,16 +1,55 @@
1
- import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
- import { c as normalizeSafeWorkspacePattern, f as sha256 } from "./path-CNAwN7pw.js";
3
- import { r as workspaceStoreTarget, t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
- import { a as copyWorkspacePath, i as appendWorkspaceFile, t as createWorkspaceTools } from "./ai-BZyLwULx.js";
5
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
6
- import { r as getWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-Dk9rY-Yh.js";
7
- import { d as normalizeHistoryRef, f as requireWorkspaceHistory, l as historyConflict, p as validateHistoryMessage } from "./utils-Blrh4N2n.js";
8
- import { i as assertPublicWorkspaceMetaKey, t as createWorkspace } from "./workspace-6pxkOuxr.js";
9
- import { c as workspaceInternalMetadataCapability, o as resolveWorkspaceMetadataTarget, r as forwardWorkspaceMetadataTarget, t as attachWorkspaceMetadataTarget } from "./metadata-target-DZEZQGHA.js";
1
+ import { i as isWorkspaceError, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { n as resolveWorkspaceStoreTarget, r as workspaceStoreTarget, t as forwardWorkspaceStoreTarget } from "./target-jWhTdIuF.js";
3
+ import { c as normalizeSafeWorkspacePattern, f as sha256 } from "./path--wrT_Azm.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
5
+ import { d as normalizeHistoryRef, f as requireWorkspaceHistory, l as historyConflict, p as validateHistoryMessage } from "./utils-CgMZCHsX.js";
6
+ import { g as getWorkspaceSourceRequestExecution, i as assertPublicWorkspaceMetaKey, m as attachWorkspaceSourceRequestExecution, t as createWorkspace } from "./workspace-sPWn2Jxj.js";
7
+ import { c as workspaceInternalMetadataCapability, o as resolveWorkspaceMetadataTarget, r as forwardWorkspaceMetadataTarget, t as attachWorkspaceMetadataTarget } from "./metadata-target-CWz6KHKq.js";
8
+ import { o as useRegisteredWorkspace } from "./registry-CNphafBx.js";
10
9
  import { n as useWorkspaceAssets } from "./asset-registry-DfBV5kmw.js";
11
- import { a as useRegisteredWorkspace } from "./registry-Bp-8UUfG.js";
12
- import { t as createHostedWorkspaceSession } from "./host-CFnrTXTK.js";
10
+ import { t as createHostedWorkspaceSession } from "./host-BFBpXn0N.js";
13
11
  import { getViteHubErrorShape } from "@vite-hub/runtime";
12
+ import { posix } from "node:path";
13
+ //#region src/fs-ops.ts
14
+ async function ensureMissingOrReplaceable(workspace, path, overwrite = false) {
15
+ if (!await workspace.exists(path)) return;
16
+ if (!overwrite) throw workspaceError(`[vitehub] Workspace path already exists: ${path}.`);
17
+ await workspace.rm(path, {
18
+ recursive: true,
19
+ force: true
20
+ });
21
+ }
22
+ async function copyWorkspacePath(workspace, from, to, overwrite = false) {
23
+ if (from === to) throw workspaceError("[vitehub] Source and destination must be different.");
24
+ const source = await workspace.stat(from);
25
+ if (source.type === "directory" && to.startsWith(`${from}/`)) throw workspaceError("[vitehub] Destination cannot be nested inside the source directory.");
26
+ if (from.startsWith(`${to}/`)) throw workspaceError("[vitehub] Destination cannot contain the source.");
27
+ if (overwrite && await (await resolveWorkspaceStoreTarget(workspace))?.containsPath?.(to, from)) throw workspaceError("[vitehub] Destination cannot contain the source.");
28
+ await ensureMissingOrReplaceable(workspace, to, overwrite);
29
+ if (source.type === "file") {
30
+ const content = await workspace.readFile(from, { encoding: "binary" });
31
+ await workspace.writeFile(to, content, { mediaType: source.mediaType });
32
+ return;
33
+ }
34
+ const entries = await workspace.list(from, { recursive: true });
35
+ await workspace.mkdir(to, { recursive: true });
36
+ const directories = entries.filter((entry) => entry.type === "directory").sort((left, right) => left.path.length - right.path.length);
37
+ for (const entry of directories) await workspace.mkdir(posix.join(to, posix.relative(from, entry.path)), { recursive: true });
38
+ await Promise.all(entries.filter((entry) => entry.type === "file").map(async (entry) => {
39
+ const content = await workspace.readFile(entry.path, { encoding: "binary" });
40
+ await workspace.writeFile(posix.join(to, posix.relative(from, entry.path)), content, { mediaType: entry.mediaType });
41
+ }));
42
+ }
43
+ async function appendWorkspaceFile(workspace, path, content) {
44
+ let current = "";
45
+ try {
46
+ current = String(await workspace.readFile(path));
47
+ } catch (error) {
48
+ if (!isWorkspaceError(error)) throw error;
49
+ }
50
+ await workspace.writeFile(path, `${current}${content}`);
51
+ }
52
+ //#endregion
14
53
  //#region src/core/use.ts
15
54
  const workspaceDefinitionSyncStates = /* @__PURE__ */ new WeakMap();
16
55
  async function workspaceDefinitionSyncState(workspace) {
@@ -75,7 +114,10 @@ async function materializeWorkspaceSources(workspace, options) {
75
114
  function createLazyWorkspace(name, definition, options = {}) {
76
115
  let workspacePromise;
77
116
  async function resolveWorkspace() {
78
- workspacePromise ||= definition ? Promise.resolve(createWorkspace(definition, options)) : useRegisteredWorkspace(name, options);
117
+ workspacePromise ||= (definition ? Promise.resolve(createWorkspace(definition, options)) : useRegisteredWorkspace(name, options)).catch((error) => {
118
+ workspacePromise = void 0;
119
+ throw error;
120
+ });
79
121
  return await workspacePromise;
80
122
  }
81
123
  async function resolveSyncedWorkspace(abortSignal) {
@@ -382,58 +424,9 @@ function createReadonlyFs(name, workspace) {
382
424
  });
383
425
  return readonlyFs;
384
426
  }
385
- function toReadOperations(options) {
386
- return {
387
- list: options?.list,
388
- materialize: options?.materialize ?? true,
389
- read: options?.read,
390
- search: options?.search
391
- };
392
- }
393
- function toWriteOperations(options) {
394
- return {
395
- ...toReadOperations(options),
396
- write: {
397
- appendFile: options?.appendFile !== false,
398
- copyPath: options?.copyPath !== false,
399
- deletePath: options?.deletePath !== false,
400
- makeDir: options?.makeDir !== false,
401
- movePath: options?.movePath !== false,
402
- writeFile: options?.writeFile !== false
403
- }
404
- };
405
- }
406
- function createDefaultToolSet(createTools) {
407
- return createTools();
408
- }
409
- function emptyTools() {
410
- return {};
411
- }
412
- function useWorkspace(name, options) {
427
+ function createWorkspaceFileRuntime(name, options) {
413
428
  if (options?.mode === "write") {
414
429
  const workspace = createLazyWorkspace(name, options.definition);
415
- const createTools = (opts) => createWorkspaceTools(workspace, {
416
- broadSearchPaths: opts?.broadSearchPaths,
417
- cwd: opts?.cwd,
418
- maxShellCalls: opts?.maxShellCalls,
419
- maxOutputLength: opts?.maxOutputLength,
420
- operations: toWriteOperations(opts),
421
- sourceRequests: opts?.sourceRequests,
422
- timeout: opts?.timeout
423
- });
424
- const createReadTools = (opts) => createWorkspaceTools(createReadonlyFs(name, workspace), {
425
- broadSearchPaths: opts?.broadSearchPaths,
426
- cwd: opts?.cwd,
427
- maxShellCalls: opts?.maxShellCalls,
428
- maxOutputLength: opts?.maxOutputLength,
429
- operations: toReadOperations(opts),
430
- sourceRequests: opts?.sourceRequests,
431
- timeout: opts?.timeout
432
- });
433
- const tools = createDefaultToolSet(createTools);
434
- tools.inspect = createReadTools;
435
- tools.write = createTools;
436
- tools.none = emptyTools;
437
430
  const facade = {
438
431
  [workspaceStoreTarget]: async () => {
439
432
  return await workspace[workspaceStoreTarget]?.();
@@ -443,7 +436,10 @@ function useWorkspace(name, options) {
443
436
  fs: createWritableFs(name, workspace),
444
437
  history: {
445
438
  ...workspace.history,
446
- checkpoint: async (options) => await workspace.snapshot({ name: options?.message }),
439
+ checkpoint: async (options) => await workspace.snapshot({
440
+ name: options?.message,
441
+ ...options?.author ? { author: options.author } : {}
442
+ }),
447
443
  rebase: async (options) => await workspace.rebase(options)
448
444
  },
449
445
  getMeta: async (key) => await workspace.getMeta?.(key),
@@ -451,26 +447,17 @@ function useWorkspace(name, options) {
451
447
  setMeta: async (key, value, capability) => await workspace.setMeta?.(key, value, capability),
452
448
  snapshot: async (options) => await workspace.snapshot(options),
453
449
  startSession: async (options) => await workspace.startSession(options),
454
- sync: async (options) => await workspace.sync(options),
455
- tools
450
+ sync: async (options) => await workspace.sync(options)
456
451
  };
457
452
  forwardWorkspaceMetadataTarget(workspace, facade);
458
- return facade;
453
+ return {
454
+ mode: "write",
455
+ workspace,
456
+ facade
457
+ };
459
458
  }
460
459
  const workspace = createLazyWorkspace(name, options?.definition, { reuseStartupSnapshots: options?.refresh === false });
461
460
  const fs = createReadonlyFs(name, workspace);
462
- const createTools = (opts) => createWorkspaceTools(fs, {
463
- broadSearchPaths: opts?.broadSearchPaths,
464
- cwd: opts?.cwd,
465
- maxShellCalls: opts?.maxShellCalls,
466
- maxOutputLength: opts?.maxOutputLength,
467
- operations: toReadOperations(opts),
468
- sourceRequests: opts?.sourceRequests,
469
- timeout: opts?.timeout
470
- });
471
- const tools = createDefaultToolSet(createTools);
472
- tools.inspect = createTools;
473
- tools.none = emptyTools;
474
461
  const facade = {
475
462
  fs,
476
463
  history: {
@@ -480,12 +467,18 @@ function useWorkspace(name, options) {
480
467
  open: (id) => requireWorkspaceHistory(workspace).open(id),
481
468
  usage: () => requireWorkspaceHistory(workspace).usage()
482
469
  },
483
- getMeta: async (key) => await workspace.getMeta?.(key),
484
- tools
470
+ getMeta: async (key) => await workspace.getMeta?.(key)
485
471
  };
486
472
  forwardWorkspaceMetadataTarget(fs, facade);
487
473
  forwardWorkspaceStoreTarget(workspace, facade);
488
- return facade;
474
+ return {
475
+ mode: "read",
476
+ workspace,
477
+ facade
478
+ };
479
+ }
480
+ function useWorkspaceFiles(name, options) {
481
+ return createWorkspaceFileRuntime(name, options).facade;
489
482
  }
490
483
  //#endregion
491
- export { useWorkspace as t };
484
+ export { copyWorkspacePath as a, appendWorkspaceFile as i, createWorkspaceFileRuntime as n, useWorkspaceFiles as r, createReadonlyFs as t };
@@ -1,10 +1,10 @@
1
1
  import { a as workspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
- import { f as sha256, l as normalizeWorkspacePath, o as isWorkspaceBytes, r as contentToBytes } from "./path-CNAwN7pw.js";
3
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
4
- import { n as copyJsonWorkspaceMetadata, t as copyJsonFileMetadata } from "./file-metadata-CxDy-E2H.js";
5
- import { minimatch } from "minimatch";
6
- import { hasRuntimeType, isRuntimeObject } from "@vite-hub/runtime/internal/runtime-type";
2
+ import { a as cascadingRuleKeys, i as assertWorkspaceRules, o as copyJsonFileMetadata, s as copyJsonWorkspaceMetadata } from "./target-jWhTdIuF.js";
3
+ import { f as sha256, l as normalizeWorkspacePath, o as isWorkspaceBytes, r as contentToBytes } from "./path--wrT_Azm.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
7
5
  import { lookup } from "mrmime";
6
+ import { isRuntimeObject } from "@vite-hub/runtime/internal/runtime-type";
7
+ import { minimatch } from "minimatch";
8
8
  //#region src/core/plugins.ts
9
9
  const contributedPluginsKey = Symbol.for("vitehub.workspace.contributedPlugins");
10
10
  function contributedPluginState() {
@@ -21,8 +21,9 @@ function contributedPluginState() {
21
21
  * with the same id wins. The returned function removes this registration.
22
22
  */
23
23
  function registerWorkspacePlugin(workspace, plugin) {
24
- if (!hasRuntimeType(workspace, "string") || !workspace) throw workspaceErrorDiagnostics.WORKSPACE_R0022({ message: "[vitehub] registerWorkspacePlugin requires a Workspace name." });
25
- if (!plugin || !hasRuntimeType(plugin.id, "string") || !plugin.id) throw workspaceErrorDiagnostics.WORKSPACE_R0024({ message: "[vitehub] Workspace plugins require an id." });
24
+ if (typeof workspace !== "string" || !workspace) throw workspaceErrorDiagnostics.WORKSPACE_R0022({ message: "[vitehub] registerWorkspacePlugin requires a Workspace name." });
25
+ if (!plugin || typeof plugin.id !== "string" || !plugin.id) throw workspaceErrorDiagnostics.WORKSPACE_R0024({ message: "[vitehub] Workspace plugins require an id." });
26
+ assertWorkspaceRules(plugin.rules);
26
27
  const state = contributedPluginState();
27
28
  let plugins = state.plugins.get(workspace);
28
29
  if (!plugins) state.plugins.set(workspace, plugins = /* @__PURE__ */ new Map());
@@ -69,7 +70,29 @@ function mergeHooks(left = {}, right = {}) {
69
70
  "write:validate": [...toArray(left["write:validate"]), ...toArray(right["write:validate"])]
70
71
  };
71
72
  }
72
- function normalizeRules(rules = {}) {
73
+ /** Merges rules on the same pattern field by field. A later rule replaces only the fields it sets, and validators add up. */
74
+ function mergeRules(left, right = {}) {
75
+ assertWorkspaceRules(right);
76
+ const merged = { ...left };
77
+ for (const [pattern, rule] of Object.entries(right)) {
78
+ const previous = merged[pattern];
79
+ if (!previous) {
80
+ merged[pattern] = rule;
81
+ continue;
82
+ }
83
+ const next = {
84
+ ...previous,
85
+ validate: [...toArray(previous.validate), ...toArray(rule.validate)]
86
+ };
87
+ if (rule.commit !== void 0) next.commit = rule.commit;
88
+ if (rule.maxBytes !== void 0) next.maxBytes = rule.maxBytes;
89
+ if (rule.mediaType !== void 0) next.mediaType = rule.mediaType;
90
+ if (rule.write !== void 0) next.write = rule.write;
91
+ merged[pattern] = next;
92
+ }
93
+ return merged;
94
+ }
95
+ function normalizeRules(rules) {
73
96
  return Object.entries(rules).map(([pattern, rule]) => {
74
97
  const normalizedPattern = normalizeWorkspacePath(pattern);
75
98
  return {
@@ -86,28 +109,41 @@ function normalizePolicy(definition) {
86
109
  let rules = {};
87
110
  for (const plugin of workspaceDefinitionPlugins(definition)) {
88
111
  if (!plugin?.id) throw workspaceErrorDiagnostics.WORKSPACE_R0024({ message: "[vitehub] Workspace plugins require an id." });
89
- rules = {
90
- ...rules,
91
- ...plugin.rules
92
- };
112
+ rules = mergeRules(rules, plugin.rules);
93
113
  hooks = mergeHooks(hooks, plugin.hooks);
94
114
  }
95
- rules = {
96
- ...rules,
97
- ...definition.rules
98
- };
115
+ rules = mergeRules(rules, definition.rules);
99
116
  hooks = mergeHooks(hooks, definition.hooks);
100
117
  return {
101
118
  hooks,
102
119
  rules: normalizeRules(rules)
103
120
  };
104
121
  }
122
+ /**
123
+ * Resolves every rule that matches the path, from the least to the most specific. A more specific rule replaces a
124
+ * field only when it sets that field, so `"docs/**": { maxBytes }` keeps a broader `write: false`. Validators of every
125
+ * matching rule run, the least specific first.
126
+ */
105
127
  function matchRule(policy, path) {
106
128
  const normalized = normalizeWorkspacePath(path);
107
129
  let matched;
108
130
  for (const rule of policy.rules) {
109
131
  const globstarDirectory = rule.pattern.endsWith("/**") ? rule.pattern.slice(0, -3) : void 0;
110
- if (minimatch(normalized, rule.pattern, { dot: true }) || normalized === globstarDirectory) matched = rule;
132
+ if (!minimatch(normalized, rule.pattern, { dot: true }) && normalized !== globstarDirectory) continue;
133
+ matched ??= {
134
+ origins: {},
135
+ rule: {
136
+ pattern: rule.pattern,
137
+ validate: []
138
+ }
139
+ };
140
+ matched.rule.pattern = rule.pattern;
141
+ matched.rule.validate = [...matched.rule.validate, ...rule.validate];
142
+ for (const key of cascadingRuleKeys) {
143
+ if (rule[key] === void 0) continue;
144
+ matched.origins[key] = rule.pattern;
145
+ Object.assign(matched.rule, { [key]: rule[key] });
146
+ }
111
147
  }
112
148
  return matched;
113
149
  }
@@ -122,16 +158,30 @@ function writeAllowed(write, operation, exists) {
122
158
  function sizeOf(content) {
123
159
  return content === void 0 ? 0 : contentToBytes(content).byteLength;
124
160
  }
125
- function assertRuleAllows(input) {
126
- const rule = input.rule;
127
- if (!rule) return;
161
+ /** The media type that a file write stores: the one the caller passed, else the one its path implies. */
162
+ function writeMediaType(input) {
163
+ return input.mediaType || lookup(input.path) || "application/octet-stream";
164
+ }
165
+ function assertRuleAllows(input, matched) {
166
+ if (!matched) return;
167
+ const { origins, rule } = matched;
128
168
  const exists = Boolean(input.previous);
129
- if (!writeAllowed(rule.write, input.operation, exists)) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" does not allow ${input.operation} for ${input.path}.`);
130
- if (rule.maxBytes !== void 0 && sizeOf(input.content) > rule.maxBytes) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" limits writes to ${rule.maxBytes} bytes: ${input.path}.`);
131
- if (rule.mediaType && input.mediaType) {
132
- if (!(Array.isArray(rule.mediaType) ? rule.mediaType : [rule.mediaType]).includes(input.mediaType)) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" does not allow media type ${input.mediaType}: ${input.path}.`);
169
+ if (!writeAllowed(rule.write, input.operation, exists)) throw workspaceError(`[vitehub] Workspace rule "${origins.write}" does not allow ${input.operation} for ${input.path}.`);
170
+ if (rule.maxBytes !== void 0 && sizeOf(input.content) > rule.maxBytes) throw workspaceError(`[vitehub] Workspace rule "${origins.maxBytes}" limits writes to ${rule.maxBytes} bytes: ${input.path}.`);
171
+ if (rule.mediaType && input.operation === "writeFile") {
172
+ const allowed = Array.isArray(rule.mediaType) ? rule.mediaType : [rule.mediaType];
173
+ const mediaType = writeMediaType(input);
174
+ if (!allowed.includes(mediaType)) throw workspaceError(`[vitehub] Workspace rule "${origins.mediaType}" does not allow media type ${mediaType}: ${input.path}.`);
133
175
  }
134
176
  }
177
+ /** Stores the media type that the rule checked, so the stored file cannot get another type from the Store. */
178
+ function withCheckedMediaType(input, matched) {
179
+ if (!matched?.rule.mediaType || input.operation !== "writeFile" || input.mediaType) return input;
180
+ return {
181
+ ...input,
182
+ mediaType: writeMediaType(input)
183
+ };
184
+ }
135
185
  async function runHooks(hooks, name, input) {
136
186
  for (const hook of toArray(hooks[name])) await hook(input);
137
187
  }
@@ -159,16 +209,18 @@ function createWorkspaceWritePolicy(definition) {
159
209
  };
160
210
  return {
161
211
  check(input) {
212
+ const matched = matchRule(currentPolicy(), input.path);
162
213
  const checked = {
163
214
  ...input,
164
- rule: matchRule(currentPolicy(), input.path)
215
+ rule: matched?.rule
165
216
  };
166
- assertRuleAllows(checked);
167
- return checked;
217
+ assertRuleAllows(checked, matched);
218
+ return withCheckedMediaType(checked, matched);
168
219
  },
169
220
  async before(input) {
170
221
  const policy = currentPolicy();
171
- const rule = matchRule(policy, input.path);
222
+ const matched = matchRule(policy, input.path);
223
+ const rule = matched?.rule;
172
224
  let current = {
173
225
  ...input,
174
226
  rule
@@ -178,15 +230,15 @@ function createWorkspaceWritePolicy(definition) {
178
230
  ...current,
179
231
  rule
180
232
  };
181
- assertRuleAllows(current);
182
- if (current.rule?.validate.length) current = await runValidators(current.rule.validate, current);
233
+ assertRuleAllows(current, matched);
234
+ if (rule?.validate.length) current = await runValidators(rule.validate, current);
183
235
  await runHooks(policy.hooks, "write:validate", current);
184
236
  current = {
185
237
  ...current,
186
238
  rule
187
239
  };
188
- assertRuleAllows(current);
189
- return current;
240
+ assertRuleAllows(current, matched);
241
+ return withCheckedMediaType(current, matched);
190
242
  },
191
243
  async after(input) {
192
244
  await runHooks(currentPolicy().hooks, "write:after", input);
@@ -207,7 +259,7 @@ function resolveWorkspaceAutoCommit(definition, diff) {
207
259
  };
208
260
  const policy = normalizePolicy(definition);
209
261
  const paths = diff.entries.map((entry) => normalizeWorkspacePath(entry.path));
210
- const rules = paths.map((path) => matchRule(policy, path));
262
+ const rules = paths.map((path) => matchRule(policy, path)?.rule);
211
263
  if (!rules.length || rules.some((rule) => !rule?.commit)) return;
212
264
  return {
213
265
  message: rules.map((rule) => rule?.commit).find((commit) => typeof commit === "string" && commit.trim().length > 0)?.trim() || `chore: update ${definition.name} workspace`,
@@ -254,6 +306,11 @@ function forwardWorkspaceHistoryFiles(options) {
254
306
  forwardedHistoryCommits.add(forwarded);
255
307
  return forwarded;
256
308
  }
309
+ function deepFreeze(value) {
310
+ if (Object(value) !== value) return value;
311
+ for (const child of Object.values(Object(value))) deepFreeze(child);
312
+ return Object.freeze(value);
313
+ }
257
314
  function requireWorkspaceHistory(workspace) {
258
315
  if (!workspace.history) throw historyUnavailable();
259
316
  return workspace.history;
@@ -280,12 +337,12 @@ function createWorkspaceHistoryReader(history, complete) {
280
337
  };
281
338
  }
282
339
  function validateHistoryMessage(message) {
283
- if (message !== void 0 && !hasRuntimeType(message, "string")) throw workspaceError("[vitehub] History revision message must be a string.");
340
+ if (message !== void 0 && typeof message !== "string") throw workspaceError("[vitehub] History revision message must be a string.");
284
341
  }
285
342
  /** Resolve an optional ref name. Names use letters, numbers, `_` and `-`, joined by single `.` or `/`. */
286
343
  function normalizeHistoryRef(ref) {
287
344
  if (ref === void 0) return defaultWorkspaceHistoryRef;
288
- if (!hasRuntimeType(ref, "string") || ref.length > 128 || !historyRefPattern.test(ref)) throw workspaceErrorDiagnostics.WORKSPACE_R0071({ message: `[vitehub] Invalid history ref${hasRuntimeType(ref, "string") ? ` ${JSON.stringify(ref.slice(0, 128))}` : ""}. Use up to 128 letters, numbers, underscores, and dashes, separated by single dots or slashes.` });
345
+ if (typeof ref !== "string" || ref.length > 128 || !historyRefPattern.test(ref)) throw workspaceErrorDiagnostics.WORKSPACE_R0071({ message: `[vitehub] Invalid history ref${typeof ref === "string" ? ` ${JSON.stringify(ref.slice(0, 128))}` : ""}. Use up to 128 letters, numbers, underscores, and dashes, separated by single dots or slashes.` });
289
346
  return ref;
290
347
  }
291
348
  function normalizeHistoryPath(path) {
@@ -305,10 +362,10 @@ function readHistoryFiles(files, label) {
305
362
  for (const [path, value] of Object.entries(files)) {
306
363
  const normalized = normalizeHistoryPath(path);
307
364
  if (result.has(normalized)) throw workspaceError(`[vitehub] Duplicate history file path: ${normalized}.`);
308
- const input = !hasRuntimeType(value, "string") && !isWorkspaceBytes(value) && isRuntimeObject(value) ? value : void 0;
365
+ const input = typeof value !== "string" && !isWorkspaceBytes(value) && isRuntimeObject(value) ? value : void 0;
309
366
  const content = input ? input.content : value;
310
- if (!hasRuntimeType(content, "string") && !isWorkspaceBytes(content)) throw workspaceError(`[vitehub] Invalid history file content: ${normalized}.`);
311
- if (input?.mediaType !== void 0 && (!hasRuntimeType(input.mediaType, "string") || !input.mediaType)) throw workspaceError(`[vitehub] Invalid history file media type: ${normalized}.`);
367
+ if (typeof content !== "string" && !isWorkspaceBytes(content)) throw workspaceError(`[vitehub] Invalid history file content: ${normalized}.`);
368
+ if (input?.mediaType !== void 0 && (typeof input.mediaType !== "string" || !input.mediaType)) throw workspaceError(`[vitehub] Invalid history file media type: ${normalized}.`);
312
369
  result.set(normalized, {
313
370
  file: {
314
371
  path: normalized,
@@ -336,7 +393,7 @@ function readHistoryCommit(options) {
336
393
  if (remove !== void 0 && !Array.isArray(remove)) throw workspaceError("[vitehub] History changes.delete must be an array of file paths.");
337
394
  const deletes = /* @__PURE__ */ new Set();
338
395
  for (const path of remove ?? []) {
339
- if (!hasRuntimeType(path, "string")) throw workspaceError("[vitehub] History changes.delete must be an array of file paths.");
396
+ if (typeof path !== "string") throw workspaceError("[vitehub] History changes.delete must be an array of file paths.");
340
397
  const normalized = normalizeHistoryPath(path);
341
398
  if (deletes.has(normalized) || puts.has(normalized)) throw workspaceError(`[vitehub] Duplicate history file path: ${normalized}.`);
342
399
  deletes.add(normalized);
@@ -359,14 +416,14 @@ function createWorkspaceHistory(definition, store, files) {
359
416
  const retained = history();
360
417
  validateHistoryMessage(options.message);
361
418
  const ref = normalizeHistoryRef(options.ref);
362
- if (options.ifHead !== null && (!hasRuntimeType(options.ifHead, "string") || !options.ifHead)) throw workspaceError("[vitehub] History commit requires ifHead to be a revision id or null.");
419
+ if (options.ifHead !== null && (typeof options.ifHead !== "string" || !options.ifHead)) throw workspaceError("[vitehub] History commit requires ifHead to be a revision id or null.");
363
420
  const forwarded = forwardedHistoryCommits.has(options);
364
421
  const beforeWrite = forwarded ? policy.check : policy.before;
365
422
  const commit = readHistoryCommit(options);
366
423
  const metadata = copyJsonWorkspaceMetadata("history revision", options.metadata);
367
424
  const current = await retained.head({ ref });
368
425
  if ((current?.id ?? null) !== options.ifHead) throw historyConflict(ref, options.ifHead, current?.id ?? null);
369
- if (options.startFrom !== void 0 && (!hasRuntimeType(options.startFrom, "string") || !options.startFrom || options.ifHead !== null || !store.history?.forksFrom)) throw workspaceError("[vitehub] History commit startFrom needs a revision id, ifHead null, and a Store that starts missing refs from another ref.");
426
+ if (options.startFrom !== void 0 && (typeof options.startFrom !== "string" || !options.startFrom || options.ifHead !== null || !store.history?.forksFrom)) throw workspaceError("[vitehub] History commit startFrom needs a revision id, ifHead null, and a Store that starts missing refs from another ref.");
370
427
  const forkRef = current || options.startFrom ? void 0 : await store.history?.forksFrom?.(ref);
371
428
  const startId = current?.id ?? options.startFrom ?? (forkRef ? (await retained.head({ ref: forkRef }))?.id : void 0);
372
429
  const previous = startId ? await retained.open(startId) : void 0;
@@ -379,6 +436,7 @@ function createWorkspaceHistory(definition, store, files) {
379
436
  const deleted = [];
380
437
  const inputs = [];
381
438
  const grants = [];
439
+ const writes = [];
382
440
  for (const path of [...candidates].sort()) {
383
441
  const put = commit.puts.get(path);
384
442
  const file = put?.file;
@@ -392,8 +450,21 @@ function createWorkspaceHistory(definition, store, files) {
392
450
  };
393
451
  continue;
394
452
  }
453
+ writes.push({
454
+ path,
455
+ file,
456
+ before
457
+ });
458
+ }
459
+ const writeCommit = Object.freeze({
460
+ ...options.message === void 0 ? {} : { message: options.message },
461
+ metadata: deepFreeze(copyJsonWorkspaceMetadata("history revision", metadata) ?? {}),
462
+ paths: Object.freeze(writes.map((write) => write.path))
463
+ });
464
+ for (const { path, file, before } of writes) {
395
465
  const requested = await files.assertWritable(path);
396
466
  const input = await beforeWrite({
467
+ commit: writeCommit,
397
468
  content: file?.content,
398
469
  mediaType: file?.mediaType,
399
470
  metadata: file?.metadata,