@vite-hub/rate-limit 0.3.0 → 0.4.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.
@@ -1,57 +1,7 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
+ import { n as normalizeRateLimitPolicy } from "./policy-BeyQ0vnc.js";
2
3
  import * as v from "valibot";
3
4
  import { Diagnostic } from "nostics";
4
- //#region src/policy.ts
5
- const rateLimitPolicyKeys = /* @__PURE__ */ new Set([
6
- "enforcement",
7
- "failure",
8
- "limit",
9
- "window"
10
- ]);
11
- const unitMilliseconds = {
12
- d: 864e5,
13
- h: 36e5,
14
- m: 6e4,
15
- ms: 1,
16
- s: 1e3
17
- };
18
- function parseRateLimitWindow(value) {
19
- const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(value);
20
- if (!match) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0031({ message: "[vitehub] Rate Limit window must use a duration such as \"10s\", \"1m\", \"1h\", or \"1d\"." });
21
- const unitMs = unitMilliseconds[match[2]];
22
- const [integer, fraction = ""] = match[1].split(".");
23
- const fractionalOverflow = Number(integer) === 864e13 / unitMs && /[1-9]/.test(fraction);
24
- const windowMs = Math.ceil(Number(match[1]) * unitMs);
25
- if (!Number.isFinite(windowMs) || windowMs <= 0 || windowMs > 864e13 || fractionalOverflow) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0032({ message: "[vitehub] Rate Limit window must resolve to finite milliseconds greater than zero and at most 8640000000000000." });
26
- return windowMs;
27
- }
28
- function normalizeRateLimitPolicy(policy) {
29
- if (!policy || typeof policy !== "object" || Array.isArray(policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0033({ message: "[vitehub] Rate Limit policy must be an object." });
30
- const limit = Object.hasOwn(policy, "limit") ? policy.limit : void 0;
31
- const duration = Object.hasOwn(policy, "window") ? policy.window : void 0;
32
- const enforcement = Object.hasOwn(policy, "enforcement") ? policy.enforcement : void 0;
33
- const failure = Object.hasOwn(policy, "failure") ? policy.failure : void 0;
34
- if (limit === void 0 || !Number.isInteger(limit) || limit <= 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0034({ message: "[vitehub] Rate Limit limit must be a positive integer." });
35
- if (typeof duration !== "string") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0031({ message: "[vitehub] Rate Limit window must use a duration such as \"10s\", \"1m\", \"1h\", or \"1d\"." });
36
- if (enforcement !== void 0 && enforcement !== "best-effort" && enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0035({ message: "[vitehub] Rate Limit enforcement must be \"best-effort\" or \"strict\"." });
37
- if (failure !== void 0 && failure !== "allow" && failure !== "deny") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0036({ message: "[vitehub] Rate Limit failure must be \"allow\" or \"deny\"." });
38
- return {
39
- enforcement: enforcement ?? "best-effort",
40
- failure: failure ?? "deny",
41
- limit,
42
- window: duration,
43
- windowMs: parseRateLimitWindow(duration)
44
- };
45
- }
46
- function declaredRateLimitPolicy(policy) {
47
- return {
48
- enforcement: policy.enforcement,
49
- failure: policy.failure,
50
- limit: policy.limit,
51
- window: policy.window
52
- };
53
- }
54
- //#endregion
55
5
  //#region src/limiter.ts
56
6
  const driverErrorSchema = v.custom((value) => {
57
7
  return ("isError" in Error && v.is(v.function(), Error.isError) ? Error.isError(value) === true : v.is(v.instance(Error), value) || v.is(v.object({}), value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null && Object.prototype.toString.call(value) === "[object Error]") && v.is(v.object({
@@ -60,7 +10,7 @@ const driverErrorSchema = v.custom((value) => {
60
10
  }), value);
61
11
  });
62
12
  const driverOutcomeSchema = v.pipe(v.array(v.unknown()), v.length(2), v.union([v.strictTuple([v.undefined(), v.unknown()]), v.strictTuple([driverErrorSchema, v.undefined()])]));
63
- const driverResetOutcomeSchema = v.pipe(v.array(v.unknown()), v.length(2), v.strictTuple([v.optional(driverErrorSchema), v.undefined()]));
13
+ const driverVoidOutcomeSchema = v.pipe(v.array(v.unknown()), v.length(2), v.strictTuple([v.optional(driverErrorSchema), v.undefined()]));
64
14
  function resolveDriverCapabilities(options, capabilities = options.driver.capabilities, driverName = options.driver.name) {
65
15
  if (!capabilities || typeof capabilities !== "object") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0019({ message: `[vitehub] Rate Limit driver "${driverName}" must declare capabilities.` });
66
16
  if (capabilities.enforcement !== "best-effort" && capabilities.enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0020({ message: `[vitehub] Rate Limit driver "${driverName}" must declare valid enforcement.` });
@@ -131,7 +81,8 @@ function normalizePeekResult(result, policy) {
131
81
  };
132
82
  }
133
83
  function unsupportedReason(driverName, operation) {
134
- return operation === "peek" ? `The "${driverName}" Rate Limit driver cannot read a counter without consuming a token.` : `The "${driverName}" Rate Limit driver cannot reset a counter.`;
84
+ if (operation === "peek") return `The "${driverName}" Rate Limit driver cannot read a counter without consuming a token.`;
85
+ return operation === "refund" ? `The "${driverName}" Rate Limit driver cannot give back a request.` : `The "${driverName}" Rate Limit driver cannot reset a counter.`;
135
86
  }
136
87
  function assertKey(input, operation) {
137
88
  if (!input || !v.is(v.string(), input.key) || input.key.length === 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0038({ message: `[vitehub] Rate Limiter ${operation}() requires a non-empty key.` });
@@ -152,6 +103,7 @@ function inspectRateLimiterOptions(options) {
152
103
  const consume = Reflect.get(driver, "consume");
153
104
  if (typeof consume !== "function") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires a Rate Limit driver with a consume() function." });
154
105
  const peek = Reflect.get(driver, "peek");
106
+ const refund = Reflect.get(driver, "refund");
155
107
  const reset = Reflect.get(driver, "reset");
156
108
  const policy = {
157
109
  driver,
@@ -168,6 +120,7 @@ function inspectRateLimiterOptions(options) {
168
120
  driverName: Reflect.get(driver, "name"),
169
121
  consume,
170
122
  peek,
123
+ refund,
171
124
  reset
172
125
  };
173
126
  const windows = Reflect.get(capabilities, "windows");
@@ -183,6 +136,7 @@ function inspectRateLimiterOptions(options) {
183
136
  driverName: Reflect.get(driver, "name"),
184
137
  consume,
185
138
  peek,
139
+ refund,
186
140
  reset
187
141
  };
188
142
  }
@@ -198,7 +152,8 @@ const rateLimitDiagnosticCodes = /* @__PURE__ */ new Set([
198
152
  "RATE_LIMIT_B0001",
199
153
  "RATE_LIMIT_B0002",
200
154
  "RATE_LIMIT_B0003",
201
- "RATE_LIMIT_B0004"
155
+ "RATE_LIMIT_B0004",
156
+ "RUNTIME_DURATION_INVALID"
202
157
  ]);
203
158
  function createRateLimiter(options) {
204
159
  if (!isRateLimiterOptions(options)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires a Rate Limit driver." });
@@ -228,6 +183,7 @@ function createRateLimiter(options) {
228
183
  const driver = inspected.policy.driver;
229
184
  const consume = inspected.consume;
230
185
  const peek = inspected.peek;
186
+ const refund = inspected.refund;
231
187
  const reset = inspected.reset;
232
188
  return {
233
189
  capabilities,
@@ -266,6 +222,21 @@ function createRateLimiter(options) {
266
222
  return normalizePeekResult(result, policy);
267
223
  },
268
224
  policy,
225
+ async refund(input) {
226
+ assertKey(input, "refund");
227
+ if (!v.is(v.function(), refund)) return {
228
+ reason: unsupportedReason(inspected.driverName, "refund"),
229
+ status: "unsupported"
230
+ };
231
+ const outcome = await refund.call(driver, driverInput(input));
232
+ const parsed = v.safeParse(driverVoidOutcomeSchema, outcome);
233
+ if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_REFUND_RESULT_INVALID();
234
+ const [error] = parsed.output;
235
+ return error ? {
236
+ cause: error.cause ?? error,
237
+ status: "unavailable"
238
+ } : { status: "refunded" };
239
+ },
269
240
  async reset(input) {
270
241
  assertKey(input, "reset");
271
242
  if (!v.is(v.function(), reset)) return {
@@ -273,7 +244,7 @@ function createRateLimiter(options) {
273
244
  status: "unsupported"
274
245
  };
275
246
  const outcome = await reset.call(driver, driverInput(input));
276
- const parsed = v.safeParse(driverResetOutcomeSchema, outcome);
247
+ const parsed = v.safeParse(driverVoidOutcomeSchema, outcome);
277
248
  if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0042({ message: "[vitehub] Rate Limit driver reset() must return [undefined, undefined] or [error, undefined]." });
278
249
  const [error] = parsed.output;
279
250
  return error ? {
@@ -290,4 +261,4 @@ function resolveKVRateLimitDriver(driver) {
290
261
  return driver === "database" || driver === "redis" || driver === "upstash" ? "kv" : "memory";
291
262
  }
292
263
  //#endregion
293
- export { rateLimitPolicyKeys as a, normalizeRateLimitPolicy as i, createRateLimiter as n, declaredRateLimitPolicy as r, resolveKVRateLimitDriver as t };
264
+ export { createRateLimiter as n, resolveKVRateLimitDriver as t };
@@ -115,6 +115,11 @@ interface OperationContext {
115
115
  surface: "console" | "cli" | "mcp" | "agent";
116
116
  /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
117
  development?: boolean;
118
+ /**
119
+ * The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
120
+ * it only with `development`, so a deployed server never reads project files through it.
121
+ */
122
+ projectRoot?: string;
118
123
  env?: Record<string, unknown>;
119
124
  waitUntil?: (task: Promise<unknown>) => void;
120
125
  request?: Request;
@@ -1,5 +1,5 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
- import { n as resetRateLimit, t as peekRateLimit } from "./counters-DgVdHwdL.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-D4LANMAi.js";
3
3
  import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
4
4
  //#region src/runtime/operations.ts
5
5
  /** Removes credentials from the echoed key and from driver error text before the result leaves the runtime. */
@@ -6,211 +6,6 @@ import { tmpdir } from "node:os";
6
6
  import "node:url";
7
7
  import { createBirpc } from "birpc";
8
8
  import { toJsonSchema } from "@valibot/to-json-schema";
9
- //#region ../internal/src/object.ts
10
- /** A non-null object that is not an array. Functions do not pass. */
11
- function isRecord(value) {
12
- return typeof value === "object" && value !== null && !Array.isArray(value);
13
- }
14
- /** A non-null object or a function that is not an array. */
15
- function isRecordOrFunction(value) {
16
- return Object(value) === value && !Array.isArray(value);
17
- }
18
- /** A shallow copy of a non-array object, or an empty object for any other value. */
19
- function cloneRecord(value) {
20
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
21
- }
22
- function parseViteHubDevTimeout(value, error) {
23
- if (!/^\d+$/.test(value)) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
24
- const timeout = Number(value);
25
- if (timeout > 2147483647) throw error("--timeout must be at most 2147483647 milliseconds.");
26
- if (!Number.isInteger(timeout) || timeout < 1) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
27
- return timeout;
28
- }
29
- /**
30
- * Reads one dev target option at `args[index]`: `--url <url>`, `--server <url>`,
31
- * `--url=<url>`, `--timeout <ms>` or `--timeout=<ms>`.
32
- *
33
- * Returns the number of extra arguments that the option used (`0` or `1`), or
34
- * `undefined` when `args[index]` is not a dev target option.
35
- */
36
- function readViteHubDevTargetOption(args, index, target, errors) {
37
- const arg = args[index];
38
- if (arg === void 0) return;
39
- const readValue = () => {
40
- const value = args[index + 1];
41
- if (!value || value.startsWith("-")) throw errors.missingValue(`Missing value for ${arg}.`);
42
- return value;
43
- };
44
- if (arg === "--url" || arg === "--server") {
45
- target.url = readValue();
46
- return 1;
47
- }
48
- if (arg.startsWith("--url=")) {
49
- const value = arg.slice(6);
50
- if (!value) throw errors.missingValue(`Missing value for ${arg}.`);
51
- target.url = value;
52
- return 0;
53
- }
54
- if (arg === "--timeout") {
55
- target.timeout = parseViteHubDevTimeout(readValue(), errors.invalidTimeout);
56
- return 1;
57
- }
58
- if (arg.startsWith("--timeout=")) {
59
- target.timeout = parseViteHubDevTimeout(arg.slice(10), errors.invalidInlineTimeout);
60
- return 0;
61
- }
62
- }
63
- /** Writes a command failure: as `{ error }` JSON on stdout with `--json`, else the message and fix on stderr. Returns exit code 1. */
64
- function writeCliFailure(json, streams, failure) {
65
- if (json) streams.stdout.write(`${JSON.stringify({ error: failure }, null, 2)}\n`);
66
- else streams.stderr.write(`${failure.message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
67
- return 1;
68
- }
69
- /** Asks a question on the terminal through stderr. Only `y` or `yes`, in any case, is a yes. */
70
- async function askOnTerminal(question) {
71
- const terminal = createInterface({
72
- input: process.stdin,
73
- output: process.stderr
74
- });
75
- try {
76
- return /^y(es)?$/i.test((await terminal.question(question)).trim());
77
- } finally {
78
- terminal.close();
79
- }
80
- }
81
- /** File in the project root where the running dev server tells commands where it listens. */
82
- const viteHubDevServerFile = ".vitehub/dev-server.json";
83
- function writeViteHubDevServerFile(root, info) {
84
- const file = join(root, viteHubDevServerFile);
85
- mkdirSync(dirname(file), { recursive: true });
86
- writeFileSync(file, `${JSON.stringify(info)}\n`);
87
- }
88
- function removeViteHubDevServerFile(root) {
89
- rmSync(join(root, viteHubDevServerFile), { force: true });
90
- }
91
- /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
92
- function readViteHubDevServerFile(root) {
93
- try {
94
- const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
95
- const url = isRecord(value) ? value.url : void 0;
96
- const served = isRecord(value) ? value.root : void 0;
97
- return typeof url === "string" && url && typeof served === "string" && served ? {
98
- root: served,
99
- url
100
- } : void 0;
101
- } catch {
102
- return;
103
- }
104
- }
105
- /**
106
- * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
107
- * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
108
- */
109
- function findViteHubDevServerUrl(roots, env) {
110
- for (const root of roots) {
111
- const file = readViteHubDevServerFile(root);
112
- if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
113
- }
114
- return env["VITEHUB_DEV_SERVER_URL"] || void 0;
115
- }
116
- //#endregion
117
- //#region ../internal/src/build/vite.ts
118
- const projectRootDirectoryMarkers = [
119
- ["server", "agents"],
120
- ["server", "channels"],
121
- ["server", "connections"],
122
- ["server", "browsers"],
123
- ["server", "emails"],
124
- ["server", "schedules"],
125
- ["server", "workspaces"]
126
- ];
127
- const projectRootFileMarkers = [
128
- ["package.json"],
129
- ["nuxt.config.ts"],
130
- ["nuxt.config.mts"],
131
- ["nuxt.config.js"],
132
- ["nuxt.config.mjs"]
133
- ];
134
- function createNoExternalAddition(...packageNames) {
135
- return (current) => {
136
- if (current === true) return;
137
- const values = Array.isArray(current) ? current : [current];
138
- const missing = packageNames.filter((packageName) => !values.includes(packageName));
139
- return missing.length ? missing : void 0;
140
- };
141
- }
142
- function isServerEnvironment(name, config) {
143
- return name === "ssr" || config.consumer === "server";
144
- }
145
- const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
146
- /** The deployment host that `vitehub()` selected, such as `"cloudflare"`. */
147
- const VITEHUB_DEPLOYMENT_HOST = "__vitehubDeploymentHost";
148
- /**
149
- * Feature options that `vitehub()` and `vite-hub/nuxt` resolve for owner plugins during config hooks, such as the Queue
150
- * provider of the host. Apps set features only in `vitehub()`, so this key is private.
151
- */
152
- const VITEHUB_FEATURES = "__vitehubFeatures";
153
- /** The options that ViteHub resolved for a feature on this Vite config. The owner plugin names their type. */
154
- function getResolvedFeatureOptions(config, feature) {
155
- const features = Reflect.get(config, VITEHUB_FEATURES);
156
- if (!features || typeof features !== "object") return void 0;
157
- return Reflect.get(features, feature);
158
- }
159
- /** The deployment host that `vitehub()` selected on this Vite config. */
160
- function getDeploymentHost(config) {
161
- const host = Reflect.get(config, VITEHUB_DEPLOYMENT_HOST);
162
- return typeof host === "string" ? host : void 0;
163
- }
164
- function shouldSkipViteProviderBuild(command) {
165
- return command === "serve";
166
- }
167
- function resolveViteHubProjectRoot(root, options = {}) {
168
- const resolvedRoot = resolve(root);
169
- const temporaryRoot = resolve(tmpdir());
170
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
171
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
172
- if (basename(resolvedRoot) === "app") {
173
- const parent = dirname(resolvedRoot);
174
- if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
175
- "nuxt.config.ts",
176
- "nuxt.config.mts",
177
- "nuxt.config.js",
178
- "nuxt.config.mjs"
179
- ]))) return parent;
180
- }
181
- let current = resolvedRoot;
182
- while (true) {
183
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
184
- if (hasProjectRootMarker(current)) return current;
185
- const parent = dirname(current);
186
- if (parent === current) return resolvedRoot;
187
- current = parent;
188
- }
189
- }
190
- function hasProjectRootDirectoryMarker(root) {
191
- for (const marker of projectRootDirectoryMarkers) try {
192
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
193
- } catch (error) {
194
- if (error.code !== "ENOENT") throw error;
195
- }
196
- return false;
197
- }
198
- function hasProjectRootMarker(root) {
199
- if (hasProjectRootDirectoryMarker(root)) return true;
200
- return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
201
- }
202
- function hasProjectRootFileMarker(root, markers) {
203
- for (const marker of markers) {
204
- const path = Array.isArray(marker) ? marker : [marker];
205
- try {
206
- if (statSync(resolve(root, ...path)).isFile()) return true;
207
- } catch (error) {
208
- if (error.code !== "ENOENT") throw error;
209
- }
210
- }
211
- return false;
212
- }
213
- //#endregion
214
9
  //#region ../internal/src/error-diagnostics.ts
215
10
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
216
11
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
@@ -382,7 +177,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
382
177
  },
383
178
  INTERNAL_R0004: {
384
179
  ...dynamicError,
385
- fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
180
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
386
181
  },
387
182
  INTERNAL_R0005: {
388
183
  ...dynamicError,
@@ -428,6 +223,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
428
223
  why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
429
224
  fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
430
225
  },
226
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
227
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
228
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
229
+ },
431
230
  INTERNAL_FORGE_NOT_INSTALLED: {
432
231
  why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
433
232
  fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
@@ -475,6 +274,217 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
475
274
  }
476
275
  });
477
276
  //#endregion
277
+ //#region ../internal/src/object.ts
278
+ /** A non-null object that is not an array. Functions do not pass. */
279
+ function isRecord(value) {
280
+ return typeof value === "object" && value !== null && !Array.isArray(value);
281
+ }
282
+ /** A non-null object or a function that is not an array. */
283
+ function isRecordOrFunction(value) {
284
+ return Object(value) === value && !Array.isArray(value);
285
+ }
286
+ /** A shallow copy of a non-array object, or an empty object for any other value. */
287
+ function cloneRecord(value) {
288
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
289
+ }
290
+ function parseViteHubDevTimeout(value, error) {
291
+ if (!/^\d+$/.test(value)) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
292
+ const timeout = Number(value);
293
+ if (timeout > 2147483647) throw error("--timeout must be at most 2147483647 milliseconds.");
294
+ if (!Number.isInteger(timeout) || timeout < 1) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
295
+ return timeout;
296
+ }
297
+ /**
298
+ * Reads one dev target option at `args[index]`: `--url <url>`, `--url=<url>`,
299
+ * `--timeout <ms>` or `--timeout=<ms>`. `--url` is always the app, and `--server` fails with the fix.
300
+ *
301
+ * Returns the number of extra arguments that the option used (`0` or `1`), or
302
+ * `undefined` when `args[index]` is not a dev target option.
303
+ */
304
+ function readViteHubDevTargetOption(args, index, target, errors) {
305
+ const arg = args[index];
306
+ if (arg === void 0) return;
307
+ const readValue = () => {
308
+ const value = args[index + 1];
309
+ if (!value || value.startsWith("-")) throw errors.missingValue(`Missing value for ${arg}.`);
310
+ return value;
311
+ };
312
+ if (arg === "--server" || arg.startsWith("--server=")) throw errors.unknownOption("--server is now --url. Pass --url with the app URL, such as --url http://localhost:3000.");
313
+ if (arg === "--url") {
314
+ target.url = readValue();
315
+ return 1;
316
+ }
317
+ if (arg.startsWith("--url=")) {
318
+ const value = arg.slice(6);
319
+ if (!value) throw errors.missingValue(`Missing value for ${arg}.`);
320
+ target.url = value;
321
+ return 0;
322
+ }
323
+ if (arg === "--timeout") {
324
+ target.timeout = parseViteHubDevTimeout(readValue(), errors.invalidTimeout);
325
+ return 1;
326
+ }
327
+ if (arg.startsWith("--timeout=")) {
328
+ target.timeout = parseViteHubDevTimeout(arg.slice(10), errors.invalidInlineTimeout);
329
+ return 0;
330
+ }
331
+ }
332
+ /** Writes a command failure: as `{ error }` JSON on stdout with `--json`, else the message and fix on stderr. Returns exit code 1. */
333
+ function writeCliFailure(json, streams, failure) {
334
+ if (json) streams.stdout.write(`${JSON.stringify({ error: failure }, null, 2)}\n`);
335
+ else streams.stderr.write(`${failure.message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
336
+ return 1;
337
+ }
338
+ /** Asks a question on the terminal through stderr. Only `y` or `yes`, in any case, is a yes. */
339
+ async function askOnTerminal(question) {
340
+ const terminal = createInterface({
341
+ input: process.stdin,
342
+ output: process.stderr
343
+ });
344
+ try {
345
+ return /^y(es)?$/i.test((await terminal.question(question)).trim());
346
+ } finally {
347
+ terminal.close();
348
+ }
349
+ }
350
+ /** File in the project root where the running dev server tells commands where it listens. */
351
+ const viteHubDevServerFile = ".vitehub/dev-server.json";
352
+ function writeViteHubDevServerFile(root, info) {
353
+ const file = join(root, viteHubDevServerFile);
354
+ mkdirSync(dirname(file), { recursive: true });
355
+ writeFileSync(file, `${JSON.stringify(info)}\n`);
356
+ }
357
+ function removeViteHubDevServerFile(root) {
358
+ rmSync(join(root, viteHubDevServerFile), { force: true });
359
+ }
360
+ /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
361
+ function readViteHubDevServerFile(root) {
362
+ try {
363
+ const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
364
+ const url = isRecord(value) ? value.url : void 0;
365
+ const served = isRecord(value) ? value.root : void 0;
366
+ return typeof url === "string" && url && typeof served === "string" && served ? {
367
+ root: served,
368
+ url
369
+ } : void 0;
370
+ } catch {
371
+ return;
372
+ }
373
+ }
374
+ /**
375
+ * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
376
+ * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
377
+ */
378
+ function findViteHubDevServerUrl(roots, env) {
379
+ for (const root of roots) {
380
+ const file = readViteHubDevServerFile(root);
381
+ if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
382
+ }
383
+ return env["VITEHUB_DEV_SERVER_URL"] || void 0;
384
+ }
385
+ //#endregion
386
+ //#region ../internal/src/build/vite.ts
387
+ const projectRootDirectoryMarkers = [
388
+ ["server", "agents"],
389
+ ["server", "channels"],
390
+ ["server", "connections"],
391
+ ["server", "browsers"],
392
+ ["server", "emails"],
393
+ ["server", "schedules"],
394
+ ["server", "workspaces"]
395
+ ];
396
+ const projectRootFileMarkers = [
397
+ ["package.json"],
398
+ ["nuxt.config.ts"],
399
+ ["nuxt.config.mts"],
400
+ ["nuxt.config.js"],
401
+ ["nuxt.config.mjs"]
402
+ ];
403
+ function createNoExternalAddition(...packageNames) {
404
+ return (current) => {
405
+ if (current === true) return;
406
+ const values = Array.isArray(current) ? current : [current];
407
+ const missing = packageNames.filter((packageName) => !values.includes(packageName));
408
+ return missing.length ? missing : void 0;
409
+ };
410
+ }
411
+ function isServerEnvironment(name, config) {
412
+ return name === "ssr" || config.consumer === "server";
413
+ }
414
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
415
+ /** The deployment host that `vitehub()` selected, such as `"cloudflare"`. */
416
+ const VITEHUB_DEPLOYMENT_HOST = "__vitehubDeploymentHost";
417
+ /**
418
+ * Feature options that `vitehub()` and `vite-hub/nuxt` resolve for owner plugins during config hooks, such as the Queue
419
+ * provider of the host. Apps set features only in `vitehub()`, so this key is private.
420
+ */
421
+ const VITEHUB_FEATURES = "__vitehubFeatures";
422
+ /** The options that ViteHub resolved for a feature on this Vite config. The owner plugin names their type. */
423
+ function getResolvedFeatureOptions(config, feature) {
424
+ const features = Reflect.get(config, VITEHUB_FEATURES);
425
+ if (!features || typeof features !== "object") return void 0;
426
+ return Reflect.get(features, feature);
427
+ }
428
+ /** The deployment host that `vitehub()` selected on this Vite config. */
429
+ function getDeploymentHost(config) {
430
+ const host = Reflect.get(config, VITEHUB_DEPLOYMENT_HOST);
431
+ return typeof host === "string" ? host : void 0;
432
+ }
433
+ /**
434
+ * Set by `vite-hub/nuxt` when it replays Vite config hooks for `nuxt prepare`. Prepare uses `command: "build"` to write
435
+ * the same types as the build, but it builds nothing.
436
+ */
437
+ const VITEHUB_PREPARE = "__vitehubPrepare";
438
+ function shouldSkipViteProviderBuild(command) {
439
+ return command === "serve";
440
+ }
441
+ function resolveViteHubProjectRoot(root, options = {}) {
442
+ const resolvedRoot = resolve(root);
443
+ const temporaryRoot = resolve(tmpdir());
444
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
445
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
446
+ if (basename(resolvedRoot) === "app") {
447
+ const parent = dirname(resolvedRoot);
448
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
449
+ "nuxt.config.ts",
450
+ "nuxt.config.mts",
451
+ "nuxt.config.js",
452
+ "nuxt.config.mjs"
453
+ ]))) return parent;
454
+ }
455
+ let current = resolvedRoot;
456
+ while (true) {
457
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
458
+ if (hasProjectRootMarker(current)) return current;
459
+ const parent = dirname(current);
460
+ if (parent === current) return resolvedRoot;
461
+ current = parent;
462
+ }
463
+ }
464
+ function hasProjectRootDirectoryMarker(root) {
465
+ for (const marker of projectRootDirectoryMarkers) try {
466
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
467
+ } catch (error) {
468
+ if (error.code !== "ENOENT") throw error;
469
+ }
470
+ return false;
471
+ }
472
+ function hasProjectRootMarker(root) {
473
+ if (hasProjectRootDirectoryMarker(root)) return true;
474
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
475
+ }
476
+ function hasProjectRootFileMarker(root, markers) {
477
+ for (const marker of markers) {
478
+ const path = Array.isArray(marker) ? marker : [marker];
479
+ try {
480
+ if (statSync(resolve(root, ...path)).isFile()) return true;
481
+ } catch (error) {
482
+ if (error.code !== "ENOENT") throw error;
483
+ }
484
+ }
485
+ return false;
486
+ }
487
+ //#endregion
478
488
  //#region ../internal/src/invariant.ts
479
489
  const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
480
490
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
@@ -899,6 +909,7 @@ const reservedOperationNamespaces = [
899
909
  "drain",
900
910
  "login",
901
911
  "logout",
912
+ "update",
902
913
  "whoami"
903
914
  ]
904
915
  ];
@@ -1352,4 +1363,4 @@ function table(rows) {
1352
1363
  return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
1353
1364
  }
1354
1365
  //#endregion
1355
- export { writeCliFailure as A, isServerEnvironment as C, readViteHubDevServerFile as D, askOnTerminal as E, cloneRecord as M, isRecord as N, readViteHubDevTargetOption as O, isRecordOrFunction as P, getResolvedFeatureOptions as S, shouldSkipViteProviderBuild as T, invariant as _, operationRootHeader as a, createNoExternalAddition as b, projectRootHash as c, toOperationFailure as d, defineOperation as f, readOperationRpcCall as g, operationRpcRefusal as h, createOperationRegistry as i, writeViteHubDevServerFile as j, removeViteHubDevServerFile as k, runOperation as l, operationRpcPath as m, callOperationFromCli as n, operationRpcHeader as o, answerOperationRpc as p, collectOperationContributions as r, operationsOf as s, assertOperationProject as t, table as u, internalErrorDiagnostics as v, resolveViteHubProjectRoot as w, getDeploymentHost as x, VITEHUB_PROJECT_ROOT as y };
1366
+ export { writeCliFailure as A, isServerEnvironment as C, readViteHubDevServerFile as D, askOnTerminal as E, internalErrorDiagnostics as F, cloneRecord as M, isRecord as N, readViteHubDevTargetOption as O, isRecordOrFunction as P, getResolvedFeatureOptions as S, shouldSkipViteProviderBuild as T, invariant as _, operationRootHeader as a, createNoExternalAddition as b, projectRootHash as c, toOperationFailure as d, defineOperation as f, readOperationRpcCall as g, operationRpcRefusal as h, createOperationRegistry as i, writeViteHubDevServerFile as j, removeViteHubDevServerFile as k, runOperation as l, operationRpcPath as m, callOperationFromCli as n, operationRpcHeader as o, answerOperationRpc as p, collectOperationContributions as r, operationsOf as s, assertOperationProject as t, table as u, VITEHUB_PREPARE as v, resolveViteHubProjectRoot as w, getDeploymentHost as x, VITEHUB_PROJECT_ROOT as y };
@@ -1,5 +1,5 @@
1
- import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-DXpF67J_.js";
2
- import { t as AnyOperation } from "./operation-definition-8gOe-ubD.js";
1
+ import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-d8FaLiE1.js";
2
+ import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
3
3
  //#region ../internal/src/operations-dev.d.ts
4
4
  /**
5
5
  * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
@@ -1,4 +1,4 @@
1
- import { a as operationRootHeader, c as projectRootHash, d as toOperationFailure, f as defineOperation, g as readOperationRpcCall, h as operationRpcRefusal, i as createOperationRegistry, l as runOperation, o as operationRpcHeader, p as answerOperationRpc, s as operationsOf, t as assertOperationProject, v as internalErrorDiagnostics } from "./operations-BYRa7wpx.js";
1
+ import { F as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as toOperationFailure, f as defineOperation, g as readOperationRpcCall, h as operationRpcRefusal, i as createOperationRegistry, l as runOperation, o as operationRpcHeader, p as answerOperationRpc, s as operationsOf, t as assertOperationProject } from "./operations-q0ieloSJ.js";
2
2
  import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
3
3
  import * as v from "valibot";
4
4
  //#region ../internal/src/secret.ts
@@ -203,6 +203,7 @@ function createStandaloneOperationHandler(sources, root) {
203
203
  sections: "all"
204
204
  },
205
205
  development: true,
206
+ projectRoot: root,
206
207
  surface: "cli",
207
208
  user: null,
208
209
  request,
@@ -236,7 +237,7 @@ function createStandaloneOperationHandler(sources, root) {
236
237
  }
237
238
  //#endregion
238
239
  //#region src/operations.ts
239
- const runtime = () => import("./operations-CLI9w3rO.js");
240
+ const runtime = () => import("./operations-B1MnA9cW.js");
240
241
  const target = v.object({
241
242
  key: v.pipe(v.string(), v.minLength(1, "Name the limited key, for example a client IP or user ID.")),
242
243
  name: v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name the stable ID of `requireRateLimit()`."))