@vite-hub/rate-limit 0.4.1 → 0.5.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 (35) hide show
  1. package/README.md +7 -3
  2. package/dist/{cli-szm60zN5.d.ts → cli-B77bo6ii.d.ts} +1 -6
  3. package/dist/cli.d.ts +2 -4
  4. package/dist/cli.js +5 -7
  5. package/dist/{cloudflare-_Tz3DcpB.js → cloudflare-CWK4wJ9b.js} +4 -7
  6. package/dist/{counters-d8FaLiE1.d.ts → counters-BCNUEaDn.d.ts} +1 -3
  7. package/dist/{counters-D4LANMAi.js → counters-dyc0Q_HL.js} +3 -6
  8. package/dist/{dev-peer-CHafxbtj.js → dev-peer-D0vOxmrD.js} +1 -2
  9. package/dist/drivers/cloudflare.d.ts +2 -6
  10. package/dist/drivers/cloudflare.js +1 -2
  11. package/dist/drivers/kv.d.ts +1 -1
  12. package/dist/drivers/kv.js +2 -12
  13. package/dist/drivers/memory.d.ts +2 -4
  14. package/dist/drivers/memory.js +13 -7
  15. package/dist/durability.d.ts +1 -3
  16. package/dist/durability.js +1 -2
  17. package/dist/{error-diagnostics-DRuEG4wu.js → error-diagnostics-ulOX0clN.js} +1 -2
  18. package/dist/index.d.ts +2 -6
  19. package/dist/index.js +36 -13
  20. package/dist/{inspect-B6gTdgy9.js → inspect-Dqvi9vUt.js} +2 -4
  21. package/dist/{kv-Cw_jK6Gu.d.ts → kv-DldoJary.d.ts} +1 -4
  22. package/dist/{kv-provider-DlgNQC-o.js → kv-provider-DAq-42o6.js} +4 -6
  23. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  24. package/dist/{operations-B1MnA9cW.js → operations-BuAYwMe4.js} +4 -6
  25. package/dist/{operations-q0ieloSJ.js → operations-DWWMHBWt.js} +46 -27
  26. package/dist/operations.d.ts +2 -6
  27. package/dist/operations.js +7 -11
  28. package/dist/{policy-BeyQ0vnc.js → policy-CMsNKnqo.js} +2 -3
  29. package/dist/runtime.d.ts +2 -4
  30. package/dist/runtime.js +1 -2
  31. package/dist/{state-Fq3rGFO3.js → state-BXD6-GFo.js} +4 -6
  32. package/dist/{types-OzukEqHf.d.ts → types-Bw8vrrVF.d.ts} +0 -2
  33. package/dist/vite.d.ts +5 -15
  34. package/dist/vite.js +41 -51
  35. package/package.json +7 -6
package/dist/vite.js CHANGED
@@ -1,19 +1,19 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { a as rateLimitPolicyKeys, i as rateLimitPolicyKey, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-BeyQ0vnc.js";
3
- import { n as createRateLimiter, t as resolveKVRateLimitDriver } from "./kv-provider-DlgNQC-o.js";
1
+ import { C as isServerEnvironment, D as readViteHubDevServerFile, F as internalErrorDiagnostics, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions, w as resolveViteHubProjectRoot, x as getDeploymentHost, y as VITEHUB_PROJECT_ROOT } from "./operations-DWWMHBWt.js";
2
+ import { i as resolve$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-Dqvi9vUt.js";
3
+ import { t as addViteHubDevPeerDevHandler } from "./dev-peer-D0vOxmrD.js";
4
+ import { a as rateLimitPolicyKeys, i as rateLimitPolicyKey, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-CMsNKnqo.js";
5
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
6
+ import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-CWK4wJ9b.js";
4
7
  import { kvRateLimitDriver } from "./drivers/kv.js";
5
8
  import { memoryRateLimitDriver } from "./drivers/memory.js";
6
- import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-_Tz3DcpB.js";
7
- import { i as resolve$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-B6gTdgy9.js";
8
- import { C as isServerEnvironment, D as readViteHubDevServerFile, F as internalErrorDiagnostics, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions, w as resolveViteHubProjectRoot, x as getDeploymentHost, y as VITEHUB_PROJECT_ROOT } from "./operations-q0ieloSJ.js";
9
- import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
9
+ import { n as createRateLimiter, t as resolveKVRateLimitDriver } from "./kv-provider-DAq-42o6.js";
10
10
  import { formatDiagnostic } from "nostics";
11
11
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
12
12
  import { mkdir, readFile, writeFile } from "node:fs/promises";
13
13
  import { basename, dirname, relative, resolve } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { Visitor, parseSync } from "vite";
16
- //#region ../internal/src/hints.ts
16
+ // ../internal/src/hints.ts
17
17
  /**
18
18
  * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
19
19
  * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
@@ -91,8 +91,7 @@ function startViteHubHints(config, owner = config) {
91
91
  started.add(owner);
92
92
  write(startRun(config));
93
93
  }
94
- //#endregion
95
- //#region ../internal/src/build/paths.ts
94
+ // ../internal/src/build/paths.ts
96
95
  function resolveRuntimeModule(packageDir, modulePath) {
97
96
  const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
98
97
  return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
@@ -119,8 +118,7 @@ function findPackageDir(file) {
119
118
  function ownModule(importMetaUrl, modulePath) {
120
119
  return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
121
120
  }
122
- //#endregion
123
- //#region ../internal/src/definition-catalog.ts
121
+ // ../internal/src/definition-catalog.ts
124
122
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
125
123
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
126
124
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
@@ -176,8 +174,15 @@ async function writeFileIfChanged(file, contents) {
176
174
  await mkdir(resolve$1(file, ".."), { recursive: true });
177
175
  await writeFile(file, contents, "utf8");
178
176
  }
179
- //#endregion
180
- //#region ../internal/src/nitro-kit.ts
177
+ Object.freeze({ vitehubAuthAccess: "handler" });
178
+ /**
179
+ * The route meta of a generated handler that checks access on every request, even when the app adds no rule: a required
180
+ * `authorize` policy, an explicit `access` rule, a required access token, or a signature. Auth access routes still apply
181
+ * to it, so an app rule stays in force. `checksOwnAccess(event)` of `vite-hub/auth` reads it, so app middleware can skip
182
+ * the route. A route that can run without a check, such as a browser error sink, an optional `authorize`, or a webhook
183
+ * with `secret: false`, must not use it.
184
+ */
185
+ const ownAccessRouteMeta = Object.freeze({ vitehubOwnAccess: true });
181
186
  function cloneArray(value) {
182
187
  return Array.isArray(value) ? [...value] : [];
183
188
  }
@@ -205,8 +210,7 @@ function createNitroServerKit(value = {}) {
205
210
  }
206
211
  };
207
212
  }
208
- //#endregion
209
- //#region ../internal/src/contributions.ts
213
+ // ../internal/src/contributions.ts
210
214
  function isThenable(value) {
211
215
  return typeof value.then === "function";
212
216
  }
@@ -233,8 +237,7 @@ async function flattenPluginOptions(plugins) {
233
237
  await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
234
238
  return flattened;
235
239
  }
236
- //#endregion
237
- //#region ../internal/src/operations-vite.ts
240
+ // ../internal/src/operations-vite.ts
238
241
  const owners = /* @__PURE__ */ new Set([
239
242
  "@vite-hub/kv/vite",
240
243
  "@vite-hub/blob/vite",
@@ -293,6 +296,7 @@ async function installStandaloneOperationRpc(config, command, module) {
293
296
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
294
297
  kit.addHandler({
295
298
  handler,
299
+ meta: { ...ownAccessRouteMeta },
296
300
  route: operationRpcPath
297
301
  });
298
302
  const devHandlers = kit.config.devHandlers;
@@ -301,14 +305,12 @@ async function installStandaloneOperationRpc(config, command, module) {
301
305
  kit.config.devHandlers = signed;
302
306
  Reflect.set(config, "nitro", kit.config);
303
307
  }
304
- //#endregion
305
- //#region ../internal/src/durability.ts
308
+ // ../internal/src/durability.ts
306
309
  /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
307
310
  function durabilityModuleFile(importMetaUrl) {
308
311
  return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
309
312
  }
310
- //#endregion
311
- //#region ../internal/src/build/provider-output-config.ts
313
+ // ../internal/src/build/provider-output-config.ts
312
314
  function isProviderJsonArray(value, ancestors) {
313
315
  if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
314
316
  if (Reflect.ownKeys(value).length !== value.length + 1) return false;
@@ -395,8 +397,7 @@ function mergeProviderOutputConfig(existing, value, ownership = {}) {
395
397
  ...mergeOwnedArrays(existing, value, ownership.arrays)
396
398
  };
397
399
  }
398
- //#endregion
399
- //#region ../internal/src/build/bundle-options.ts
400
+ // ../internal/src/build/bundle-options.ts
400
401
  /** Select the runtime constants from one resolved Vite configuration. */
401
402
  function resolveViteHubBundleDefines(config) {
402
403
  const defines = {};
@@ -406,8 +407,7 @@ function resolveViteHubBundleDefines(config) {
406
407
  }
407
408
  return defines;
408
409
  }
409
- //#endregion
410
- //#region ../internal/src/build/cloudflare-provider-output.ts
410
+ // ../internal/src/build/cloudflare-provider-output.ts
411
411
  function isDeepStrictEqual(left, right) {
412
412
  if (Object.is(left, right)) return true;
413
413
  if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
@@ -430,7 +430,11 @@ function cloneProviderValue(value) {
430
430
  if (value && typeof value === "object") return cloneProviderRecord(value);
431
431
  return value;
432
432
  }
433
- function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
433
+ /**
434
+ * The incoming entries that the app config does not have yet. An entry that the app already has must agree on
435
+ * `conflictKeys`, and on each of `setKeys` that the incoming entry sets, because the app's entry is the one that stays.
436
+ */
437
+ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner, setKeys = []) {
434
438
  const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
435
439
  return (incoming ?? []).filter((entry) => {
436
440
  const identity = entry[identityKey];
@@ -440,6 +444,8 @@ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner)
440
444
  return true;
441
445
  }
442
446
  if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.` });
447
+ const differentKey = setKeys.find((key) => entry[key] !== void 0 && !isDeepStrictEqual(match[key], entry[key]));
448
+ if (differentKey) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] The Cloudflare ${identityKey} ${JSON.stringify(identity)} in the app's Wrangler config has ${differentKey} ${JSON.stringify(match[differentKey]) ?? "unset"}, but ${owner} sets ${JSON.stringify(entry[differentKey])}. Remove the entry from the Wrangler config, because ViteHub writes it, or give it the same value.` });
443
449
  return false;
444
450
  });
445
451
  }
@@ -496,7 +502,7 @@ function mergeContribution(wrangler, owner, contribution) {
496
502
  const queues = cloneProviderRecord(wrangler.queues);
497
503
  const secrets = cloneProviderRecord(wrangler.secrets);
498
504
  const environments = cloneProviderRecord(wrangler.env);
499
- const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
505
+ const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner, ["max_batch_size"]);
500
506
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
501
507
  const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
502
508
  const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
@@ -580,8 +586,7 @@ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = v
580
586
  associateProviderOutputCatalog(output, catalog);
581
587
  return output;
582
588
  }
583
- //#endregion
584
- //#region ../internal/src/build/provider-output-catalog.ts
589
+ // ../internal/src/build/provider-output-catalog.ts
585
590
  var ProviderOutputCatalog = class {
586
591
  bundleDefines = {};
587
592
  #appliedCloudflareContributions = /* @__PURE__ */ new Map();
@@ -823,8 +828,7 @@ function hostFromNitroPreset(value) {
823
828
  if (normalized === "node" || normalized.startsWith("node-")) return "node";
824
829
  if (normalized.startsWith("vercel")) return "vercel";
825
830
  }
826
- //#endregion
827
- //#region ../internal/src/hosting.ts
831
+ // ../internal/src/hosting.ts
828
832
  /**
829
833
  * Returns the Nitro preset name that this build targets, as the developer wrote it.
830
834
  * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
@@ -850,10 +854,8 @@ function getHostingProvider(hosting) {
850
854
  const host = hostFromNitroPreset(hosting);
851
855
  if (host === "cloudflare" || host === "netlify" || host === "vercel") return host;
852
856
  }
853
- //#endregion
854
- //#region src/discovery.ts
857
+ // src/discovery.ts
855
858
  const rateLimitImports = /* @__PURE__ */ new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
856
- /** Functions whose calls declare a managed Rate Limit. They use the same counters. */
857
859
  const rateLimitGuards = [
858
860
  "checkRateLimit",
859
861
  "refundRateLimit",
@@ -907,7 +909,6 @@ function resolveDirectGuard(name, scopes) {
907
909
  if (scope.shadows.has(name)) return void 0;
908
910
  }
909
911
  }
910
- /** The literal value of the `const` that `name` reads in this scope, or `undefined` for any other binding. */
911
912
  function resolveConstant(name, scopes) {
912
913
  for (let index = scopes.length - 1; index >= 0; index -= 1) {
913
914
  const scope = scopes[index];
@@ -923,7 +924,6 @@ function resolveNamespace(name, scopes) {
923
924
  }
924
925
  return false;
925
926
  }
926
- /** The guard that a call invokes, or `undefined` when the callee is not a Rate Limit guard. */
927
927
  function rateLimitGuardOf(callee, scopes) {
928
928
  if (callee.type === "Identifier") return resolveDirectGuard(callee.name, scopes);
929
929
  if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveNamespace(callee.object.name, scopes)) return;
@@ -1120,7 +1120,6 @@ function staticString(expression) {
1120
1120
  if (value.type === "Literal" && typeof value.value === "string") return value.value;
1121
1121
  if (value.type === "TemplateLiteral" && value.expressions.length === 0) return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw;
1122
1122
  }
1123
- /** A string or number literal, or an identifier that reads a `const` with one. */
1124
1123
  function staticScalar(expression, scopes) {
1125
1124
  const value = unwrapStaticExpression(expression);
1126
1125
  if (value.type === "Literal" && typeof value.value === "number") return value.value;
@@ -1295,8 +1294,7 @@ function discoverRateLimitCatalog(options, snapshots = /* @__PURE__ */ new Map()
1295
1294
  function discoverRateLimitDeclarations(options) {
1296
1295
  return discoverRateLimitCatalog(options).declarations;
1297
1296
  }
1298
- //#endregion
1299
- //#region src/inspect.ts
1297
+ // src/inspect.ts
1300
1298
  function summarizeRateLimitDeclaration(projectRoot, declaration) {
1301
1299
  return {
1302
1300
  fields: [
@@ -1345,8 +1343,7 @@ const rateLimitConsoleSection = {
1345
1343
  notice: "The page lists the policies. Enter a key to read its live counter or to reset it. Counters depend on the provider: a Cloudflare binding cannot be read or reset, a memory counter exists only in this server process, and a kv counter is shared by every process that uses the KV store."
1346
1344
  }
1347
1345
  };
1348
- //#endregion
1349
- //#region src/internal/cloudflare-bindings.ts
1346
+ // src/internal/cloudflare-bindings.ts
1350
1347
  function namespaceId(namespace, rateLimitId) {
1351
1348
  let hash = 2166136261;
1352
1349
  for (const character of `${namespace}:${rateLimitId}`) {
@@ -1389,8 +1386,7 @@ function createCloudflareRateLimitBindings(declarations, namespace) {
1389
1386
  simple: cloudflareSimpleLimit(declaration)
1390
1387
  }));
1391
1388
  }
1392
- //#endregion
1393
- //#region src/internal/manifest.ts
1389
+ // src/internal/manifest.ts
1394
1390
  const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
1395
1391
  const unusedResult = async () => [void 0, void 0];
1396
1392
  function resolveProviderCapabilities(provider) {
@@ -1422,15 +1418,13 @@ async function writeRateLimitManifest(rootDir, declarations, provider) {
1422
1418
  const manifest = createRateLimitManifest(declarations, provider);
1423
1419
  await writeFileIfChanged(resolve(rootDir, rateLimitManifestPath), `${JSON.stringify(manifest, null, 2)}\n`);
1424
1420
  }
1425
- //#endregion
1426
- //#region src/vite.ts
1421
+ // src/vite.ts
1427
1422
  const operationsModule = ownModule(import.meta.url, "operations");
1428
1423
  const runtimeModule = ownModule(import.meta.url, "runtime");
1429
1424
  const packageName = "@vite-hub/rate-limit";
1430
1425
  const pluginName = "@vite-hub/rate-limit/vite";
1431
1426
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
1432
1427
  const mergeNoExternal = createNoExternalAddition(packageName);
1433
- /** The driver of the default KV store, or `undefined` when the app has no KV. */
1434
1428
  function kvStoreDriver(config, build = false) {
1435
1429
  const api = (config.plugins?.find((plugin) => plugin.name === "@vite-hub/kv/vite"))?.api;
1436
1430
  const kv = (build ? api?.getBuildConfig?.() : void 0)?.kv ?? api?.getConfig?.().kv;
@@ -1455,9 +1449,6 @@ function mergeNitroConfig(config, value, declarations, namespace, driver, nitroC
1455
1449
  });
1456
1450
  return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
1457
1451
  }
1458
- /**
1459
- * `kvWindows`: on Cloudflare, a Rate Limit uses a window that the binding does not support, so it counts in KV.
1460
- */
1461
1452
  function renderRuntimeInstaller(runtimeConfig, kvImport, kvWindows) {
1462
1453
  if (runtimeConfig.driver === "cloudflare" && kvWindows) return [
1463
1454
  "import { definePlugin } from 'nitro'",
@@ -1680,5 +1671,4 @@ function hubRateLimit(options = {}) {
1680
1671
  }
1681
1672
  };
1682
1673
  }
1683
- //#endregion
1684
1674
  export { discoverRateLimitDeclarations, hubRateLimit, inspectRateLimitDefinitions, rateLimitConsoleSection };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/rate-limit",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Provider-neutral Rate Limit primitives and Vite deployment integration for ViteHub.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -67,21 +67,22 @@
67
67
  },
68
68
  "dependencies": {
69
69
  "@valibot/to-json-schema": "^1.8.0",
70
- "@vite-hub/runtime": "0.4.1",
70
+ "@vite-hub/runtime": "0.5.1",
71
71
  "birpc": "^4.2.0",
72
72
  "h3": "^2.0.8",
73
73
  "nostics": "1.4.0",
74
74
  "valibot": "^1.5.0"
75
75
  },
76
76
  "devDependencies": {
77
- "@types/node": "^24.19.1",
77
+ "@types/node": "^24.19.2",
78
78
  "@vite-hub/internal": "0.0.1",
79
+ "evlog": "2.37.1",
79
80
  "nitro": "^3.0.261103-rc",
80
81
  "publint": "^0.3.25",
81
82
  "typescript": "^6.0.3",
82
- "vite": "^8.2.2",
83
- "vite-plus": "^0.3.3",
84
- "vitest": "^4.1.11"
83
+ "vite": "^8.3.8",
84
+ "vite-plus": "^1.7.0",
85
+ "vitest": "5.1.0"
85
86
  },
86
87
  "peerDependencies": {
87
88
  "nitro": "3.0.261102-rc || ^3.0.261103-rc",