burger-api 0.9.7 → 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.
Files changed (175) hide show
  1. package/README.md +84 -241
  2. package/dist/src/adapter/bun/index.d.ts +14 -0
  3. package/dist/src/adapter/bun/index.js +73 -0
  4. package/dist/src/adapter/bun/types.d.ts +15 -0
  5. package/dist/src/adapter/bun/types.js +1 -0
  6. package/dist/src/adapter/index.d.ts +1 -0
  7. package/dist/src/adapter/index.js +1 -0
  8. package/dist/src/adapter/types.d.ts +49 -0
  9. package/dist/src/adapter/types.js +1 -0
  10. package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
  11. package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
  12. package/dist/src/adapter/web-standard/index.d.ts +8 -0
  13. package/dist/src/adapter/web-standard/index.js +7 -0
  14. package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
  15. package/dist/src/analysis/route-access-analyzer.js +287 -0
  16. package/dist/src/chain/chain.d.ts +16 -0
  17. package/dist/src/chain/chain.js +17 -0
  18. package/dist/src/chain/flattener.d.ts +3 -0
  19. package/dist/src/chain/flattener.js +78 -0
  20. package/dist/src/chain/node.d.ts +25 -0
  21. package/dist/src/chain/node.js +1 -0
  22. package/dist/src/compiler/conventions.d.ts +67 -0
  23. package/dist/src/compiler/conventions.js +129 -0
  24. package/dist/src/compiler/index.d.ts +13 -0
  25. package/dist/src/compiler/index.js +11 -0
  26. package/dist/src/compiler/module-loader.d.ts +75 -0
  27. package/dist/src/compiler/module-loader.js +276 -0
  28. package/dist/src/compiler/route-module.d.ts +97 -0
  29. package/dist/src/compiler/route-module.js +1 -0
  30. package/dist/src/compiler/route-tree.d.ts +19 -0
  31. package/dist/src/compiler/route-tree.js +28 -0
  32. package/dist/src/compiler/scanner.d.ts +42 -0
  33. package/dist/src/compiler/scanner.js +240 -0
  34. package/dist/src/context/context-set.d.ts +26 -0
  35. package/dist/src/context/context-set.js +45 -0
  36. package/dist/src/context/context.d.ts +357 -0
  37. package/dist/src/context/context.js +401 -0
  38. package/dist/src/context/query-parser.d.ts +23 -0
  39. package/dist/src/context/query-parser.js +132 -0
  40. package/dist/src/context/route-access.d.ts +7 -0
  41. package/dist/src/context/route-access.js +18 -0
  42. package/dist/src/context/types.d.ts +62 -0
  43. package/dist/src/context/types.js +5 -0
  44. package/dist/src/core/asset-mime.d.ts +9 -0
  45. package/dist/src/core/asset-mime.js +35 -0
  46. package/dist/src/core/assets.d.ts +30 -0
  47. package/dist/src/core/assets.js +67 -0
  48. package/dist/src/core/docs-providers.d.ts +13 -0
  49. package/dist/src/core/docs-providers.js +89 -0
  50. package/dist/src/core/embedded-assets.d.ts +18 -0
  51. package/dist/src/core/embedded-assets.js +13 -0
  52. package/dist/src/core/openapi.d.ts +9 -10
  53. package/dist/src/core/openapi.js +333 -127
  54. package/dist/src/core/page-router.d.ts +13 -17
  55. package/dist/src/core/page-router.js +86 -55
  56. package/dist/src/core/server.d.ts +20 -11
  57. package/dist/src/core/server.js +41 -45
  58. package/dist/src/errors/forbidden.d.ts +14 -0
  59. package/dist/src/errors/forbidden.js +16 -0
  60. package/dist/src/errors/http-error.d.ts +49 -0
  61. package/dist/src/errors/http-error.js +155 -0
  62. package/dist/src/errors/method-not-allowed.d.ts +13 -0
  63. package/dist/src/errors/method-not-allowed.js +15 -0
  64. package/dist/src/errors/not-found.d.ts +14 -0
  65. package/dist/src/errors/not-found.js +16 -0
  66. package/dist/src/errors/unauthorized.d.ts +14 -0
  67. package/dist/src/errors/unauthorized.js +16 -0
  68. package/dist/src/index.d.ts +275 -50
  69. package/dist/src/index.js +974 -333
  70. package/dist/src/lifecycle/executor.d.ts +64 -0
  71. package/dist/src/lifecycle/executor.js +201 -0
  72. package/dist/src/lifecycle/hook-runner.d.ts +11 -0
  73. package/dist/src/lifecycle/hook-runner.js +156 -0
  74. package/dist/src/lifecycle/jit.d.ts +50 -0
  75. package/dist/src/lifecycle/jit.js +258 -0
  76. package/dist/src/lifecycle/transform.d.ts +26 -0
  77. package/dist/src/lifecycle/transform.js +99 -0
  78. package/dist/src/lifecycle/types.d.ts +135 -0
  79. package/dist/src/lifecycle/types.js +1 -0
  80. package/dist/src/plugin/composer.d.ts +3 -0
  81. package/dist/src/plugin/composer.js +28 -0
  82. package/dist/src/plugin/registry.d.ts +25 -0
  83. package/dist/src/plugin/registry.js +107 -0
  84. package/dist/src/plugin/types.d.ts +20 -0
  85. package/dist/src/plugin/types.js +1 -0
  86. package/dist/src/router/allow-cache.d.ts +20 -0
  87. package/dist/src/router/allow-cache.js +26 -0
  88. package/dist/src/router/compiler.d.ts +39 -0
  89. package/dist/src/router/compiler.js +867 -0
  90. package/dist/src/router/define.d.ts +67 -0
  91. package/dist/src/router/define.js +34 -0
  92. package/dist/src/router/index.d.ts +6 -0
  93. package/dist/src/router/index.js +5 -0
  94. package/dist/src/router/param-extract.d.ts +33 -0
  95. package/dist/src/router/param-extract.js +87 -0
  96. package/dist/src/router/regex-matcher.d.ts +42 -0
  97. package/dist/src/router/regex-matcher.js +216 -0
  98. package/dist/src/router/router.d.ts +214 -0
  99. package/dist/src/router/router.js +670 -0
  100. package/dist/src/router/static-map.d.ts +39 -0
  101. package/dist/src/router/static-map.js +48 -0
  102. package/dist/src/router/trie.d.ts +69 -0
  103. package/dist/src/router/trie.js +572 -0
  104. package/dist/src/router/types.d.ts +104 -0
  105. package/dist/src/router/types.js +1 -0
  106. package/dist/src/runtime/capabilities.d.ts +29 -0
  107. package/dist/src/runtime/capabilities.js +48 -0
  108. package/dist/src/types/index.d.ts +260 -109
  109. package/dist/src/types/index.js +1 -1
  110. package/dist/src/types/inference.d.ts +78 -0
  111. package/dist/src/types/inference.js +20 -0
  112. package/dist/src/types/openapi-config.d.ts +164 -0
  113. package/dist/src/types/openapi-config.js +8 -0
  114. package/dist/src/utils/env.d.ts +13 -0
  115. package/dist/src/utils/env.js +24 -0
  116. package/dist/src/utils/fs.d.ts +29 -0
  117. package/dist/src/utils/fs.js +75 -0
  118. package/dist/src/utils/index.d.ts +1 -1
  119. package/dist/src/utils/index.js +2 -2
  120. package/dist/src/utils/pathConversion.js +13 -7
  121. package/dist/src/utils/response.d.ts +42 -6
  122. package/dist/src/utils/response.js +189 -7
  123. package/dist/src/utils/routing.d.ts +32 -13
  124. package/dist/src/utils/routing.js +41 -18
  125. package/dist/src/utils/thenable.d.ts +8 -0
  126. package/dist/src/utils/thenable.js +12 -0
  127. package/dist/src/utils/timing-safe.d.ts +9 -0
  128. package/dist/src/utils/timing-safe.js +20 -0
  129. package/dist/src/utils/wildcard.d.ts +6 -7
  130. package/dist/src/utils/wildcard.js +38 -55
  131. package/dist/src/validation/adapter.d.ts +54 -0
  132. package/dist/src/validation/adapter.js +75 -0
  133. package/dist/src/validation/adapters/standard.d.ts +11 -0
  134. package/dist/src/validation/adapters/standard.js +110 -0
  135. package/dist/src/validation/adapters/zod.d.ts +9 -0
  136. package/dist/src/validation/adapters/zod.js +128 -0
  137. package/dist/src/validation/cache.d.ts +26 -0
  138. package/dist/src/validation/cache.js +35 -0
  139. package/dist/src/validation/coerce.d.ts +28 -0
  140. package/dist/src/validation/coerce.js +176 -0
  141. package/dist/src/validation/compiler.d.ts +27 -0
  142. package/dist/src/validation/compiler.js +191 -0
  143. package/dist/src/validation/error.d.ts +69 -0
  144. package/dist/src/validation/error.js +137 -0
  145. package/dist/src/validation/index.d.ts +16 -0
  146. package/dist/src/validation/index.js +12 -0
  147. package/dist/src/validation/response.d.ts +25 -0
  148. package/dist/src/validation/response.js +85 -0
  149. package/dist/src/validation/types.d.ts +148 -0
  150. package/dist/src/validation/types.js +6 -0
  151. package/dist/src/validation/validator.d.ts +39 -0
  152. package/dist/src/validation/validator.js +441 -0
  153. package/dist/src/ws/adapter.d.ts +230 -0
  154. package/dist/src/ws/adapter.js +660 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +178 -0
  157. package/dist/src/ws/index.d.ts +11 -0
  158. package/dist/src/ws/index.js +8 -0
  159. package/dist/src/ws/platform.d.ts +82 -0
  160. package/dist/src/ws/platform.js +122 -0
  161. package/dist/src/ws/router.d.ts +47 -0
  162. package/dist/src/ws/router.js +183 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +253 -0
  165. package/dist/src/ws/types.d.ts +381 -0
  166. package/dist/src/ws/types.js +213 -0
  167. package/package.json +72 -60
  168. package/dist/src/core/api-router.d.ts +0 -65
  169. package/dist/src/core/api-router.js +0 -264
  170. package/dist/src/core/swagger-ui.d.ts +0 -1
  171. package/dist/src/core/swagger-ui.js +0 -33
  172. package/dist/src/middleware/validator.d.ts +0 -14
  173. package/dist/src/middleware/validator.js +0 -133
  174. package/dist/src/utils/error.d.ts +0 -17
  175. package/dist/src/utils/error.js +0 -63
@@ -1,13 +1,15 @@
1
- // Import stuff from node
2
- import { readdirSync } from 'fs';
3
- import * as path from 'path';
1
+ // Bun has no native recursive directory walker, so traversal uses Node's
2
+ // `fs/promises` via Bun's compatibility layer. `node:path` is only used for
3
+ // OS-agnostic path string joins.
4
+ import { readdir } from 'node:fs/promises';
5
+ import * as path from 'node:path';
4
6
  // Import utils
5
- import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index';
6
- import { filePathToPageRoutePath } from '../utils/pathConversion';
7
+ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
8
+ import { resolveScanDir } from '../utils/fs.js';
9
+ import { filePathToPageRoutePath } from '../utils/pathConversion.js';
7
10
  /**
8
- * PageRouter class for handling file-based page routing.
9
- * Loads pages from a directory structure and matches requests to the appropriate page handlers.
10
- * Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
11
+ * File-based page router: loads pages from a directory tree, matches requests,
12
+ * and supports dynamic segments (e.g. `[id]`). Default exports are handlers.
11
13
  */
12
14
  export class PageRouter {
13
15
  pagesDir;
@@ -15,9 +17,8 @@ export class PageRouter {
15
17
  /** Array of loaded page definitions */
16
18
  pages = [];
17
19
  /**
18
- * Constructor for the PageRouter class.
19
- * @param pagesDir The directory path where page modules are located.
20
- * @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
20
+ * @param pagesDir Directory containing page modules.
21
+ * @param prefix Optional prefix for every route (e.g. "pages" → "/pages/...").
21
22
  */
22
23
  constructor(pagesDir, prefix = '') {
23
24
  this.pagesDir = pagesDir;
@@ -25,24 +26,18 @@ export class PageRouter {
25
26
  if (!pagesDir) {
26
27
  throw new Error('Pages directory path must be provided');
27
28
  }
28
- // Normalize the pagesDir path
29
- this.pagesDir = path.normalize(pagesDir);
30
- // Normalize the prefix if provided
29
+ this.pagesDir = path.normalize(resolveScanDir(pagesDir, 'Pages', 'pageDir'));
31
30
  if (prefix) {
32
31
  this.prefix = cleanPrefix(prefix);
33
32
  }
34
33
  }
35
34
  /**
36
- * Loads page modules from the specified directory and adds them to the pages array.
37
- * After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
38
- * @returns A promise that resolves when all page modules have been loaded and sorted.
35
+ * Loads and sorts page modules (static routes before dynamic ones).
39
36
  */
40
37
  async loadPages() {
41
- // Clear the pages array
42
38
  this.pages = [];
43
39
  try {
44
40
  await this.scanDirectory(this.pagesDir);
45
- // Sort pages to ensure static routes are matched before dynamic ones
46
41
  this.pages.sort((a, b) => compareRoutes(a, b));
47
42
  }
48
43
  catch (error) {
@@ -51,19 +46,28 @@ export class PageRouter {
51
46
  }
52
47
  }
53
48
  /**
54
- * Recursively scans the directory for page modules and adds them to the pages array.
55
- * @param dir The current directory to scan.
56
- * @param basePath The base path for constructing the route path.
49
+ * Recursively scans `dir` for page modules.
50
+ * @param dir Directory to scan.
51
+ * @param basePath Base path used to build route paths.
57
52
  */
58
53
  async scanDirectory(dir, basePath = '') {
59
- // Track if a dynamic folder has been found at this directory level
54
+ // Tracks whether a dynamic folder or file was already seen at this
55
+ // level (two `[param]` entries would be ambiguous).
60
56
  let dynamicFolderFound = false;
57
+ let dynamicFileFound = false;
61
58
  try {
62
- const entries = readdirSync(dir, { withFileTypes: true });
59
+ const entries = await readdir(dir, { withFileTypes: true });
63
60
  for (const entry of entries) {
64
61
  const entryPath = path.join(dir, entry.name);
65
62
  const relativePath = path.join(basePath, entry.name);
66
63
  if (entry.isDirectory()) {
64
+ // Named wildcard folders (`[...slug]`) can never match a
65
+ // page route — fail loud instead of silently dropping them.
66
+ if (entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
67
+ entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
68
+ throw new Error(`Named wildcard folder '${entry.name}' is not supported — ` +
69
+ `use '${ROUTE_CONSTANTS.WILDCARD_SIMPLE}' (anonymous) instead.`);
70
+ }
67
71
  if (entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
68
72
  continue;
69
73
  }
@@ -79,35 +83,55 @@ export class PageRouter {
79
83
  }
80
84
  else if (entry.isFile() &&
81
85
  ROUTE_CONSTANTS.SUPPORTED_PAGE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
86
+ // Two dynamic files (`[a].tsx` + `[b].tsx`) at the same
87
+ // level are ambiguous — fail loud like dynamic folders.
88
+ if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
89
+ entry.name.includes(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
90
+ if (dynamicFileFound) {
91
+ throw new Error(`Multiple dynamic page files found in the same directory: '${entry.name}' conflicts with another dynamic file.`);
92
+ }
93
+ dynamicFileFound = true;
94
+ }
82
95
  // Convert file path to route path and load the module
83
96
  const cleanedRoutePath = filePathToPageRoutePath(relativePath, this.prefix);
84
- // Get the module path
85
- const modulePath = path.resolve(entryPath);
86
- try {
87
- // Import the module
88
- const pageModule = await import(modulePath);
89
- // Get the default export as the page handler
90
- if (entry.name.endsWith('.tsx') &&
91
- typeof pageModule.default !== 'function') {
92
- throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
93
- }
94
- // Create page definition
95
- const pageDefWithSlash = {
96
- path: cleanedRoutePath + '/',
97
- handler: pageModule.default,
98
- middleware: pageModule.middleware,
99
- };
100
- // Create page definition
101
- const pageDef = {
102
- path: cleanedRoutePath,
103
- handler: pageModule.default,
104
- middleware: pageModule.middleware,
105
- };
106
- // Add the page definition to the pages array
107
- this.pages.push(pageDefWithSlash, pageDef);
97
+ // `.html` files are imported as raw markup — Bun's default
98
+ // `.html` import yields an HTMLBundle that would crash on
99
+ // `toFetchHandler`.
100
+ const isHtmlPage = entry.name.endsWith('.html');
101
+ const modulePath = path.resolve(isHtmlPage ? entryPath + '?raw' : entryPath);
102
+ const pageModule = await import(modulePath);
103
+ // `.tsx` pages export a function; `.html` pages export raw
104
+ // markup — wrap it so both Bun and WinterCG serve text/html.
105
+ let handler;
106
+ if (typeof pageModule.default === 'function') {
107
+ handler = pageModule.default;
108
108
  }
109
- catch (importError) {
110
- console.error(`Failed to import module at ${modulePath}:`, importError);
109
+ else if (typeof pageModule.default === 'string') {
110
+ handler = () => new Response(pageModule.default, {
111
+ headers: {
112
+ 'Content-Type': 'text/html; charset=utf-8',
113
+ },
114
+ });
115
+ }
116
+ else {
117
+ throw new Error(`Page at ${entryPath} must export a default function or an HTML string as its handler.`);
118
+ }
119
+ const pageDef = {
120
+ path: cleanedRoutePath,
121
+ handler,
122
+ source: entryPath,
123
+ };
124
+ this.pages.push(pageDef);
125
+ // Non-root pages also answer the trailing-slash variant.
126
+ // The root already ends in `/` — adding another would
127
+ // create the odd `//` route key.
128
+ if (cleanedRoutePath !== '/' &&
129
+ !cleanedRoutePath.endsWith('/')) {
130
+ this.pages.push({
131
+ path: cleanedRoutePath + '/',
132
+ handler,
133
+ source: entryPath,
134
+ });
111
135
  }
112
136
  }
113
137
  }
@@ -118,9 +142,9 @@ export class PageRouter {
118
142
  }
119
143
  }
120
144
  /**
121
- * Resolves the given request by finding a matching page and extracting dynamic parameters.
145
+ * Finds the page matching the request and extracts dynamic params.
122
146
  * @param request The request to resolve.
123
- * @returns An object containing the matched page and parameters, or an empty params object if no match.
147
+ * @returns The matched page + params, or empty params when nothing matches.
124
148
  */
125
149
  resolve(request) {
126
150
  const url = new URL(request.url);
@@ -137,10 +161,10 @@ export class PageRouter {
137
161
  return { params: {} };
138
162
  }
139
163
  /**
140
- * Checks if the request path matches the page path, extracting dynamic parameters if matched.
164
+ * Matches a request path against a page path.
141
165
  * @param requestPath The request path to check.
142
166
  * @param pagePath The page path to match against.
143
- * @returns A record of dynamic parameters if matched, otherwise null.
167
+ * @returns Captured params when matched, otherwise null.
144
168
  */
145
169
  matchRoute(requestPath, pagePath) {
146
170
  const reqSegments = requestPath.split('/').filter(Boolean);
@@ -154,7 +178,14 @@ export class PageRouter {
154
178
  const reqSegment = reqSegments[i];
155
179
  if (pSegment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
156
180
  const paramName = pSegment.slice(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX.length);
157
- params[paramName] = reqSegment;
181
+ // Percent-decode the captured value; fall back to the raw
182
+ // segment on malformed encoding.
183
+ try {
184
+ params[paramName] = decodeURIComponent(reqSegment);
185
+ }
186
+ catch {
187
+ params[paramName] = reqSegment;
188
+ }
158
189
  }
159
190
  else if (pSegment !== reqSegment) {
160
191
  return null;
@@ -1,19 +1,28 @@
1
- import type { HTMLBundle } from 'bun';
2
- import type { ServerOptions, FetchHandler, RequestHandler } from '../types/index';
1
+ import type { ServerOptions } from '../types/index.js';
2
+ import type { AdapterStartOptions, RuntimeAdapter } from '../adapter/types.js';
3
+ import type { BunAdapterStartOptions } from '../adapter/bun/types.js';
4
+ /**
5
+ * Thin server wrapper. Owns the runtime adapter and delegates bootstrap to it.
6
+ * The Bun adapter loads lazily on first `start()`, so WinterCG bundles — which
7
+ * only use `toFetchHandler()` — never contain a `bun` import.
8
+ */
3
9
  export declare class Server {
4
10
  private options;
5
- private server;
11
+ private adapter?;
12
+ private handle?;
13
+ constructor(options: ServerOptions, adapter?: RuntimeAdapter);
6
14
  /**
7
- * Initializes a new instance of the Server class with the given options.
8
- * @param options - Configuration options for the server.
15
+ * Starts the server via the configured adapter, loading the Bun adapter
16
+ * lazily on first use.
17
+ * @param opts adapter bootstrap options (static routes, fetch fallback, port).
9
18
  */
10
- constructor(options: ServerOptions);
11
- start(routes: Record<string, HTMLBundle | RequestHandler> | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
19
+ start(opts: AdapterStartOptions | BunAdapterStartOptions): Promise<void>;
12
20
  /**
13
- * Stops the server.
14
- * If the server is currently running, this method will stop the server and
15
- * log a message to the console indicating that the server has been stopped.
16
- * If the server is not running, this method does nothing.
21
+ * Stops the running server (no-op if it was never started).
17
22
  */
18
23
  stop(): void;
24
+ /**
25
+ * Returns true once the adapter has started a server.
26
+ */
27
+ isRunning(): boolean;
19
28
  }
@@ -1,58 +1,54 @@
1
- // Import stuff from Bun
2
- import { serve } from 'bun';
3
- // Import stuff from utils
4
- import { errorResponse } from '../utils/error';
1
+ /**
2
+ * Non-foldable module id for the Bun adapter: bundlers keep dynamic imports
3
+ * with non-static specifiers external, so `bun` never enters WinterCG bundles.
4
+ */
5
+ function adapterModuleId() {
6
+ return ['burger-api', 'adapter', 'bun'].join('/');
7
+ }
8
+ /**
9
+ * Thin server wrapper. Owns the runtime adapter and delegates bootstrap to it.
10
+ * The Bun adapter loads lazily on first `start()`, so WinterCG bundles — which
11
+ * only use `toFetchHandler()` — never contain a `bun` import.
12
+ */
5
13
  export class Server {
6
14
  options;
7
- server = null;
8
- /**
9
- * Initializes a new instance of the Server class with the given options.
10
- * @param options - Configuration options for the server.
11
- */
12
- constructor(options) {
15
+ adapter;
16
+ handle;
17
+ constructor(options, adapter) {
13
18
  this.options = options;
19
+ this.adapter = adapter;
14
20
  }
15
- start(routes, handler, port, cb) {
16
- // Start Bun's native server using Bun.serve
17
- const serveOptions = {
18
- routes,
19
- fetch: async (request) => {
20
- try {
21
- return await handler(request);
22
- }
23
- catch (error) {
24
- return errorResponse(error, request, this.options.debug ?? false);
25
- }
26
- },
27
- error(error) {
28
- console.error(error);
29
- return new Response(`Internal Server Error: ${error.message}`, {
30
- status: 500,
31
- headers: {
32
- 'Content-Type': 'text/plain',
33
- },
34
- });
35
- },
36
- port,
37
- };
38
- this.server = serve(serveOptions);
39
- if (cb) {
40
- cb();
41
- }
42
- else {
43
- console.log(`🍔 BurgerAPI is running at: http://${this.options.hostname || 'localhost'}:${port}`);
21
+ /**
22
+ * Starts the server via the configured adapter, loading the Bun adapter
23
+ * lazily on first use.
24
+ * @param opts adapter bootstrap options (static routes, fetch fallback, port).
25
+ */
26
+ async start(opts) {
27
+ if (!this.adapter) {
28
+ const { BunAdapter } = (await import(adapterModuleId()));
29
+ this.adapter = new BunAdapter();
44
30
  }
31
+ this.handle = this.adapter.start({
32
+ ...opts,
33
+ hostname: opts.hostname ?? this.options.hostname,
34
+ debug: opts.debug ?? this.options.debug,
35
+ maxRequestBodySize: opts.maxRequestBodySize ?? this.options.maxRequestBodySize,
36
+ });
45
37
  }
46
38
  /**
47
- * Stops the server.
48
- * If the server is currently running, this method will stop the server and
49
- * log a message to the console indicating that the server has been stopped.
50
- * If the server is not running, this method does nothing.
39
+ * Stops the running server (no-op if it was never started).
51
40
  */
52
41
  stop() {
53
- if (this.server) {
54
- this.server.stop();
42
+ if (this.handle) {
43
+ this.handle.stop();
55
44
  console.log('Server stopped.');
45
+ this.handle = undefined;
56
46
  }
57
47
  }
48
+ /**
49
+ * Returns true once the adapter has started a server.
50
+ */
51
+ isRunning() {
52
+ return this.handle !== undefined;
53
+ }
58
54
  }
@@ -0,0 +1,14 @@
1
+ import { HTTPError } from './http-error.js';
2
+ /**
3
+ * 403 Forbidden — thrown when the user is authenticated but lacks permission.
4
+ *
5
+ * @example
6
+ * throw new ForbiddenError();
7
+ * throw new ForbiddenError('Insufficient permissions');
8
+ * throw new ForbiddenError('Admin only', { cause: roleError });
9
+ */
10
+ export declare class ForbiddenError extends HTTPError {
11
+ readonly name = "ForbiddenError";
12
+ readonly status: 403;
13
+ constructor(message?: string, options?: ErrorOptions);
14
+ }
@@ -0,0 +1,16 @@
1
+ import { HTTPError } from './http-error.js';
2
+ /**
3
+ * 403 Forbidden — thrown when the user is authenticated but lacks permission.
4
+ *
5
+ * @example
6
+ * throw new ForbiddenError();
7
+ * throw new ForbiddenError('Insufficient permissions');
8
+ * throw new ForbiddenError('Admin only', { cause: roleError });
9
+ */
10
+ export class ForbiddenError extends HTTPError {
11
+ name = 'ForbiddenError';
12
+ status = 403;
13
+ constructor(message, options) {
14
+ super(403, message ?? 'Forbidden', options);
15
+ }
16
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Base HTTP error class for BurgerAPI.
3
+ *
4
+ * All framework errors extend this; each subclass sets a static `status` and a
5
+ * default `name`. The `onError` pipeline renders them as RFC 9457 Problem
6
+ * Details. Subclasses: ValidationError (422), NotFoundError (404),
7
+ * UnauthorizedError (401), ForbiddenError (403), MethodNotAllowedError (405).
8
+ */
9
+ export declare class HTTPError extends Error {
10
+ /** HTTP status code for this error. */
11
+ readonly status: number;
12
+ constructor(status: number, message: string, options?: ErrorOptions);
13
+ }
14
+ /**
15
+ * Logs a 5xx error that no user `onError` hook handled. Server-side only:
16
+ * one line of context plus the error and its stack.
17
+ */
18
+ export declare function logUnhandledError(method: string, url: string, error: unknown): void;
19
+ /**
20
+ * Renders an error that escaped the request pipeline as RFC 9457 and logs it
21
+ * when it is a server-side failure. Shared by the Bun adapter, the router's
22
+ * pre-routing path and the WinterCG fetch entry, so uncaught errors render
23
+ * identically on every runtime.
24
+ */
25
+ export declare function renderUncaught(error: unknown, request: {
26
+ method: string;
27
+ url: string;
28
+ }, debug?: boolean): Response;
29
+ /**
30
+ * Renders an `HTTPError` (or subclass) as an RFC 9457 Problem Details
31
+ * response (`application/problem+json`).
32
+ *
33
+ * - Dev mode adds `stack` and the `cause` chain; production emits only
34
+ * `type`, `title`, `status`, `detail`.
35
+ * - 500 responses always carry the fixed `Internal Server Error` detail — a
36
+ * thrown message is never echoed to clients. Other 5xx keep the message
37
+ * only for real `HTTPError` instances; a plain object with a `status`
38
+ * gets the bare status title.
39
+ * - Non-HTTPError values are wrapped in `HTTPError(500)`.
40
+ * - The status is clamped to 100-599 (integer); anything else renders as 500
41
+ * instead of escaping as a `RangeError`.
42
+ *
43
+ * @param error The error to render.
44
+ * @param isDev Whether to include dev diagnostics (stack, cause).
45
+ * @param extras Optional members merged into the problem body (e.g.
46
+ * `{ errors }` for validation failures); spread last, so they can override
47
+ * `title`/`detail`.
48
+ */
49
+ export declare function renderHTTPError(error: unknown, isDev: boolean, extras?: Record<string, unknown>): Response;
@@ -0,0 +1,155 @@
1
+ import { resolveDebug } from '../utils/env.js';
2
+ /**
3
+ * Base HTTP error class for BurgerAPI.
4
+ *
5
+ * All framework errors extend this; each subclass sets a static `status` and a
6
+ * default `name`. The `onError` pipeline renders them as RFC 9457 Problem
7
+ * Details. Subclasses: ValidationError (422), NotFoundError (404),
8
+ * UnauthorizedError (401), ForbiddenError (403), MethodNotAllowedError (405).
9
+ */
10
+ export class HTTPError extends Error {
11
+ /** HTTP status code for this error. */
12
+ status;
13
+ constructor(status, message, options) {
14
+ super(message, options);
15
+ this.status = status;
16
+ this.name = 'HTTPError';
17
+ }
18
+ }
19
+ /**
20
+ * HTTP status reason phrases (RFC 9110) used as the Problem Details `title`.
21
+ * Unlisted codes fall back to the error class name.
22
+ */
23
+ const STATUS_TITLES = {
24
+ 400: 'Bad Request',
25
+ 401: 'Unauthorized',
26
+ 402: 'Payment Required',
27
+ 403: 'Forbidden',
28
+ 404: 'Not Found',
29
+ 405: 'Method Not Allowed',
30
+ 406: 'Not Acceptable',
31
+ 408: 'Request Timeout',
32
+ 409: 'Conflict',
33
+ 410: 'Gone',
34
+ 411: 'Length Required',
35
+ 412: 'Precondition Failed',
36
+ 413: 'Content Too Large',
37
+ 414: 'URI Too Long',
38
+ 415: 'Unsupported Media Type',
39
+ 416: 'Range Not Satisfiable',
40
+ 417: 'Expectation Failed',
41
+ 418: "I'm a teapot",
42
+ 422: 'Unprocessable Content',
43
+ 423: 'Locked',
44
+ 424: 'Failed Dependency',
45
+ 425: 'Too Early',
46
+ 426: 'Upgrade Required',
47
+ 428: 'Precondition Required',
48
+ 429: 'Too Many Requests',
49
+ 431: 'Request Header Fields Too Large',
50
+ 451: 'Unavailable For Legal Reasons',
51
+ 500: 'Internal Server Error',
52
+ 501: 'Not Implemented',
53
+ 502: 'Bad Gateway',
54
+ 503: 'Service Unavailable',
55
+ 504: 'Gateway Timeout',
56
+ 505: 'HTTP Version Not Supported',
57
+ };
58
+ /**
59
+ * Logs a 5xx error that no user `onError` hook handled. Server-side only:
60
+ * one line of context plus the error and its stack.
61
+ */
62
+ export function logUnhandledError(method, url, error) {
63
+ let path = url;
64
+ try {
65
+ path = new URL(url).pathname;
66
+ }
67
+ catch {
68
+ // Not an absolute URL — log it verbatim.
69
+ }
70
+ console.error(`[burger-api] Unhandled error in ${method} ${path}:`, error);
71
+ }
72
+ /**
73
+ * Renders an error that escaped the request pipeline as RFC 9457 and logs it
74
+ * when it is a server-side failure. Shared by the Bun adapter, the router's
75
+ * pre-routing path and the WinterCG fetch entry, so uncaught errors render
76
+ * identically on every runtime.
77
+ */
78
+ export function renderUncaught(error, request, debug) {
79
+ const response = renderHTTPError(error, resolveDebug(debug));
80
+ if (response.status >= 500) {
81
+ logUnhandledError(request.method, request.url, error);
82
+ }
83
+ return response;
84
+ }
85
+ /**
86
+ * Renders an `HTTPError` (or subclass) as an RFC 9457 Problem Details
87
+ * response (`application/problem+json`).
88
+ *
89
+ * - Dev mode adds `stack` and the `cause` chain; production emits only
90
+ * `type`, `title`, `status`, `detail`.
91
+ * - 500 responses always carry the fixed `Internal Server Error` detail — a
92
+ * thrown message is never echoed to clients. Other 5xx keep the message
93
+ * only for real `HTTPError` instances; a plain object with a `status`
94
+ * gets the bare status title.
95
+ * - Non-HTTPError values are wrapped in `HTTPError(500)`.
96
+ * - The status is clamped to 100-599 (integer); anything else renders as 500
97
+ * instead of escaping as a `RangeError`.
98
+ *
99
+ * @param error The error to render.
100
+ * @param isDev Whether to include dev diagnostics (stack, cause).
101
+ * @param extras Optional members merged into the problem body (e.g.
102
+ * `{ errors }` for validation failures); spread last, so they can override
103
+ * `title`/`detail`.
104
+ */
105
+ export function renderHTTPError(error, isDev, extras) {
106
+ const httpError = error instanceof HTTPError ||
107
+ (error !== null &&
108
+ typeof error === 'object' &&
109
+ 'status' in error &&
110
+ typeof error.status === 'number')
111
+ ? error
112
+ : new HTTPError(500, 'Internal Server Error', error instanceof Error ? { cause: error } : undefined);
113
+ // Clamp to a valid HTTP status; junk renders as 500, never throws a
114
+ // `RangeError` from the `Response` constructor.
115
+ const rawStatus = httpError.status;
116
+ const status = Number.isInteger(rawStatus) && rawStatus >= 100 && rawStatus <= 599
117
+ ? rawStatus
118
+ : 500;
119
+ // Server-side failures never echo the thrown message to clients. A real
120
+ // HTTPError other than 500 is written by the developer, so it may; a
121
+ // thrown object that only carries a `status` (often a library error)
122
+ // may hold secrets, so its 5xx renders the bare status title.
123
+ const hide = !isDev &&
124
+ status >= 500 &&
125
+ (status === 500 || !(error instanceof HTTPError));
126
+ const genericTitle = STATUS_TITLES[status] ?? 'Internal Server Error';
127
+ const problem = {
128
+ type: 'about:blank',
129
+ // RFC 9457: the title is the status phrase, not the class name.
130
+ title: hide
131
+ ? genericTitle
132
+ : (STATUS_TITLES[status] ?? httpError.name ?? 'Error'),
133
+ status,
134
+ detail: hide ? genericTitle : httpError.message,
135
+ ...extras,
136
+ };
137
+ if (isDev) {
138
+ if (httpError.stack) {
139
+ problem.stack = httpError.stack;
140
+ }
141
+ if (httpError.cause) {
142
+ problem.cause =
143
+ httpError.cause instanceof Error
144
+ ? {
145
+ message: httpError.cause.message,
146
+ stack: httpError.cause.stack,
147
+ }
148
+ : { message: String(httpError.cause) };
149
+ }
150
+ }
151
+ return new Response(JSON.stringify(problem), {
152
+ status,
153
+ headers: { 'Content-Type': 'application/problem+json' },
154
+ });
155
+ }
@@ -0,0 +1,13 @@
1
+ import { HTTPError } from './http-error.js';
2
+ /**
3
+ * 405 Method Not Allowed — thrown when the HTTP method is not supported.
4
+ *
5
+ * @example
6
+ * throw new MethodNotAllowedError();
7
+ * throw new MethodNotAllowedError('PUT not supported on this resource');
8
+ */
9
+ export declare class MethodNotAllowedError extends HTTPError {
10
+ readonly name = "MethodNotAllowedError";
11
+ readonly status: 405;
12
+ constructor(message?: string, options?: ErrorOptions);
13
+ }
@@ -0,0 +1,15 @@
1
+ import { HTTPError } from './http-error.js';
2
+ /**
3
+ * 405 Method Not Allowed — thrown when the HTTP method is not supported.
4
+ *
5
+ * @example
6
+ * throw new MethodNotAllowedError();
7
+ * throw new MethodNotAllowedError('PUT not supported on this resource');
8
+ */
9
+ export class MethodNotAllowedError extends HTTPError {
10
+ name = 'MethodNotAllowedError';
11
+ status = 405;
12
+ constructor(message, options) {
13
+ super(405, message ?? 'Method Not Allowed', options);
14
+ }
15
+ }
@@ -0,0 +1,14 @@
1
+ import { HTTPError } from './http-error.js';
2
+ /**
3
+ * 404 Not Found — thrown when a requested resource does not exist.
4
+ *
5
+ * @example
6
+ * throw new NotFoundError();
7
+ * throw new NotFoundError('User 42 not found');
8
+ * throw new NotFoundError('User not found', { cause: dbError });
9
+ */
10
+ export declare class NotFoundError extends HTTPError {
11
+ readonly name = "NotFoundError";
12
+ readonly status: 404;
13
+ constructor(message?: string, options?: ErrorOptions);
14
+ }
@@ -0,0 +1,16 @@
1
+ import { HTTPError } from './http-error.js';
2
+ /**
3
+ * 404 Not Found — thrown when a requested resource does not exist.
4
+ *
5
+ * @example
6
+ * throw new NotFoundError();
7
+ * throw new NotFoundError('User 42 not found');
8
+ * throw new NotFoundError('User not found', { cause: dbError });
9
+ */
10
+ export class NotFoundError extends HTTPError {
11
+ name = 'NotFoundError';
12
+ status = 404;
13
+ constructor(message, options) {
14
+ super(404, message ?? 'Not Found', options);
15
+ }
16
+ }