Skip to content
Myr

refactor: support new `@cloudflare/worker-types` (#673)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* refactor: support new `@cloudflare/worker-types` * do not attach crypto to global * denoify ignore serve-static for cloudlfare * ignore the utility for cloudflare * import types

authored by Yusuke Wada · committed by GitHub · parent 5456709 · Browse files · 25 files+82 added−165 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

25 files+82 added−165 removed

  • tests:+6 added−24 removed
  • other:+76 added−141 removed

25 files+82 added−165 removed

modified:deno_dist/middleware/compress/index.ts+2 added
deleted:deno_dist/middleware/serve-static/serve-static.ts-49 removed
modified:deno_dist/utils/body.ts+4 added-4 removed
deleted:deno_dist/utils/cloudflare.ts-47 removed
modified:deno_dist/utils/crypto.ts+1 added-1 removed
modified:deno_dist/context.ts+5 added-4 removed
1import type { ExecutionContext } from './types.ts'2import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './types.ts'3import type { CookieOptions } from './utils/cookie.ts'4import { serialize } from './utils/cookie.ts'5import type { StatusCode } from './utils/http-status.ts'
8 unmodified lines
14 P extends string = string,15 E extends Partial<Environment> = Environment,16 S extends Partial<Schema> = Schema17> {17 req: Request<P, S extends Schema ? SchemaToProp<S> : S>18 req: Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>19 env: E['Bindings']20 finalized: boolean21 error: Error | undefined = undefined22
6 unmodified lines
29 private _res: Response | undefined30 private notFoundHandler: NotFoundHandler<E>3132 constructor(32 req: Request<P>,33 req: Request<unknown, P>,34 env: E['Bindings'] = {},35 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,36 notFoundHandler: NotFoundHandler<E> = () => new Response()37 ) {38 this._executionCtx = executionCtx38 this.req = req as Request<P, S extends Schema ? SchemaToProp<S> : S>39 this.req = req as unknown as Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>40 this.env = env || ({} as Bindings)4142 this.notFoundHandler = notFoundHandler43 this.finalized = false
8 unmodified lines
52 }5354 get executionCtx(): ExecutionContext {55 if (this._executionCtx) {55 return this._executionCtx56 return this._executionCtx as ExecutionContext57 } else {58 throw Error('This context has no ExecutionContext')59 }60 }
168 unmodified lines
modified:deno_dist/hono.ts+5 added-4 removed
5 unmodified lines
6import { RegExpRouter } from './router/reg-exp-router/index.ts'7import { SmartRouter } from './router/smart-router/index.ts'8import { StaticRouter } from './router/static-router/index.ts'9import { TrieRouter } from './router/trie-router/index.ts'10import type { ExecutionContext } from './types.ts'11import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types.ts'12import { getPathFromURL, mergePath } from './utils/url.ts'13import type { Schema } from './validator/schema.ts'14
63 unmodified lines
78 extendRequestPrototype()7980 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]81 allMethods.map((method) => {81 this[method] = <Path extends string, Env extends Environment, Data extends Schema>(82 args1: Path | Handler<ParamKeys<Path>, Env, Data>,83 ...args: [Handler<ParamKeys<Path>, Env, Data>]84 ): this => {82 this[method] = <Env extends Environment, Data extends Schema>(83 args1: string | Handler<string, Env, Data>,84 ...args: Handler<string, Env, Data>[]85 ) => {86 if (typeof args1 === 'string') {87 this.path = args188 } else {89 this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)
176 unmodified lines
modified:deno_dist/request.ts+6 added-3 removed
6 unmodified lines
7type ValidatedData = Record<string, any>89declare global {10 interface Request<11 // eslint-disable-next-line @typescript-eslint/no-unused-vars12 CfHostMetadata = unknown,13 ParamKeyType extends string = string,14 Data extends ValidatedData = ValidatedData15 > {16 paramData?: Record<ParamKeyType, string>
57 unmodified lines
7475 Request.prototype.header = function (this: Request, name?: string) {76 if (!this.headerData) {77 this.headerData = {}76 for (const [key, value] of this.headers) {77 this.headerData[key] = value78 }78 this.headers.forEach((value, key) => {79 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion80 this.headerData![key] = value81 })82 }83 if (name) {84 return this.headerData[name.toLowerCase()]85 } else {
88 unmodified lines
modified:deno_dist/types.ts+5 added
76 unmodified lines
77 >,78 next: Next79 ): Response | Promise<Response | undefined | void>80}8182export interface ExecutionContext {83 waitUntil(promise: Promise<any>): void84 passThroughOnException(): void85}
modified:src/middleware/basic-auth/index.test.ts+1 added-7 removed
1 unmodified line
2import { Hono } from '../../hono'3import { basicAuth } from '.'45describe('Basic Auth by Middleware', () => {6 const crypto = global.crypto6 let handlerExecuted: boolean8 beforeAll(() => {9 global.crypto = require('crypto').webcrypto10 })11 afterAll(() => {12 global.crypto = crypto13 })78 beforeEach(() => {9 handlerExecuted = false10 })11
176 unmodified lines
modified:src/middleware/compress/index.ts+2 added
14 unmodified lines
15 if (!accepted || !match || !ctx.res.body) {16 return17 }18 const encoding = match[0]19 // eslint-disable-next-line @typescript-eslint/ban-ts-comment20 // @ts-ignore21 const stream = new CompressionStream(encoding as EncodingType)22 ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)23 ctx.res.headers.set('Content-Encoding', encoding)24 }
1 unmodified line
modified:src/middleware/jwt/index.test.ts+2 added-14 removed
1 unmodified line
2import { jwt } from '.'34describe('JWT', () => {5 describe('Credentials in header', () => {6 const crypto = global.crypto6 let handlerExecuted: boolean8 beforeAll(() => {9 global.crypto = require('crypto').webcrypto10 })11 afterAll(() => {12 global.crypto = crypto13 })78 beforeEach(() => {9 handlerExecuted = false10 })11
105 unmodified lines
117 })118 })119120 describe('Credentials in cookie', () => {127 const crypto = global.crypto121 let handlerExecuted: boolean129 beforeAll(() => {130 global.crypto = require('crypto').webcrypto131 })132 afterAll(() => {133 global.crypto = crypto134 })122123 beforeEach(() => {124 handlerExecuted = false125 })126
86 unmodified lines
modified:src/middleware/serve-static/serve-static.ts+2 added
1// @denoify-ignore2import type { KVNamespace } from '@cloudflare/workers-types'3import type { MiddlewareHandler } from '../../types'4import { getContentFromKVAsset } from '../../utils/cloudflare'5import { getFilePath } from '../../utils/filepath'6import { getMimeType } from '../../utils/mime'
45 unmodified lines
modified:src/utils/body.ts+4 added-4 removed
9 unmodified lines
10 (contentType.startsWith('multipart/form-data') ||11 contentType === 'application/x-www-form-urlencoded')12 ) {13 const form: Record<string, string | File> = {}14 body = [...(await r.formData())].reduce((acc, cur) => {15 acc[cur[0]] = cur[1]16 return acc17 }, form)14 ;(await r.formData()).forEach((value, key) => {15 form[key] = value16 })17 body = form18 }19 return body as BodyType20}
modified:src/utils/cloudflare.test.ts+3 added-3 removed
20 unmodified lines
2122describe('Utils for Cloudflare Workers', () => {23 it('getContentFromKVAsset', async () => {24 let content = await getContentFromKVAsset('not-found.txt')25 expect(content).toBeUndefined()25 expect(content).toBeFalsy()26 content = await getContentFromKVAsset('index.html')27 expect(content).not.toBeUndefined()27 expect(content).toBeTruthy()28 expect(content).toBe('This is index')29 content = await getContentFromKVAsset('assets/static/plain.txt')30 expect(content).not.toBeUndefined()30 expect(content).toBeTruthy()31 expect(content).toBe('Asset text')32 })33})
modified:src/utils/cloudflare.ts+6 added-5 removed
1// @denoify-ignore2import type { KVNamespace } from '@cloudflare/workers-types'3declare const __STATIC_CONTENT: KVNamespace4declare const __STATIC_CONTENT_MANIFEST: string56export type KVAssetOptions = {
32 unmodified lines
39 if (!key) {40 return null41 }4241 let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })4243 if (content) {44 content = content as ArrayBuffer43 const content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })44 if (!content) {45 return null46 }46 return content47 return content as unknown as ArrayBuffer48}
modified:src/utils/crypto.ts+1 added-1 removed
47 unmodified lines
48 const buffer = await crypto.subtle.digest(49 {50 name: algorithm.name,51 },52 sourceBuffer52 sourceBuffer as ArrayBuffer53 )54 const hash = Array.prototype.map55 .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))56 .join('')
4 unmodified lines
modified:src/context.ts+5 added-4 removed
1import type { ExecutionContext } from './types'2import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './types'3import type { CookieOptions } from './utils/cookie'4import { serialize } from './utils/cookie'5import type { StatusCode } from './utils/http-status'
8 unmodified lines
14 P extends string = string,15 E extends Partial<Environment> = Environment,16 S extends Partial<Schema> = Schema17> {17 req: Request<P, S extends Schema ? SchemaToProp<S> : S>18 req: Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>19 env: E['Bindings']20 finalized: boolean21 error: Error | undefined = undefined22
6 unmodified lines
29 private _res: Response | undefined30 private notFoundHandler: NotFoundHandler<E>3132 constructor(32 req: Request<P>,33 req: Request<unknown, P>,34 env: E['Bindings'] = {},35 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,36 notFoundHandler: NotFoundHandler<E> = () => new Response()37 ) {38 this._executionCtx = executionCtx38 this.req = req as Request<P, S extends Schema ? SchemaToProp<S> : S>39 this.req = req as unknown as Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>40 this.env = env || ({} as Bindings)4142 this.notFoundHandler = notFoundHandler43 this.finalized = false
8 unmodified lines
52 }5354 get executionCtx(): ExecutionContext {55 if (this._executionCtx) {55 return this._executionCtx56 return this._executionCtx as ExecutionContext57 } else {58 throw Error('This context has no ExecutionContext')59 }60 }
168 unmodified lines
modified:src/hono.ts+5 added-4 removed
5 unmodified lines
6import { RegExpRouter } from './router/reg-exp-router'7import { SmartRouter } from './router/smart-router'8import { StaticRouter } from './router/static-router'9import { TrieRouter } from './router/trie-router'10import type { ExecutionContext } from './types'11import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types'12import { getPathFromURL, mergePath } from './utils/url'13import type { Schema } from './validator/schema'14
63 unmodified lines
78 extendRequestPrototype()7980 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]81 allMethods.map((method) => {81 this[method] = <Path extends string, Env extends Environment, Data extends Schema>(82 args1: Path | Handler<ParamKeys<Path>, Env, Data>,83 ...args: [Handler<ParamKeys<Path>, Env, Data>]84 ): this => {82 this[method] = <Env extends Environment, Data extends Schema>(83 args1: string | Handler<string, Env, Data>,84 ...args: Handler<string, Env, Data>[]85 ) => {86 if (typeof args1 === 'string') {87 this.path = args188 } else {89 this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)
176 unmodified lines
modified:src/index.ts+2 added
20 unmodified lines
21 }22}2324Hono.prototype.fire = function () {25 // eslint-disable-next-line @typescript-eslint/ban-ts-comment26 // @ts-ignore27 addEventListener('fetch', (event: FetchEvent): void => {28 void event.respondWith(this.handleEvent(event))29 })30}
2 unmodified lines
modified:src/request.ts+6 added-3 removed
6 unmodified lines
7type ValidatedData = Record<string, any>89declare global {10 interface Request<11 // eslint-disable-next-line @typescript-eslint/no-unused-vars12 CfHostMetadata = unknown,13 ParamKeyType extends string = string,14 Data extends ValidatedData = ValidatedData15 > {16 paramData?: Record<ParamKeyType, string>
57 unmodified lines
7475 Request.prototype.header = function (this: Request, name?: string) {76 if (!this.headerData) {77 this.headerData = {}76 for (const [key, value] of this.headers) {77 this.headerData[key] = value78 }78 this.headers.forEach((value, key) => {79 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion80 this.headerData![key] = value81 })82 }83 if (name) {84 return this.headerData[name.toLowerCase()]85 } else {
88 unmodified lines
modified:src/types.ts+5 added
76 unmodified lines
77 >,78 next: Next79 ): Response | Promise<Response | undefined | void>80}8182export interface ExecutionContext {83 waitUntil(promise: Promise<any>): void84 passThroughOnException(): void85}
modified:package.json+2 added-2 removed
247 unmodified lines
248 "deno",249 "bun"250 ],251 "devDependencies": {252 "@cloudflare/workers-types": "^3.16.0",252 "@cloudflare/workers-types": "^4.20221111.1",253 "@types/crypto-js": "^4.1.1",254 "@types/glob": "^8.0.0",255 "@types/jest": "^29.0.2",256 "@types/node": "^17.0.29",
23 unmodified lines
280 },281 "engines": {282 "node": ">=16.0.0"283 }284}284}
modified:tsconfig.json+4 added-2 removed
10 unmodified lines
11 "strictPropertyInitialization": true,12 "strictNullChecks": true,13 "noUnusedLocals": false,14 "noUnusedParameters": false,15 "lib": [16 "WebWorker"17 ],18 "types": [19 "jest",17 "node",18 "@cloudflare/workers-types"20 "node"21 ],22 "jsx": "react",23 "jsxFactory": "jsx",24 "jsxFragmentFactory": "Fragment",
7 unmodified lines
modified:yarn.lock+4 added-4 removed
483 unmodified lines
484 version "0.2.3"485 resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39"486 integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==487488"@cloudflare/workers-types@^3.16.0":489 version "3.16.0"490 resolved "https://registry.yarnpkg.com/@cloudflare/workers-types/-/workers-types-3.16.0.tgz#011658ca3f9810373e0eb4a2b5d6cabe4848d8d6"491 integrity sha512-gaBUSaKS65mN3iKZEgichbXYEmAa/pXkc5Gbt+1BptYphdGkj09ggdsiE4w8g0F/uI1g36QaTKrzVnBAWMipvQ==488"@cloudflare/workers-types@^4.20221111.1":489 version "4.20221111.1"490 resolved "https://registry.yarnpkg.com/@cloudflare/workers-types/-/workers-types-4.20221111.1.tgz#c3dbb5ef52cf5fab275803ece0424b205c78ad3e"491 integrity sha512-BNV2wN8V6Zduvo7UzxcdjBbLQ906D2KhS804PDufLgx/sanGJCHVJMOIaLvS/b61JKtot1U7P/l1fjrjZ7/E3A==492493"@esbuild-kit/cjs-loader@^2.4.0":494 version "2.4.0"495 resolved "https://registry.yarnpkg.com/@esbuild-kit/cjs-loader/-/cjs-loader-2.4.0.tgz#643c4b2855a18f31cd983794536d4ff64d3b410d"
5599 unmodified lines