context.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __export = (target, all) => {
  6. for (var name in all)
  7. __defProp(target, name, { get: all[name], enumerable: true });
  8. };
  9. var __copyProps = (to, from, except, desc) => {
  10. if (from && typeof from === "object" || typeof from === "function") {
  11. for (let key of __getOwnPropNames(from))
  12. if (!__hasOwnProp.call(to, key) && key !== except)
  13. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  14. }
  15. return to;
  16. };
  17. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  18. var context_exports = {};
  19. __export(context_exports, {
  20. Context: () => Context,
  21. TEXT_PLAIN: () => TEXT_PLAIN
  22. });
  23. module.exports = __toCommonJS(context_exports);
  24. var import_request = require("./request");
  25. var import_html = require("./utils/html");
  26. const TEXT_PLAIN = "text/plain; charset=UTF-8";
  27. const setDefaultContentType = (contentType, headers) => {
  28. return {
  29. "Content-Type": contentType,
  30. ...headers
  31. };
  32. };
  33. const createResponseInstance = (body, init) => new Response(body, init);
  34. class Context {
  35. #rawRequest;
  36. #req;
  37. /**
  38. * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
  39. *
  40. * @see {@link https://hono.dev/docs/api/context#env}
  41. *
  42. * @example
  43. * ```ts
  44. * // Environment object for Cloudflare Workers
  45. * app.get('*', async c => {
  46. * const counter = c.env.COUNTER
  47. * })
  48. * ```
  49. */
  50. env = {};
  51. #var;
  52. finalized = false;
  53. /**
  54. * `.error` can get the error object from the middleware if the Handler throws an error.
  55. *
  56. * @see {@link https://hono.dev/docs/api/context#error}
  57. *
  58. * @example
  59. * ```ts
  60. * app.use('*', async (c, next) => {
  61. * await next()
  62. * if (c.error) {
  63. * // do something...
  64. * }
  65. * })
  66. * ```
  67. */
  68. error;
  69. #status;
  70. #executionCtx;
  71. #res;
  72. #layout;
  73. #renderer;
  74. #notFoundHandler;
  75. #preparedHeaders;
  76. #matchResult;
  77. #path;
  78. /**
  79. * Creates an instance of the Context class.
  80. *
  81. * @param req - The Request object.
  82. * @param options - Optional configuration options for the context.
  83. */
  84. constructor(req, options) {
  85. this.#rawRequest = req;
  86. if (options) {
  87. this.#executionCtx = options.executionCtx;
  88. this.env = options.env;
  89. this.#notFoundHandler = options.notFoundHandler;
  90. this.#path = options.path;
  91. this.#matchResult = options.matchResult;
  92. }
  93. }
  94. /**
  95. * `.req` is the instance of {@link HonoRequest}.
  96. */
  97. get req() {
  98. this.#req ??= new import_request.HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
  99. return this.#req;
  100. }
  101. /**
  102. * @see {@link https://hono.dev/docs/api/context#event}
  103. * The FetchEvent associated with the current request.
  104. *
  105. * @throws Will throw an error if the context does not have a FetchEvent.
  106. */
  107. get event() {
  108. if (this.#executionCtx && "respondWith" in this.#executionCtx) {
  109. return this.#executionCtx;
  110. } else {
  111. throw Error("This context has no FetchEvent");
  112. }
  113. }
  114. /**
  115. * @see {@link https://hono.dev/docs/api/context#executionctx}
  116. * The ExecutionContext associated with the current request.
  117. *
  118. * @throws Will throw an error if the context does not have an ExecutionContext.
  119. */
  120. get executionCtx() {
  121. if (this.#executionCtx) {
  122. return this.#executionCtx;
  123. } else {
  124. throw Error("This context has no ExecutionContext");
  125. }
  126. }
  127. /**
  128. * @see {@link https://hono.dev/docs/api/context#res}
  129. * The Response object for the current request.
  130. */
  131. get res() {
  132. return this.#res ||= createResponseInstance(null, {
  133. headers: this.#preparedHeaders ??= new Headers()
  134. });
  135. }
  136. /**
  137. * Sets the Response object for the current request.
  138. *
  139. * @param _res - The Response object to set.
  140. */
  141. set res(_res) {
  142. if (this.#res && _res) {
  143. _res = createResponseInstance(_res.body, _res);
  144. for (const [k, v] of this.#res.headers.entries()) {
  145. if (k === "content-type") {
  146. continue;
  147. }
  148. if (k === "set-cookie") {
  149. const cookies = this.#res.headers.getSetCookie();
  150. _res.headers.delete("set-cookie");
  151. for (const cookie of cookies) {
  152. _res.headers.append("set-cookie", cookie);
  153. }
  154. } else {
  155. _res.headers.set(k, v);
  156. }
  157. }
  158. }
  159. this.#res = _res;
  160. this.finalized = true;
  161. }
  162. /**
  163. * `.render()` can create a response within a layout.
  164. *
  165. * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
  166. *
  167. * @example
  168. * ```ts
  169. * app.get('/', (c) => {
  170. * return c.render('Hello!')
  171. * })
  172. * ```
  173. */
  174. render = (...args) => {
  175. this.#renderer ??= (content) => this.html(content);
  176. return this.#renderer(...args);
  177. };
  178. /**
  179. * Sets the layout for the response.
  180. *
  181. * @param layout - The layout to set.
  182. * @returns The layout function.
  183. */
  184. setLayout = (layout) => this.#layout = layout;
  185. /**
  186. * Gets the current layout for the response.
  187. *
  188. * @returns The current layout function.
  189. */
  190. getLayout = () => this.#layout;
  191. /**
  192. * `.setRenderer()` can set the layout in the custom middleware.
  193. *
  194. * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
  195. *
  196. * @example
  197. * ```tsx
  198. * app.use('*', async (c, next) => {
  199. * c.setRenderer((content) => {
  200. * return c.html(
  201. * <html>
  202. * <body>
  203. * <p>{content}</p>
  204. * </body>
  205. * </html>
  206. * )
  207. * })
  208. * await next()
  209. * })
  210. * ```
  211. */
  212. setRenderer = (renderer) => {
  213. this.#renderer = renderer;
  214. };
  215. /**
  216. * `.header()` can set headers.
  217. *
  218. * @see {@link https://hono.dev/docs/api/context#header}
  219. *
  220. * @example
  221. * ```ts
  222. * app.get('/welcome', (c) => {
  223. * // Set headers
  224. * c.header('X-Message', 'Hello!')
  225. * c.header('Content-Type', 'text/plain')
  226. *
  227. * return c.body('Thank you for coming')
  228. * })
  229. * ```
  230. */
  231. header = (name, value, options) => {
  232. if (this.finalized) {
  233. this.#res = createResponseInstance(this.#res.body, this.#res);
  234. }
  235. const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
  236. if (value === void 0) {
  237. headers.delete(name);
  238. } else if (options?.append) {
  239. headers.append(name, value);
  240. } else {
  241. headers.set(name, value);
  242. }
  243. };
  244. status = (status) => {
  245. this.#status = status;
  246. };
  247. /**
  248. * `.set()` can set the value specified by the key.
  249. *
  250. * @see {@link https://hono.dev/docs/api/context#set-get}
  251. *
  252. * @example
  253. * ```ts
  254. * app.use('*', async (c, next) => {
  255. * c.set('message', 'Hono is hot!!')
  256. * await next()
  257. * })
  258. * ```
  259. */
  260. set = (key, value) => {
  261. this.#var ??= /* @__PURE__ */ new Map();
  262. this.#var.set(key, value);
  263. };
  264. /**
  265. * `.get()` can use the value specified by the key.
  266. *
  267. * @see {@link https://hono.dev/docs/api/context#set-get}
  268. *
  269. * @example
  270. * ```ts
  271. * app.get('/', (c) => {
  272. * const message = c.get('message')
  273. * return c.text(`The message is "${message}"`)
  274. * })
  275. * ```
  276. */
  277. get = (key) => {
  278. return this.#var ? this.#var.get(key) : void 0;
  279. };
  280. /**
  281. * `.var` can access the value of a variable.
  282. *
  283. * @see {@link https://hono.dev/docs/api/context#var}
  284. *
  285. * @example
  286. * ```ts
  287. * const result = c.var.client.oneMethod()
  288. * ```
  289. */
  290. // c.var.propName is a read-only
  291. get var() {
  292. if (!this.#var) {
  293. return {};
  294. }
  295. return Object.fromEntries(this.#var);
  296. }
  297. #newResponse(data, arg, headers) {
  298. const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
  299. if (typeof arg === "object" && "headers" in arg) {
  300. const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
  301. for (const [key, value] of argHeaders) {
  302. if (key.toLowerCase() === "set-cookie") {
  303. responseHeaders.append(key, value);
  304. } else {
  305. responseHeaders.set(key, value);
  306. }
  307. }
  308. }
  309. if (headers) {
  310. for (const [k, v] of Object.entries(headers)) {
  311. if (typeof v === "string") {
  312. responseHeaders.set(k, v);
  313. } else {
  314. responseHeaders.delete(k);
  315. for (const v2 of v) {
  316. responseHeaders.append(k, v2);
  317. }
  318. }
  319. }
  320. }
  321. const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
  322. return createResponseInstance(data, { status, headers: responseHeaders });
  323. }
  324. newResponse = (...args) => this.#newResponse(...args);
  325. /**
  326. * `.body()` can return the HTTP response.
  327. * You can set headers with `.header()` and set HTTP status code with `.status`.
  328. * This can also be set in `.text()`, `.json()` and so on.
  329. *
  330. * @see {@link https://hono.dev/docs/api/context#body}
  331. *
  332. * @example
  333. * ```ts
  334. * app.get('/welcome', (c) => {
  335. * // Set headers
  336. * c.header('X-Message', 'Hello!')
  337. * c.header('Content-Type', 'text/plain')
  338. * // Set HTTP status code
  339. * c.status(201)
  340. *
  341. * // Return the response body
  342. * return c.body('Thank you for coming')
  343. * })
  344. * ```
  345. */
  346. body = (data, arg, headers) => this.#newResponse(data, arg, headers);
  347. /**
  348. * `.text()` can render text as `Content-Type:text/plain`.
  349. *
  350. * @see {@link https://hono.dev/docs/api/context#text}
  351. *
  352. * @example
  353. * ```ts
  354. * app.get('/say', (c) => {
  355. * return c.text('Hello!')
  356. * })
  357. * ```
  358. */
  359. text = (text, arg, headers) => {
  360. return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
  361. text,
  362. arg,
  363. setDefaultContentType(TEXT_PLAIN, headers)
  364. );
  365. };
  366. /**
  367. * `.json()` can render JSON as `Content-Type:application/json`.
  368. *
  369. * @see {@link https://hono.dev/docs/api/context#json}
  370. *
  371. * @example
  372. * ```ts
  373. * app.get('/api', (c) => {
  374. * return c.json({ message: 'Hello!' })
  375. * })
  376. * ```
  377. */
  378. json = (object, arg, headers) => {
  379. return this.#newResponse(
  380. JSON.stringify(object),
  381. arg,
  382. setDefaultContentType("application/json", headers)
  383. );
  384. };
  385. html = (html, arg, headers) => {
  386. const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
  387. return typeof html === "object" ? (0, import_html.resolveCallback)(html, import_html.HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
  388. };
  389. /**
  390. * `.redirect()` can Redirect, default status code is 302.
  391. *
  392. * @see {@link https://hono.dev/docs/api/context#redirect}
  393. *
  394. * @example
  395. * ```ts
  396. * app.get('/redirect', (c) => {
  397. * return c.redirect('/')
  398. * })
  399. * app.get('/redirect-permanently', (c) => {
  400. * return c.redirect('/', 301)
  401. * })
  402. * ```
  403. */
  404. redirect = (location, status) => {
  405. const locationString = String(location);
  406. this.header(
  407. "Location",
  408. // Multibyes should be encoded
  409. // eslint-disable-next-line no-control-regex
  410. !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
  411. );
  412. return this.newResponse(null, status ?? 302);
  413. };
  414. /**
  415. * `.notFound()` can return the Not Found Response.
  416. *
  417. * @see {@link https://hono.dev/docs/api/context#notfound}
  418. *
  419. * @example
  420. * ```ts
  421. * app.get('/notfound', (c) => {
  422. * return c.notFound()
  423. * })
  424. * ```
  425. */
  426. notFound = () => {
  427. this.#notFoundHandler ??= () => createResponseInstance();
  428. return this.#notFoundHandler(this);
  429. };
  430. }
  431. // Annotate the CommonJS export names for ESM import in node:
  432. 0 && (module.exports = {
  433. Context,
  434. TEXT_PLAIN
  435. });