burger-api 1.0.0-beta → 1.0.0-beta.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.
@@ -54,8 +54,11 @@ export function acceptWsUpgrade(options) {
54
54
  const g = globalThis;
55
55
  const pair = new g.WebSocketPair();
56
56
  const serverSide = pair[0];
57
- wirePushListeners(serverSide, data, events);
57
+ const fireOpen = wirePushListeners(serverSide, data, events);
58
58
  serverSide.accept();
59
+ // workerd never fires 'open' on the server side after accept(), so
60
+ // deliver it here. The guard keeps runtimes that do emit it to one.
61
+ fireOpen();
59
62
  // `webSocket` is the standard Workers/Deno response member; the
60
63
  // base TS lib's ResponseInit does not model it yet.
61
64
  return new Response(null, {
@@ -80,15 +83,21 @@ function wirePushListeners(socket, data, events) {
80
83
  // Push-style sockets (Workers / Deno) need `data` attached explicitly,
81
84
  // or the adapter cannot find the matched route (open/message never fire).
82
85
  socket.data = data;
83
- socket.addEventListener('open', () => {
86
+ let openFired = false;
87
+ const fireOpen = () => {
88
+ if (openFired)
89
+ return;
90
+ openFired = true;
84
91
  void events.onOpen(socket);
85
- });
92
+ };
93
+ socket.addEventListener('open', fireOpen);
86
94
  socket.addEventListener('message', (event) => {
87
95
  void events.onMessage(socket, normalizeWsMessage(event.data));
88
96
  });
89
97
  socket.addEventListener('close', (event) => {
90
98
  void events.onClose(socket, event.code ?? 1005, event.reason ?? '');
91
99
  });
100
+ return fireOpen;
92
101
  }
93
102
  /**
94
103
  * Normalizes a socket message to `string` (text) or `Buffer` (binary).
@@ -8,8 +8,7 @@ import type { CompiledWebSocketRoute } from './types.js';
8
8
  export declare class WebSocketRouter {
9
9
  private routes;
10
10
  private staticRoutes;
11
- private paramRoutes;
12
- private wildcardRoutes;
11
+ private dynamicRoutes;
13
12
  /**
14
13
  * Add a compiled route to the router
15
14
  */
@@ -7,24 +7,19 @@
7
7
  export class WebSocketRouter {
8
8
  routes = [];
9
9
  staticRoutes = new Map();
10
- paramRoutes = [];
11
- wildcardRoutes = [];
10
+ dynamicRoutes = [];
12
11
  /**
13
12
  * Add a compiled route to the router
14
13
  */
15
14
  addRoute(route) {
16
15
  this.routes.push(route);
17
- // Categorize routes. Param and wildcard routes are kept sorted by
18
- // specificity (static segment > param > wildcard at the first
19
- // differing segment; longer wildcard prefix first), matching HTTP
20
- // dispatch. The sort is stable, so equal patterns keep insertion order.
21
- if (route.path.includes('*')) {
22
- this.wildcardRoutes.push(route);
23
- this.wildcardRoutes.sort(compareWildcardSpecificity);
24
- }
25
- else if (route.path.includes(':')) {
26
- this.paramRoutes.push(route);
27
- this.paramRoutes.sort(compareRouteSpecificity);
16
+ // Dynamic routes are kept sorted by specificity (static segment >
17
+ // param > wildcard at the first differing segment), matching HTTP
18
+ // dispatch. The sort is stable, so equal patterns keep insertion
19
+ // order.
20
+ if (route.path.includes('*') || route.path.includes(':')) {
21
+ this.dynamicRoutes.push(route);
22
+ this.dynamicRoutes.sort(compareRouteSpecificity);
28
23
  }
29
24
  else {
30
25
  this.staticRoutes.set(route.path, route);
@@ -52,18 +47,23 @@ export class WebSocketRouter {
52
47
  if (staticRoute) {
53
48
  return { route: staticRoute, params: {}, wildcardParams: [] };
54
49
  }
55
- // Try parameterized routes
56
- for (const route of this.paramRoutes) {
57
- const params = this.matchParams(route.path, path);
58
- if (params !== null) {
59
- return { route, params, wildcardParams: [] };
50
+ // Try dynamic routes in specificity order (params and wildcards mixed).
51
+ for (const route of this.dynamicRoutes) {
52
+ if (route.path.includes('*')) {
53
+ const result = this.matchWildcard(route.path, path);
54
+ if (result !== null) {
55
+ return {
56
+ route,
57
+ params: result.params,
58
+ wildcardParams: result.wildcardParams,
59
+ };
60
+ }
60
61
  }
61
- }
62
- // Try wildcard routes
63
- for (const route of this.wildcardRoutes) {
64
- const result = this.matchWildcard(route.path, path);
65
- if (result !== null) {
66
- return { route, params: result.params, wildcardParams: result.wildcardParams };
62
+ else {
63
+ const params = this.matchParams(route.path, path);
64
+ if (params !== null) {
65
+ return { route, params, wildcardParams: [] };
66
+ }
67
67
  }
68
68
  }
69
69
  return null;
@@ -118,21 +118,34 @@ export class WebSocketRouter {
118
118
  * mirrors HTTP `ctx.wildcardParams`.
119
119
  */
120
120
  matchWildcard(pattern, path) {
121
- // Remove trailing * for comparison
122
- const basePattern = pattern.replace(/\*$/, '');
123
- const basePath = path.slice(0, basePattern.length);
124
- if (basePath !== basePattern) {
121
+ const patternParts = pattern.split('/');
122
+ const wildcardIndex = patternParts.indexOf('*');
123
+ if (wildcardIndex === -1)
125
124
  return null;
126
- }
127
- // Extract wildcard value
128
- const wildcardValue = path.slice(basePattern.length);
129
- const wildcardParams = [];
130
- if (wildcardValue !== '') {
131
- for (const segment of wildcardValue.split('/')) {
132
- wildcardParams.push(decodeSegment(segment));
125
+ const pathParts = path.split('/');
126
+ if (pathParts.length < wildcardIndex)
127
+ return null;
128
+ // Match the fixed prefix segment by segment, exactly like params.
129
+ const params = {};
130
+ for (let i = 0; i < wildcardIndex; i++) {
131
+ const patternPart = patternParts[i];
132
+ const pathPart = pathParts[i];
133
+ if (patternPart.startsWith(':')) {
134
+ if (pathPart === '')
135
+ return null;
136
+ params[patternPart.slice(1)] = decodeSegment(pathPart);
137
+ }
138
+ else if (patternPart !== pathPart) {
139
+ return null;
133
140
  }
134
141
  }
135
- return { params: { '*': wildcardValue }, wildcardParams };
142
+ // The wildcard keeps the raw remainder plus decoded per-segment values.
143
+ const wildcardValue = pathParts.slice(wildcardIndex).join('/');
144
+ const wildcardParams = wildcardValue === ''
145
+ ? []
146
+ : wildcardValue.split('/').map(decodeSegment);
147
+ params['*'] = wildcardValue;
148
+ return { params, wildcardParams };
136
149
  }
137
150
  }
138
151
  /** Decodes a path segment, falling back to the raw value on bad escapes. */
@@ -168,7 +181,3 @@ function compareRouteSpecificity(a, b) {
168
181
  }
169
182
  return 0;
170
183
  }
171
- /** Longer wildcard prefix is more specific. */
172
- function compareWildcardSpecificity(a, b) {
173
- return b.path.replace(/\*$/, '').length - a.path.replace(/\*$/, '').length;
174
- }
@@ -4,6 +4,7 @@
4
4
  import { readdir } from 'node:fs/promises';
5
5
  import * as path from 'node:path';
6
6
  import { resolveScanDir } from '../utils/fs.js';
7
+ import { ROUTE_CONSTANTS } from '../utils/routing.js';
7
8
  import { splitConventionName, } from '../compiler/conventions.js';
8
9
  /** WebSocket convention stems (extension is `.ts` / `.js` / `.mjs`). */
9
10
  const WS_CONVENTION_FILES = ['ws', 'hooks', 'config'];
@@ -27,6 +28,22 @@ export class WebSocketScanner {
27
28
  async scan() {
28
29
  const routes = [];
29
30
  await this.walk(this.wsDir, routes);
31
+ // Groups strip from the URL, so different folders can collide. Detect
32
+ // both exact duplicates and duplicate dynamic shapes (`/:x` vs `/:y`).
33
+ const seenPaths = new Set();
34
+ for (const route of routes) {
35
+ const shape = route.path
36
+ .split('/')
37
+ .map((segment) => segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
38
+ ? ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX
39
+ : segment)
40
+ .join('/');
41
+ if (seenPaths.has(shape)) {
42
+ throw new Error(`Duplicate route path registered: "${route.path}". ` +
43
+ `Two route directories resolve to the same URL.`);
44
+ }
45
+ seenPaths.add(shape);
46
+ }
30
47
  // Detect global hooks at the parent directory
31
48
  let globalHooks;
32
49
  const parentDir = path.dirname(this.wsDir);
@@ -61,6 +78,36 @@ export class WebSocketScanner {
61
78
  let wildcardFolderFound = false;
62
79
  const entries = await readdir(dir, { withFileTypes: true });
63
80
  const subDirs = [];
81
+ // Validate folder-level conflicts before recursing, matching the
82
+ // HTTP scanner's fail-loud rules.
83
+ for (const entry of entries) {
84
+ if (!entry.isDirectory())
85
+ continue;
86
+ const name = entry.name;
87
+ if (name.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
88
+ name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
89
+ throw new Error(`Named wildcard folder '${name}' is not supported — ` +
90
+ `use '${ROUTE_CONSTANTS.WILDCARD_SIMPLE}' (anonymous) instead.`);
91
+ }
92
+ const isDynamic = name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
93
+ name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
94
+ !name.startsWith(ROUTE_CONSTANTS.WILDCARD_START);
95
+ const isWildcard = name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
96
+ // Dynamic + wildcard siblings are legal — the router resolves
97
+ // them by priority (static > `:param` > `*`).
98
+ if (isDynamic && dynamicFolderFound) {
99
+ throw new Error(`Multiple dynamic route folders found in the same directory: ` +
100
+ `'${name}' conflicts with another dynamic folder in '${dir}'.`);
101
+ }
102
+ if (isWildcard && wildcardFolderFound) {
103
+ throw new Error(`Multiple wildcard route folders found in the same directory: ` +
104
+ `'${name}' conflicts with another wildcard folder in '${dir}'.`);
105
+ }
106
+ if (isDynamic)
107
+ dynamicFolderFound = true;
108
+ if (isWildcard)
109
+ wildcardFolderFound = true;
110
+ }
64
111
  // Collect ws / hooks / config files across all accepted extensions.
65
112
  const wsFiles = new Map();
66
113
  for (const entry of entries) {
@@ -107,6 +154,19 @@ export class WebSocketScanner {
107
154
  groupName,
108
155
  });
109
156
  }
157
+ else if (wsFiles.size > 0) {
158
+ // No `ws.ts`, so sibling hooks/config apply to nothing — routes
159
+ // never inherit from parent folders.
160
+ const relativeFolder = path
161
+ .relative(this.wsDir, dir)
162
+ .split(path.sep)
163
+ .join('/');
164
+ const fileNames = [...wsFiles.values()]
165
+ .map((file) => path.basename(file))
166
+ .sort();
167
+ console.warn(`[burger-api] ${relativeFolder || '.'} has ${fileNames.join(', ')} but no ws.ts, so they apply to nothing. ` +
168
+ `Convention files are not inherited by child routes: put hooks.ts/config.ts next to each ws.ts.`);
169
+ }
110
170
  // Process subdirectories. Group directories only affect the URL but
111
171
  // are still walked.
112
172
  for (const subDir of subDirs) {
@@ -70,9 +70,10 @@ export interface WebSocketConfig {
70
70
  */
71
71
  compression?: boolean;
72
72
  /**
73
- * Auth configuration. Set to `false` to disable auth for this route.
73
+ * Auth configuration. `true` requires an authenticated user; `false`
74
+ * disables auth for this route.
74
75
  */
75
- auth?: false | {
76
+ auth?: true | false | {
76
77
  required?: boolean;
77
78
  roles?: string[];
78
79
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "burger-api",
3
- "version": "1.0.0-beta",
3
+ "version": "1.0.0-beta.1",
4
4
  "description": "Fast, file-based API framework for Bun with hooks, Standard Schema validation, OpenAPI and WebSockets. Runs on Bun, Node, Cloudflare Workers, Deno and Vercel.",
5
5
  "author": "Isfhan Ahmed",
6
6
  "type": "module",
@@ -50,7 +50,7 @@
50
50
  "prepare": "bun run build",
51
51
  "test": "bun run test:examples && bun run test:ecosystem && bun run test:lifecycle && bun run test:context && bun run test:utils && bun run test:chain && bun run test:plugin && bun run test:router && bun run test:core && bun run test:errors && bun run test:validation && bun run test:compiler && bun run test:adapter && bun run test:provider && bun run test:smoke && bun run test:ws",
52
52
  "test:examples": "bun test --timeout 30000 --max-concurrency 1 ./examples",
53
- "test:ecosystem": "bun test --timeout 60000 --max-concurrency 1 test/ecosystem-smoke.test.ts test/ecosystem/u16-hardening.test.ts",
53
+ "test:ecosystem": "bun test --timeout 60000 --max-concurrency 1 test/ecosystem-smoke.test.ts test/ecosystem/u16-hardening.test.ts test/ecosystem/correctness.test.ts",
54
54
  "test:lifecycle": "bun test --timeout 30000 ./test/lifecycle",
55
55
  "test:context": "bun test --timeout 30000 ./test/context",
56
56
  "test:utils": "bun test --timeout 30000 ./test/utils",