@vite-hub/rate-limit 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/vite.js +143 -38
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -26,6 +26,8 @@ export async function handleImageUpload(event): Promise<Response> {
26
26
 
27
27
  `requireRateLimit()` can live inside any ordinary H3 handler. Its stable ID and provider policy must use static literals so the Vite integration can generate infrastructure; `event` and an optional dynamic `key` are runtime inputs. The guard defaults to the request's client address and throws an `HTTPError` with status `429` when the budget is exhausted. Pass `key: authenticatedUser.id` when a user or tenant is the correct budget boundary.
28
28
 
29
+ A framework may auto-import the canonical `requireRateLimit` name from this package instead. Discovery recognizes that bare call only when no local runtime binding owns the name.
30
+
29
31
  Provider unavailability follows the declared `failure` policy: fail-open guards continue, while fail-closed guards throw status `503` and preserve the provider cause. Invalid configuration and provider contract violations still throw normally. Use `createRateLimiter()` when the application needs a decision for a custom response or another transport.
30
32
 
31
33
  Add the build integration:
package/dist/vite.js CHANGED
@@ -3,7 +3,7 @@ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver
3
3
  import { memoryRateLimitDriver } from "./drivers/memory.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { cp, mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
6
- import { basename, dirname, relative, resolve } from "node:path";
6
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
7
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { isDeepStrictEqual } from "node:util";
@@ -61,10 +61,10 @@ const resolve$1 = function(...arguments_) {
61
61
  const path = index >= 0 ? arguments_[index] : cwd();
62
62
  if (!path || path.length === 0) continue;
63
63
  resolvedPath = `${path}/${resolvedPath}`;
64
- resolvedAbsolute = isAbsolute(path);
64
+ resolvedAbsolute = isAbsolute$1(path);
65
65
  }
66
66
  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
67
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
67
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
68
68
  return resolvedPath.length > 0 ? resolvedPath : ".";
69
69
  };
70
70
  function normalizeString(path, allowAboveRoot) {
@@ -117,7 +117,7 @@ function normalizeString(path, allowAboveRoot) {
117
117
  }
118
118
  return res;
119
119
  }
120
- const isAbsolute = function(p) {
120
+ const isAbsolute$1 = function(p) {
121
121
  return _IS_ABSOLUTE_RE.test(p);
122
122
  };
123
123
  const relative$1 = function(from, to) {
@@ -135,7 +135,7 @@ const relative$1 = function(from, to) {
135
135
  const dirname$1 = function(p) {
136
136
  const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
137
137
  if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
138
- return segments.join("/") || (isAbsolute(p) ? "/" : ".");
138
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
139
139
  };
140
140
  //#endregion
141
141
  //#region ../internal/src/build/client-output.ts
@@ -226,6 +226,7 @@ function deleteOwnedFields(value, ownership) {
226
226
  return next;
227
227
  }
228
228
  function getKeyedArrayEntryValue(value, key) {
229
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
229
230
  if (!isProviderJsonRecord(value)) return;
230
231
  const entryValue = value[key];
231
232
  return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
@@ -2662,6 +2663,7 @@ error: ${text}`);
2662
2663
  })))();
2663
2664
  const projectRootDirectoryMarkers = [
2664
2665
  ["server", "agents"],
2666
+ ["server", "browsers"],
2665
2667
  ["server", "schedules"],
2666
2668
  ["server", "templates"],
2667
2669
  ["server", "workspaces"]
@@ -2691,8 +2693,8 @@ function includesNitroVitePlugin(value) {
2691
2693
  if (!value || typeof value !== "object") return false;
2692
2694
  return "name" in value && value.name === "nitro:main";
2693
2695
  }
2694
- function hasNitroVitePlugin(config) {
2695
- return includesNitroVitePlugin(config.plugins);
2696
+ function hasNitroConfigContext(config) {
2697
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
2696
2698
  }
2697
2699
  function shouldSkipViteProviderBuild(command, mode) {
2698
2700
  return command === "serve" || mode === "e2e";
@@ -3187,6 +3189,23 @@ async function writeCloudflareDeploymentOutput(options) {
3187
3189
  }
3188
3190
  await Promise.all(writes);
3189
3191
  }
3192
+ async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3193
+ const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
3194
+ const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
3195
+ const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
3196
+ await copyClientOutput(clientDir, staticOutputDir);
3197
+ if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
3198
+ try {
3199
+ await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
3200
+ } catch (error) {
3201
+ if (error.code === "ENOENT") return;
3202
+ throw error;
3203
+ }
3204
+ await rm(resolve(staticOutputDir, outputRelativePath), {
3205
+ force: true,
3206
+ recursive: true
3207
+ });
3208
+ }
3190
3209
  async function writeVercelDeploymentOutput(options) {
3191
3210
  const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3192
3211
  const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
@@ -3208,7 +3227,7 @@ async function writeVercelDeploymentOutput(options) {
3208
3227
  }),
3209
3228
  writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8"),
3210
3229
  writeProviderOutputConfig(resolve(outputRoot, "config.json"), config, { keys: options.configKeys }),
3211
- staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
3230
+ staticIndex ? copyVercelClientOutput(options.rootDir, clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
3212
3231
  ]);
3213
3232
  }
3214
3233
  async function writeNetlifyDeploymentOutput(options) {
@@ -3404,9 +3423,9 @@ function requireRateLimitBindings(program) {
3404
3423
  namespaces: /* @__PURE__ */ new Set()
3405
3424
  };
3406
3425
  for (const statement of program.body) {
3407
- if (statement.type !== "ImportDeclaration" || !rateLimitImports.has(statement.source.value)) continue;
3426
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !rateLimitImports.has(statement.source.value)) continue;
3408
3427
  for (const specifier of statement.specifiers) {
3409
- if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
3428
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
3410
3429
  if (specifier.type === "ImportNamespaceSpecifier") bindings.namespaces.add(specifier.local.name);
3411
3430
  }
3412
3431
  }
@@ -3438,7 +3457,6 @@ function addDynamicRateLimitBindings(declaration, scope) {
3438
3457
  for (const declarator of declaration.declarations) {
3439
3458
  if (!rateLimitDynamicImport(declarator.init)) continue;
3440
3459
  if (declarator.id.type === "Identifier") {
3441
- scope.shadows.delete(declarator.id.name);
3442
3460
  scope.namespaces.add(declarator.id.name);
3443
3461
  continue;
3444
3462
  }
@@ -3448,14 +3466,13 @@ function addDynamicRateLimitBindings(declaration, scope) {
3448
3466
  if ((property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0) !== "requireRateLimit") continue;
3449
3467
  const value = property.value.type === "AssignmentPattern" ? property.value.left : property.value;
3450
3468
  if (value.type !== "Identifier") continue;
3451
- scope.shadows.delete(value.name);
3452
3469
  scope.direct.add(value.name);
3453
3470
  }
3454
3471
  }
3455
3472
  }
3456
3473
  function variableDeclaration(statement) {
3457
- if (statement.type === "VariableDeclaration") return statement;
3458
- if (statement.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration") return statement.declaration;
3474
+ const declaration = runtimeDeclaration(statement);
3475
+ return declaration?.type === "VariableDeclaration" ? declaration : void 0;
3459
3476
  }
3460
3477
  function addDynamicRateLimitBindingsFromStatements(statements, scope) {
3461
3478
  for (const statement of statements) {
@@ -3486,33 +3503,109 @@ function addBindingNames(pattern, names) {
3486
3503
  }
3487
3504
  for (const property of pattern.properties) addBindingNames(property.type === "RestElement" ? property.argument : property.value, names);
3488
3505
  }
3489
- function functionBindings(params) {
3506
+ function hoistedVariableBindings(root) {
3490
3507
  const names = /* @__PURE__ */ new Set();
3491
- for (const parameter of params) addBindingNames(parameter, names);
3508
+ let nestedScopeDepth = 0;
3509
+ const enterNestedScope = () => {
3510
+ nestedScopeDepth += 1;
3511
+ };
3512
+ const exitNestedScope = () => {
3513
+ nestedScopeDepth -= 1;
3514
+ };
3515
+ const program = root.type === "Program" ? root : {
3516
+ ...root,
3517
+ type: "Program",
3518
+ sourceType: "module",
3519
+ hashbang: null,
3520
+ parent: null
3521
+ };
3522
+ new Visitor({
3523
+ ArrowFunctionExpression: enterNestedScope,
3524
+ "ArrowFunctionExpression:exit": exitNestedScope,
3525
+ ClassDeclaration: enterNestedScope,
3526
+ "ClassDeclaration:exit": exitNestedScope,
3527
+ ClassExpression: enterNestedScope,
3528
+ "ClassExpression:exit": exitNestedScope,
3529
+ FunctionDeclaration: enterNestedScope,
3530
+ "FunctionDeclaration:exit": exitNestedScope,
3531
+ FunctionExpression: enterNestedScope,
3532
+ "FunctionExpression:exit": exitNestedScope,
3533
+ StaticBlock: enterNestedScope,
3534
+ "StaticBlock:exit": exitNestedScope,
3535
+ TSModuleDeclaration: enterNestedScope,
3536
+ "TSModuleDeclaration:exit": exitNestedScope,
3537
+ VariableDeclaration(declaration) {
3538
+ if (nestedScopeDepth === 0 && declaration.kind === "var" && !declaration.declare) for (const declarator of declaration.declarations) addBindingNames(declarator.id, names);
3539
+ }
3540
+ }).visit(program);
3492
3541
  return names;
3493
3542
  }
3494
- function variableBindings(declaration) {
3543
+ function functionBindings(node) {
3495
3544
  const names = /* @__PURE__ */ new Set();
3496
- for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
3545
+ if (node.type === "FunctionExpression" && node.id) names.add(node.id.name);
3546
+ for (const parameter of node.params) addBindingNames(parameter, names);
3497
3547
  return names;
3498
3548
  }
3499
- function blockBindings(block) {
3549
+ function runtimeDeclaration(statement) {
3550
+ if (statement.type === "ExportNamedDeclaration") return statement.declaration ?? void 0;
3551
+ if (statement.type === "ExportDefaultDeclaration") {
3552
+ const declaration = statement.declaration;
3553
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") return declaration;
3554
+ }
3555
+ if (statement.type === "VariableDeclaration" || statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration" || statement.type === "TSEnumDeclaration" || statement.type === "TSModuleDeclaration" || statement.type === "TSImportEqualsDeclaration") return statement;
3556
+ }
3557
+ function lexicalBindings(statements) {
3500
3558
  const names = /* @__PURE__ */ new Set();
3501
- for (const statement of block.body) {
3502
- if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id) names.add(statement.id.name);
3503
- const declaration = statement.type === "VariableDeclaration" ? statement : statement.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration" ? statement.declaration : void 0;
3504
- for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
3559
+ for (const statement of statements) {
3560
+ const declaration = runtimeDeclaration(statement);
3561
+ if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) {
3562
+ if (!declaration.declare) names.add(declaration.id.name);
3563
+ }
3564
+ if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var" && !declaration.declare) for (const declarator of declaration.declarations) addBindingNames(declarator.id, names);
3565
+ if (declaration?.type === "TSEnumDeclaration" && !declaration.declare) names.add(declaration.id.name);
3566
+ if (declaration?.type === "TSModuleDeclaration" && !declaration.declare && !declaration.global && declaration.id.type === "Identifier") names.add(declaration.id.name);
3567
+ if (declaration?.type === "TSImportEqualsDeclaration" && declaration.importKind !== "type") names.add(declaration.id.name);
3505
3568
  }
3506
3569
  return names;
3507
3570
  }
3508
- function switchBindings(statement) {
3509
- const names = /* @__PURE__ */ new Set();
3510
- for (const switchCase of statement.cases) for (const child of switchCase.consequent) {
3511
- if ((child.type === "FunctionDeclaration" || child.type === "ClassDeclaration") && child.id) names.add(child.id.name);
3512
- if (child.type === "VariableDeclaration") for (const name of variableBindings(child)) names.add(name);
3571
+ function programBindings(program) {
3572
+ const names = lexicalBindings(program.body);
3573
+ for (const name of hoistedVariableBindings(program)) names.add(name);
3574
+ for (const statement of program.body) {
3575
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
3576
+ for (const specifier of statement.specifiers) if (specifier.type !== "ImportSpecifier" || specifier.importKind !== "type") names.add(specifier.local.name);
3513
3577
  }
3514
3578
  return names;
3515
3579
  }
3580
+ function blockBindings(block) {
3581
+ return lexicalBindings(block.body);
3582
+ }
3583
+ function scopedStatementBindings(statements) {
3584
+ const names = lexicalBindings(statements);
3585
+ const program = {
3586
+ type: "Program",
3587
+ body: statements,
3588
+ sourceType: "module",
3589
+ hashbang: null,
3590
+ parent: null,
3591
+ start: 0,
3592
+ end: 0
3593
+ };
3594
+ for (const name of hoistedVariableBindings(program)) names.add(name);
3595
+ return names;
3596
+ }
3597
+ function variableBindings(declaration) {
3598
+ const names = /* @__PURE__ */ new Set();
3599
+ for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
3600
+ return names;
3601
+ }
3602
+ function loopBindings(declaration) {
3603
+ if (declaration?.kind === "var") return /* @__PURE__ */ new Set();
3604
+ return variableBindings(declaration);
3605
+ }
3606
+ function switchBindings(statement) {
3607
+ return lexicalBindings(statement.cases.flatMap((switchCase) => switchCase.consequent));
3608
+ }
3516
3609
  function staticPropertyName(property) {
3517
3610
  if (property.computed || property.kind !== "init" || property.method) return;
3518
3611
  if (property.key.type === "Identifier") return property.key.name;
@@ -3558,12 +3651,15 @@ function extractRateLimitDeclarations(file, source) {
3558
3651
  if (!source.includes("requireRateLimit")) return [];
3559
3652
  const parsed = parseSync(file, source);
3560
3653
  if (parsed.errors.length > 0) throw new Error(`[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}`);
3654
+ const rootShadows = programBindings(parsed.program);
3561
3655
  const bindings = requireRateLimitBindings(parsed.program);
3656
+ if (!rootShadows.has("requireRateLimit")) bindings.direct.add("requireRateLimit");
3562
3657
  const declarations = [];
3563
3658
  const scopes = [{
3564
3659
  ...bindings,
3565
- shadows: /* @__PURE__ */ new Set()
3660
+ shadows: rootShadows
3566
3661
  }];
3662
+ const functionBodies = /* @__PURE__ */ new WeakSet();
3567
3663
  addDynamicRateLimitBindingsFromStatements(parsed.program.body, scopes[0]);
3568
3664
  const enterScope = (shadows) => {
3569
3665
  scopes.push({
@@ -3573,9 +3669,8 @@ function extractRateLimitDeclarations(file, source) {
3573
3669
  });
3574
3670
  };
3575
3671
  const enterFunction = (node) => {
3576
- const shadows = functionBindings(node.params);
3577
- if (node.type === "FunctionExpression" && node.id) shadows.add(node.id.name);
3578
- enterScope(shadows);
3672
+ enterScope(functionBindings(node));
3673
+ if (node.body?.type === "BlockStatement") functionBodies.add(node.body);
3579
3674
  };
3580
3675
  const exitScope = () => {
3581
3676
  scopes.pop();
@@ -3584,7 +3679,7 @@ function extractRateLimitDeclarations(file, source) {
3584
3679
  ArrowFunctionExpression: enterFunction,
3585
3680
  "ArrowFunctionExpression:exit": exitScope,
3586
3681
  BlockStatement(block) {
3587
- enterScope(blockBindings(block));
3682
+ enterScope(functionBodies.has(block) ? scopedStatementBindings(block.body) : blockBindings(block));
3588
3683
  addDynamicRateLimitBindingsFromStatements(block.body, scopes.at(-1));
3589
3684
  },
3590
3685
  "BlockStatement:exit": exitScope,
@@ -3620,22 +3715,32 @@ function extractRateLimitDeclarations(file, source) {
3620
3715
  FunctionExpression: enterFunction,
3621
3716
  "FunctionExpression:exit": exitScope,
3622
3717
  ForInStatement(node) {
3623
- enterScope(node.left.type === "VariableDeclaration" ? variableBindings(node.left) : /* @__PURE__ */ new Set());
3718
+ enterScope(node.left.type === "VariableDeclaration" ? loopBindings(node.left) : /* @__PURE__ */ new Set());
3624
3719
  },
3625
3720
  "ForInStatement:exit": exitScope,
3626
3721
  ForOfStatement(node) {
3627
- enterScope(node.left.type === "VariableDeclaration" ? variableBindings(node.left) : /* @__PURE__ */ new Set());
3722
+ enterScope(node.left.type === "VariableDeclaration" ? loopBindings(node.left) : /* @__PURE__ */ new Set());
3628
3723
  },
3629
3724
  "ForOfStatement:exit": exitScope,
3630
3725
  ForStatement(node) {
3631
- enterScope(node.init?.type === "VariableDeclaration" ? variableBindings(node.init) : /* @__PURE__ */ new Set());
3726
+ enterScope(node.init?.type === "VariableDeclaration" ? loopBindings(node.init) : /* @__PURE__ */ new Set());
3632
3727
  },
3633
3728
  "ForStatement:exit": exitScope,
3634
3729
  SwitchStatement(node) {
3635
3730
  enterScope(switchBindings(node));
3636
3731
  for (const switchCase of node.cases) addDynamicRateLimitBindingsFromStatements(switchCase.consequent, scopes.at(-1));
3637
3732
  },
3638
- "SwitchStatement:exit": exitScope
3733
+ "SwitchStatement:exit": exitScope,
3734
+ StaticBlock(node) {
3735
+ enterScope(scopedStatementBindings(node.body));
3736
+ addDynamicRateLimitBindingsFromStatements(node.body, scopes.at(-1));
3737
+ },
3738
+ "StaticBlock:exit": exitScope,
3739
+ TSModuleBlock(node) {
3740
+ enterScope(scopedStatementBindings(node.body));
3741
+ addDynamicRateLimitBindingsFromStatements(node.body, scopes.at(-1));
3742
+ },
3743
+ "TSModuleBlock:exit": exitScope
3639
3744
  }).visit(parsed.program);
3640
3745
  return declarations;
3641
3746
  }
@@ -3898,7 +4003,7 @@ function hubRateLimit(options = {}) {
3898
4003
  projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
3899
4004
  const configuredNitro = config.nitro;
3900
4005
  const nitroCloudflare = resolveNitroHosting(configuredNitro) === "cloudflare";
3901
- cloudflareOwnedByNitro = hasNitroVitePlugin(config) && nitroCloudflare;
4006
+ cloudflareOwnedByNitro = hasNitroConfigContext(config) && nitroCloudflare;
3902
4007
  provider = resolveProvider(rateLimit, config.command, configuredNitro);
3903
4008
  collectDeclarations();
3904
4009
  config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/rate-limit",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Provider-neutral Rate Limit primitives and Vite deployment integration for ViteHub.",
5
5
  "keywords": [
6
6
  "cloudflare",