@vite-hub/workspace 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -0,0 +1,234 @@
1
+ //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
+ /** The Standard Typed interface. This is a base type extended by other specs. */
3
+ interface StandardTypedV1<Input = unknown, Output = Input> {
4
+ /** The Standard properties. */
5
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
6
+ }
7
+ declare namespace StandardTypedV1 {
8
+ /** The Standard Typed properties interface. */
9
+ interface Props<Input = unknown, Output = Input> {
10
+ /** The version number of the standard. */
11
+ readonly version: 1;
12
+ /** The vendor name of the schema library. */
13
+ readonly vendor: string;
14
+ /** Inferred types associated with the schema. */
15
+ readonly types?: Types<Input, Output> | undefined;
16
+ }
17
+ /** The Standard Typed types interface. */
18
+ interface Types<Input = unknown, Output = Input> {
19
+ /** The input type of the schema. */
20
+ readonly input: Input;
21
+ /** The output type of the schema. */
22
+ readonly output: Output;
23
+ }
24
+ /** Infers the input type of a Standard Typed. */
25
+ type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
26
+ /** Infers the output type of a Standard Typed. */
27
+ type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
28
+ }
29
+ /** The Standard Schema interface. */
30
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
31
+ /** The Standard Schema properties. */
32
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
33
+ }
34
+ declare namespace StandardSchemaV1 {
35
+ /** The Standard Schema properties interface. */
36
+ interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
37
+ /** Validates unknown input values. */
38
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
39
+ }
40
+ /** The result interface of the validate function. */
41
+ type Result<Output> = SuccessResult<Output> | FailureResult;
42
+ /** The result interface if validation succeeds. */
43
+ interface SuccessResult<Output> {
44
+ /** The typed output value. */
45
+ readonly value: Output;
46
+ /** A falsy value for `issues` indicates success. */
47
+ readonly issues?: undefined;
48
+ }
49
+ interface Options {
50
+ /** Explicit support for additional vendor-specific parameters, if needed. */
51
+ readonly libraryOptions?: Record<string, unknown> | undefined;
52
+ }
53
+ /** The result interface if validation fails. */
54
+ interface FailureResult {
55
+ /** The issues of failed validation. */
56
+ readonly issues: ReadonlyArray<Issue>;
57
+ }
58
+ /** The issue interface of the failure output. */
59
+ interface Issue {
60
+ /** The error message of the issue. */
61
+ readonly message: string;
62
+ /** The path of the issue, if any. */
63
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
64
+ }
65
+ /** The path segment interface of the issue. */
66
+ interface PathSegment {
67
+ /** The key representing a path segment. */
68
+ readonly key: PropertyKey;
69
+ }
70
+ /** The Standard types interface. */
71
+ interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
72
+ /** Infers the input type of a Standard. */
73
+ type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
74
+ /** Infers the output type of a Standard. */
75
+ type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
+ }
77
+ //#endregion
78
+ //#region ../internal/src/operation-definition.d.ts
79
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
+ type OperationKind = "read" | "write" | "destructive";
81
+ /** The signed-in user of a call. */
82
+ interface OperationUser {
83
+ id: string;
84
+ name?: string;
85
+ email?: string;
86
+ image?: string;
87
+ [key: string]: unknown;
88
+ }
89
+ /** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
90
+ interface OperationActor {
91
+ id: string;
92
+ kind?: string;
93
+ label?: string;
94
+ meta?: object;
95
+ }
96
+ /** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
97
+ interface OperationAccess {
98
+ readonly mode: string;
99
+ /**
100
+ * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
101
+ * operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
102
+ * calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
103
+ * allows only the reads of that scope.
104
+ */
105
+ readonly sections: "all" | readonly string[];
106
+ readonly user?: OperationUser;
107
+ }
108
+ interface OperationContext {
109
+ /** The checked Console access of the call. */
110
+ access: OperationAccess;
111
+ /** The signed-in user, or null. */
112
+ user: OperationUser | null;
113
+ /** The Agent Actor when an agent calls on behalf of `user`. */
114
+ actor?: OperationActor;
115
+ surface: "console" | "cli" | "mcp" | "agent";
116
+ /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
+ development?: boolean;
118
+ env?: Record<string, unknown>;
119
+ waitUntil?: (task: Promise<unknown>) => void;
120
+ request?: Request;
121
+ /**
122
+ * The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
123
+ * with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
124
+ * of Comments.
125
+ */
126
+ event?: unknown;
127
+ /** Operations set a success status here, such as 202 for an accepted call. */
128
+ response?: {
129
+ status?: number;
130
+ };
131
+ /**
132
+ * An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
133
+ * only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
134
+ */
135
+ overrideLeases?: boolean;
136
+ /**
137
+ * What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
138
+ * threads that the Actor takes part in. `all`: every thread. Unset: none.
139
+ */
140
+ conversations?: "all" | "participant";
141
+ }
142
+ interface OperationDefinition<Input, Output> {
143
+ /** `<section>.<verb>`, such as `content.publish`. Unique per app. */
144
+ name: string;
145
+ /** One sentence. Becomes the CLI help line and the MCP tool description. */
146
+ description: string;
147
+ /**
148
+ * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
149
+ * from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
150
+ * scope and read-only grants. A function that returns an invalid id denies the call.
151
+ */
152
+ section: string | false | ((input: Input) => string | undefined);
153
+ /**
154
+ * The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
155
+ * the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
156
+ * `:` needs the whole section.
157
+ */
158
+ scope?: (input: Input) => string | undefined;
159
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
160
+ kind: OperationKind;
161
+ /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
162
+ input: StandardSchemaV1<unknown, Input>;
163
+ output?: StandardSchemaV1<unknown, Output>;
164
+ cli?: {
165
+ /** Defaults: namespace = section, command = verb. */
166
+ namespace?: string;
167
+ /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
168
+ command?: string;
169
+ /** Input keys read from positional arguments, in order. */
170
+ positional?: string[];
171
+ /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
172
+ format?: (output: Output) => string;
173
+ /** `vitehub <namespace>` runs this command when no command is named. */
174
+ default?: boolean;
175
+ };
176
+ /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
177
+ maxRequestBytes?: number;
178
+ /**
179
+ * Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
180
+ * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
181
+ */
182
+ readOnlyWhen?: (input: Input) => boolean;
183
+ /**
184
+ * How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
185
+ * Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
186
+ * result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
187
+ * is the result as JSON.
188
+ */
189
+ mcp?: false | {
190
+ title?: string;
191
+ format?: (output: NoInfer<Output>) => string;
192
+ };
193
+ /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
194
+ user?: false;
195
+ /**
196
+ * The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
197
+ * when `console.invoke` is on, which is the default in development and off in a production build.
198
+ */
199
+ invoke?: true;
200
+ run: (input: Input, context: OperationContext) => Output | Promise<Output>;
201
+ }
202
+ /** An operation of any input and output, as a registry holds it. */
203
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
204
+ readOnlyWhen?: (input: never) => boolean;
205
+ cli?: {
206
+ namespace?: string;
207
+ command?: string;
208
+ default?: boolean;
209
+ positional?: string[];
210
+ format?: (output: never) => string;
211
+ };
212
+ mcp?: false | {
213
+ title?: string;
214
+ format?: (output: never) => string;
215
+ };
216
+ input: StandardSchemaV1;
217
+ output?: StandardSchemaV1;
218
+ run: (input: never, context: OperationContext) => unknown;
219
+ scope?: (input: never) => string | undefined;
220
+ section: string | false | ((input: never) => string | undefined);
221
+ }
222
+ /** The contribution of one plugin: operations, or a module that exports them. */
223
+ interface OperationContributionEntry {
224
+ /** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
225
+ module: string;
226
+ /** Named export that holds an operation or an array of operations. Defaults to `default`. */
227
+ export?: string;
228
+ /** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
229
+ load?: () => Promise<unknown>;
230
+ /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
231
+ runtime?: false;
232
+ }
233
+ //#endregion
234
+ export { OperationContributionEntry as n, AnyOperation as t };
@@ -0,0 +1,389 @@
1
+ import { a as workspaceConflict } from "./path-DrSIenjj.js";
2
+ import { r as contentToBytes } from "./path--wrT_Azm.js";
3
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
4
+ import { u as normalizeHistoryPath } from "./utils-CgMZCHsX.js";
5
+ import { readDerivedFrom, staleDerivedFiles } from "./lineage.js";
6
+ import { r as useWorkspaceFiles } from "./use-CSpT5W87.js";
7
+ import { s as redactInspectionText } from "./operations-CE2drFih.js";
8
+ //#region src/runtime/operations.ts
9
+ const invalidRequestCodes = /* @__PURE__ */ new Set([
10
+ "WORKSPACE_HISTORY_INVALID",
11
+ "WORKSPACE_PATH_INVALID",
12
+ "WORKSPACE_R0070",
13
+ "WORKSPACE_R0071"
14
+ ]);
15
+ /** Gives an operation error the HTTP status and the redacted message that the CLI and the Console report. */
16
+ function withStatus(error, status, message = error.message) {
17
+ return Object.defineProperties(error, {
18
+ status: {
19
+ configurable: true,
20
+ enumerable: false,
21
+ value: status,
22
+ writable: true
23
+ },
24
+ statusMessage: {
25
+ configurable: true,
26
+ enumerable: false,
27
+ value: redactInspectionText(message),
28
+ writable: true
29
+ }
30
+ });
31
+ }
32
+ /** The status of each Workspace code that the operations throw. A failure that sets its own client status keeps it. */
33
+ const operationStatus = {
34
+ WORKSPACE_CONFLICT: 409,
35
+ WORKSPACE_FORBIDDEN: 403,
36
+ WORKSPACE_HISTORY_INVALID: 400,
37
+ WORKSPACE_NOT_FOUND: 404
38
+ };
39
+ /** Reads the code of a ViteHub error or a Workspace diagnostic. */
40
+ function errorCode(error) {
41
+ const code = Object(error) === error ? Reflect.get(Object(error), "code") : void 0;
42
+ return typeof code === "string" ? code : void 0;
43
+ }
44
+ function isoTime(value) {
45
+ const time = Date.parse(value);
46
+ return Number.isNaN(time) ? value : new Date(time).toISOString();
47
+ }
48
+ /** The author of a revision: a string, or a person `{ id, name, email }` as Content and `vitehub push` record it. */
49
+ function authorName(author) {
50
+ if (typeof author === "string") return author || void 0;
51
+ if (Object(author) !== author) return void 0;
52
+ for (const key of [
53
+ "name",
54
+ "email",
55
+ "id"
56
+ ]) {
57
+ const value = Reflect.get(Object(author), key);
58
+ if (typeof value === "string" && value) return value;
59
+ }
60
+ }
61
+ function describeRevision(revision) {
62
+ const author = authorName(revision.metadata?.author);
63
+ const result = {
64
+ ...revision,
65
+ createdAt: isoTime(revision.createdAt)
66
+ };
67
+ if (author) result.author = author;
68
+ return result;
69
+ }
70
+ function describeFile(entry) {
71
+ const result = { path: entry.path };
72
+ if (entry.size !== void 0) result.size = entry.size;
73
+ if (entry.mediaType !== void 0) result.mediaType = entry.mediaType;
74
+ if (entry.digest !== void 0) result.digest = entry.digest;
75
+ return result;
76
+ }
77
+ function encodeContent(bytes) {
78
+ try {
79
+ return {
80
+ content: new TextDecoder("utf-8", { fatal: true }).decode(bytes),
81
+ encoding: "utf8"
82
+ };
83
+ } catch {
84
+ let binary = "";
85
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
86
+ return {
87
+ content: btoa(binary),
88
+ encoding: "base64"
89
+ };
90
+ }
91
+ }
92
+ async function listHistory(workspace, history, request) {
93
+ const limit = request.limit ?? 20;
94
+ if (request.ref !== void 0) {
95
+ const page = await history.list({
96
+ cursor: request.cursor,
97
+ limit,
98
+ ref: request.ref
99
+ });
100
+ return {
101
+ workspace,
102
+ ref: request.ref,
103
+ revisions: page.revisions.map(describeRevision),
104
+ cursor: page.cursor,
105
+ more: Boolean(page.cursor)
106
+ };
107
+ }
108
+ const pages = await Promise.all((await history.refs()).map(async (ref) => await history.list({
109
+ limit,
110
+ ref: ref.name
111
+ })));
112
+ const revisions = pages.flatMap((page) => page.revisions).map(describeRevision).sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt));
113
+ return {
114
+ workspace,
115
+ revisions: revisions.slice(0, limit),
116
+ more: revisions.length > limit || pages.some((page) => page.cursor)
117
+ };
118
+ }
119
+ async function showRevision(workspace, history, request) {
120
+ const ref = (await history.refs()).find((entry) => entry.name === request.target);
121
+ let view;
122
+ try {
123
+ view = await history.open(ref ? ref.head.id : request.target);
124
+ } catch (error) {
125
+ if (errorCode(error) !== "WORKSPACE_NOT_FOUND") throw error;
126
+ throw workspaceErrorDiagnostics.WORKSPACE_NOT_FOUND({
127
+ id: request.target,
128
+ problem: "target",
129
+ workspace,
130
+ cause: error
131
+ });
132
+ }
133
+ const revision = describeRevision(view.revision);
134
+ if (request.path === void 0) return {
135
+ workspace,
136
+ revision,
137
+ files: (await view.list("", { recursive: true })).filter((entry) => entry.type === "file").map(describeFile)
138
+ };
139
+ let stat;
140
+ try {
141
+ stat = await view.stat(request.path);
142
+ } catch (error) {
143
+ if (errorCode(error) !== "WORKSPACE_NOT_FOUND") throw error;
144
+ throw workspaceErrorDiagnostics.WORKSPACE_NOT_FOUND({
145
+ id: revision.id,
146
+ path: request.path,
147
+ problem: "path",
148
+ workspace,
149
+ cause: error
150
+ });
151
+ }
152
+ if (stat.type === "directory") {
153
+ const files = (await view.list(stat.path, { recursive: true })).filter((entry) => entry.type === "file").map(describeFile);
154
+ return {
155
+ workspace,
156
+ revision,
157
+ path: stat.path,
158
+ files
159
+ };
160
+ }
161
+ const bytes = await view.readFile(stat.path, { encoding: "binary" });
162
+ return {
163
+ workspace,
164
+ revision,
165
+ path: stat.path,
166
+ file: {
167
+ ...describeFile(stat),
168
+ ...encodeContent(bytes)
169
+ }
170
+ };
171
+ }
172
+ function decodeContent(file) {
173
+ if (file.encoding === "utf8") return file.content;
174
+ return Uint8Array.from(atob(file.content), (character) => character.charCodeAt(0));
175
+ }
176
+ /** The files of a revision by path, with the digest of each. */
177
+ async function filesOf(view) {
178
+ const files = /* @__PURE__ */ new Map();
179
+ for (const entry of await view.list("", { recursive: true })) if (entry.type === "file") files.set(entry.path, entry);
180
+ return files;
181
+ }
182
+ async function sameBytes(left, right, path, leftEntry, rightEntry) {
183
+ if (leftEntry.digest !== void 0 && rightEntry.digest !== void 0) return leftEntry.digest === rightEntry.digest;
184
+ const [a, b] = await Promise.all([left.readFile(path, { encoding: "binary" }), right.readFile(path, { encoding: "binary" })]);
185
+ return a.length === b.length && a.every((byte, index) => byte === b[index]);
186
+ }
187
+ async function readContent(view, path) {
188
+ return encodeContent(await view.readFile(path, { encoding: "binary" }));
189
+ }
190
+ async function openOrMissing(history, id) {
191
+ try {
192
+ return await history.open(id);
193
+ } catch (error) {
194
+ if (errorCode(error) !== "WORKSPACE_NOT_FOUND") throw error;
195
+ throw workspaceErrorDiagnostics.WORKSPACE_NOT_FOUND({
196
+ id,
197
+ problem: "revision",
198
+ workspace: "",
199
+ cause: error
200
+ });
201
+ }
202
+ }
203
+ async function listChanges(workspace, history, request) {
204
+ const ref = request.ref ?? "main";
205
+ const head = await history.head({ ref });
206
+ const result = {
207
+ workspace,
208
+ ref,
209
+ head: head ? describeRevision(head) : null,
210
+ files: []
211
+ };
212
+ const since = request.since ?? null;
213
+ if (head?.id === since) return result;
214
+ const headView = head ? await history.open(head.id) : void 0;
215
+ const baseView = since === null ? void 0 : await openOrMissing(history, since);
216
+ const headFiles = headView ? await filesOf(headView) : /* @__PURE__ */ new Map();
217
+ const baseFiles = baseView ? await filesOf(baseView) : /* @__PURE__ */ new Map();
218
+ const withContent = request.content !== false;
219
+ for (const path of [.../* @__PURE__ */ new Set([...headFiles.keys(), ...baseFiles.keys()])].sort()) {
220
+ const now = headFiles.get(path);
221
+ const before = baseFiles.get(path);
222
+ if (now && before && await sameBytes(baseView, headView, path, before, now)) continue;
223
+ const file = {
224
+ path,
225
+ ...now ? {} : { deleted: true }
226
+ };
227
+ if (withContent && now) file.head = await readContent(headView, path);
228
+ if (withContent && before) file.base = await readContent(baseView, path);
229
+ result.files.push(file);
230
+ }
231
+ return result;
232
+ }
233
+ /** The new content of a file. A file that exists at the base revision keeps its media type and metadata. */
234
+ function replacement(content, before) {
235
+ const file = { content };
236
+ if (before?.mediaType) file.mediaType = before.mediaType;
237
+ if (before?.metadata) file.metadata = Object.fromEntries(Object.entries(before.metadata).filter(([key]) => key !== "source"));
238
+ return file;
239
+ }
240
+ /** The caller of a commit in the shape that Content records: the surface, the person, and the Agent Actor. */
241
+ function callerMetadata(context) {
242
+ const author = Object.fromEntries([
243
+ "id",
244
+ "name",
245
+ "email"
246
+ ].flatMap((key) => {
247
+ const value = context.user?.[key];
248
+ return typeof value === "string" && value ? [[key, value]] : [];
249
+ }));
250
+ return {
251
+ source: context.surface,
252
+ ...Object.keys(author).length ? { author } : {},
253
+ ...context.actor?.id ? { agent: { actor: context.actor.id } } : {}
254
+ };
255
+ }
256
+ /** An Agent tool or an MCP client: a model decides the call, for the person it works for. */
257
+ function modelSurface(context) {
258
+ return context.surface === "agent" || context.surface === "mcp";
259
+ }
260
+ async function commitChanges(workspace, request, context) {
261
+ const remove = request.delete ?? [];
262
+ if (!Object.keys(request.put ?? {}).length && !remove.length) throw workspaceErrorDiagnostics.WORKSPACE_HISTORY_INVALID({ problem: "empty-commit" });
263
+ if (request.lease === "override" && modelSurface(context) && !context.overrideLeases) throw workspaceErrorDiagnostics.WORKSPACE_FORBIDDEN();
264
+ const { history } = useWorkspaceFiles(workspace, { mode: "write" });
265
+ const ref = request.ref ?? "main";
266
+ const forkRef = request.ifHead === null ? await history.forksFrom?.(ref) : void 0;
267
+ const startFrom = forkRef ? (await history.head({ ref: forkRef }))?.id : void 0;
268
+ const baseId = request.ifHead ?? startFrom;
269
+ const base = baseId ? await filesOf(await openOrMissing(history, baseId)) : /* @__PURE__ */ new Map();
270
+ const put = Object.fromEntries(Object.entries(request.put ?? {}).map(([path, file]) => [path, replacement(decodeContent(file), base.get(normalizeHistoryPath(path)))]));
271
+ try {
272
+ const revision = await history.commit({
273
+ ref,
274
+ ifHead: request.ifHead,
275
+ ...startFrom ? { startFrom } : {},
276
+ ...forkRef ? { ifHeads: { [forkRef]: startFrom ?? null } } : {},
277
+ changes: {
278
+ put,
279
+ delete: remove
280
+ },
281
+ message: request.message ?? `Push ${Object.keys(put).length + remove.length} files`,
282
+ metadata: {
283
+ ...callerMetadata(context),
284
+ ...request.lease === "override" ? { lease: "override" } : {}
285
+ }
286
+ });
287
+ const view = await history.open(revision.id);
288
+ const normalized = {};
289
+ for (const [path, file] of Object.entries(put)) {
290
+ const submitted = encodeContent(contentToBytes(file.content));
291
+ const committed = await readContent(view, normalizeHistoryPath(path));
292
+ if (committed.content !== submitted.content || committed.encoding !== submitted.encoding) normalized[path] = committed;
293
+ }
294
+ return {
295
+ workspace,
296
+ revision: describeRevision(revision),
297
+ ...Object.keys(normalized).length ? { normalized } : {}
298
+ };
299
+ } catch (error) {
300
+ if (errorCode(error) !== "WORKSPACE_CONFLICT") throw error;
301
+ throw workspaceConflict(`Ref "${request.ref ?? "main"}" of Workspace "${workspace}" moved after revision ${request.ifHead ?? "(none)"}. Pull, then push again.`, { cause: error });
302
+ }
303
+ }
304
+ const derivedExtensions = /\.(?:json|markdown|md|mdx|ya?ml)$/i;
305
+ async function listStale(workspace, history, ref) {
306
+ const head = await history.head({ ref });
307
+ if (!head) return {
308
+ workspace,
309
+ ref,
310
+ head: null,
311
+ stale: []
312
+ };
313
+ const view = await history.open(head.id);
314
+ const paths = new Set((await view.list("", { recursive: true })).filter((entry) => entry.type === "file").map((entry) => entry.path));
315
+ const files = /* @__PURE__ */ new Map();
316
+ for (const path of paths) if (derivedExtensions.test(path)) files.set(path, await view.readFile(path, { encoding: "binary" }));
317
+ for (const [path, bytes] of files) {
318
+ const source = readDerivedFrom(path, bytes)?.path;
319
+ if (source && !files.has(source) && paths.has(source)) files.set(source, await view.readFile(source, { encoding: "binary" }));
320
+ }
321
+ return {
322
+ workspace,
323
+ ref,
324
+ head: head.id,
325
+ stale: staleDerivedFiles(files)
326
+ };
327
+ }
328
+ /** The derived files on a ref whose source changed or is gone since they were made. */
329
+ async function runWorkspaceStale(input) {
330
+ try {
331
+ return await listStale(input.workspace, useWorkspaceFiles(input.workspace).history, input.ref ?? "main");
332
+ } catch (error) {
333
+ throw describeFailure(input.workspace, error);
334
+ }
335
+ }
336
+ /** Lists the files that changed on a ref since a revision, with their content, for `vitehub pull`. */
337
+ async function runWorkspaceChanges(input) {
338
+ try {
339
+ return await listChanges(input.workspace, useWorkspaceFiles(input.workspace).history, input);
340
+ } catch (error) {
341
+ throw describeFailure(input.workspace, error);
342
+ }
343
+ }
344
+ /** Commits files to a ref when its head is still `ifHead`, for `vitehub push`. Write rules and validators run. */
345
+ async function runWorkspaceCommit(input, context) {
346
+ try {
347
+ return await commitChanges(input.workspace, input, context);
348
+ } catch (error) {
349
+ throw describeFailure(input.workspace, error);
350
+ }
351
+ }
352
+ async function runWorkspaceOperation(operation, input) {
353
+ try {
354
+ if (operation === "history" && "cursor" in input && input.cursor !== void 0 && input.ref === void 0) throw workspaceErrorDiagnostics.WORKSPACE_HISTORY_INVALID({ problem: "cursor-ref" });
355
+ const { history } = useWorkspaceFiles(input.workspace);
356
+ if (operation === "refs") {
357
+ const refs = await history.refs();
358
+ return {
359
+ workspace: input.workspace,
360
+ refs: refs.map((ref) => ({
361
+ name: ref.name,
362
+ head: describeRevision(ref.head)
363
+ }))
364
+ };
365
+ }
366
+ if (operation === "history") return await listHistory(input.workspace, history, input);
367
+ return await showRevision(input.workspace, history, input);
368
+ } catch (error) {
369
+ throw describeFailure(input.workspace, error);
370
+ }
371
+ }
372
+ function describeFailure(workspace, error) {
373
+ const code = errorCode(error);
374
+ if (!(error instanceof Error) || !code) return withStatus(workspaceErrorDiagnostics.WORKSPACE_HISTORY_FAILED({
375
+ workspace,
376
+ cause: error
377
+ }), 500, error instanceof Error ? error.message : String(error));
378
+ if (code === "WORKSPACE_R0069") return withStatus(error, 409, `Workspace "${workspace}" has no retained history because its Store does not keep revisions. Use the Blob + Database Store, createBlobDatabaseWorkspaceStore() from @vite-hub/workspace/blob-database, to keep refs and revisions.`);
379
+ if (code === "WORKSPACE_NOT_FOUND" && error.message.includes(`Workspace "${workspace}" is not registered.`)) return withStatus(workspaceErrorDiagnostics.WORKSPACE_NOT_FOUND({
380
+ problem: "workspace",
381
+ workspace,
382
+ cause: error
383
+ }), 404);
384
+ const own = Reflect.get(error, "status");
385
+ if (typeof own === "number" && own >= 400 && own < 500) return withStatus(error, own);
386
+ return withStatus(error, operationStatus[code] ?? (invalidRequestCodes.has(code) ? 400 : 500));
387
+ }
388
+ //#endregion
389
+ export { runWorkspaceChanges, runWorkspaceCommit, runWorkspaceOperation, runWorkspaceStale };