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
Provenance
- Commit
1eb49b8- Tree
8b83538- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
5456709
25 files changed+82 added−165 removed
modified:deno_dist/middleware/compress/index.ts+2 added
14 unmodified lines151617181920212223242514 unmodified lines if (!accepted || !match || !ctx.res.body) { return } const encoding = match[0] // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const stream = new CompressionStream(encoding as EncodingType) ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res) ctx.res.headers.set('Content-Encoding', encoding) }}deleted:deno_dist/middleware/serve-static/serve-static.ts-49 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import type { MiddlewareHandler } from '../../types.ts'import { getContentFromKVAsset } from '../../utils/cloudflare.ts'import { getFilePath } from '../../utils/filepath.ts'import { getMimeType } from '../../utils/mime.ts'
export type ServeStaticOptions = { root?: string path?: string manifest?: object | string namespace?: KVNamespace}
const DEFAULT_DOCUMENT = 'index.html'
// This middleware is available only on Cloudflare Workers.export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => { return async (c, next) => { // Do nothing if Response is already set if (c.finalized) { await next() return }
const url = new URL(c.req.url)
const path = getFilePath({ filename: options.path ?? url.pathname, root: options.root, defaultDocument: DEFAULT_DOCUMENT, })
const content = await getContentFromKVAsset(path, { manifest: options.manifest, namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined, }) if (content) { const mimeType = getMimeType(path) if (mimeType) { c.header('Content-Type', mimeType) } // Return Response object return c.body(content) } else { console.warn(`Static file: ${path} is not found`) await next() } return }}modified:deno_dist/utils/body.ts+4 added-4 removed
9 unmodified lines1011121314151617141516171819209 unmodified lines (contentType.startsWith('multipart/form-data') || contentType === 'application/x-www-form-urlencoded') ) { const form: Record<string, string | File> = {} body = [...(await r.formData())].reduce((acc, cur) => { acc[cur[0]] = cur[1] return acc }, form) ;(await r.formData()).forEach((value, key) => { form[key] = value }) body = form } return body as BodyType}deleted:deno_dist/utils/cloudflare.ts-47 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647declare const __STATIC_CONTENT: KVNamespacedeclare const __STATIC_CONTENT_MANIFEST: string
export type KVAssetOptions = { manifest?: object | string namespace?: KVNamespace}
export const getContentFromKVAsset = async ( path: string, options?: KVAssetOptions): Promise<ArrayBuffer | null> => { let ASSET_MANIFEST: Record<string, string> = {}
if (options && options.manifest) { if (typeof options.manifest === 'string') { ASSET_MANIFEST = JSON.parse(options.manifest) } else { ASSET_MANIFEST = options.manifest as Record<string, string> } } else { if (typeof __STATIC_CONTENT_MANIFEST === 'string') { ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST) } else { ASSET_MANIFEST = __STATIC_CONTENT_MANIFEST } }
let ASSET_NAMESPACE: KVNamespace if (options && options.namespace) { ASSET_NAMESPACE = options.namespace } else { ASSET_NAMESPACE = __STATIC_CONTENT }
const key = ASSET_MANIFEST[path] || path if (!key) { return null }
let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })
if (content) { content = content as ArrayBuffer } return content}modified:deno_dist/utils/crypto.ts+1 added-1 removed
47 unmodified lines484950515252535455564 unmodified lines47 unmodified lines const buffer = await crypto.subtle.digest( { name: algorithm.name, }, sourceBuffer sourceBuffer as ArrayBuffer ) const hash = Array.prototype.map .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2)) .join('')4 unmodified linesmodified:deno_dist/context.ts+5 added-4 removed
1+import type { ExecutionContext } from './types.ts'2 import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './types.ts'3 import type { CookieOptions } from './utils/cookie.ts'4 import { serialize } from './utils/cookie.ts'5 import type { StatusCode } from './utils/http-status.ts'8 unmodified lines14 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 lines29 private _res: Response | undefined30 private notFoundHandler: NotFoundHandler<E>31 32 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)41 42 this.notFoundHandler = notFoundHandler43 this.finalized = false8 unmodified lines52 }53 54 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 linesmodified:deno_dist/hono.ts+5 added-4 removed
5 unmodified lines6 import { RegExpRouter } from './router/reg-exp-router/index.ts'7 import { SmartRouter } from './router/smart-router/index.ts'8 import { StaticRouter } from './router/static-router/index.ts'9 import { TrieRouter } from './router/trie-router/index.ts'10+import type { ExecutionContext } from './types.ts'11 import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types.ts'12 import { getPathFromURL, mergePath } from './utils/url.ts'13 import type { Schema } from './validator/schema.ts'14 63 unmodified lines78 extendRequestPrototype()79 80 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 linesmodified:deno_dist/request.ts+6 added-3 removed
6 unmodified lines7 type ValidatedData = Record<string, any>8 9 declare 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 lines74 75 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 linesmodified:deno_dist/types.ts+5 added
76 unmodified lines77 >,78 next: Next79 ): Response | Promise<Response | undefined | void>80 }81+82+export interface ExecutionContext {83+ waitUntil(promise: Promise<any>): void84+ passThroughOnException(): void85+}modified:src/middleware/basic-auth/index.test.ts+1 added-7 removed
1 unmodified line2 import { Hono } from '../../hono'3 import { basicAuth } from '.'4 5 describe('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- })7+8 beforeEach(() => {9 handlerExecuted = false10 })11 176 unmodified linesmodified:src/middleware/compress/index.ts+2 added
14 unmodified lines15 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 linemodified:src/middleware/jwt/index.test.ts+2 added-14 removed
1 unmodified line2 import { jwt } from '.'3 4 describe('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- })7+8 beforeEach(() => {9 handlerExecuted = false10 })11 105 unmodified lines117 })118 })119 120 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- })122+123 beforeEach(() => {124 handlerExecuted = false125 })126 86 unmodified linesmodified:src/middleware/serve-static/serve-static.ts+2 added
1+// @denoify-ignore2+import type { KVNamespace } from '@cloudflare/workers-types'3 import type { MiddlewareHandler } from '../../types'4 import { getContentFromKVAsset } from '../../utils/cloudflare'5 import { getFilePath } from '../../utils/filepath'6 import { getMimeType } from '../../utils/mime'45 unmodified linesmodified:src/utils/body.ts+4 added-4 removed
9 unmodified lines10 (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 lines21 22 describe('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-ignore2+import type { KVNamespace } from '@cloudflare/workers-types'3 declare const __STATIC_CONTENT: KVNamespace4 declare const __STATIC_CONTENT_MANIFEST: string5 6 export type KVAssetOptions = {32 unmodified lines39 if (!key) {40 return null41 }42 41- let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })42-43- 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 lines48 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 linesmodified:src/context.ts+5 added-4 removed
1+import type { ExecutionContext } from './types'2 import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './types'3 import type { CookieOptions } from './utils/cookie'4 import { serialize } from './utils/cookie'5 import type { StatusCode } from './utils/http-status'8 unmodified lines14 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 lines29 private _res: Response | undefined30 private notFoundHandler: NotFoundHandler<E>31 32 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)41 42 this.notFoundHandler = notFoundHandler43 this.finalized = false8 unmodified lines52 }53 54 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 linesmodified:src/hono.ts+5 added-4 removed
5 unmodified lines6 import { RegExpRouter } from './router/reg-exp-router'7 import { SmartRouter } from './router/smart-router'8 import { StaticRouter } from './router/static-router'9 import { TrieRouter } from './router/trie-router'10+import type { ExecutionContext } from './types'11 import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types'12 import { getPathFromURL, mergePath } from './utils/url'13 import type { Schema } from './validator/schema'14 63 unmodified lines78 extendRequestPrototype()79 80 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 linesmodified:src/index.ts+2 added
20 unmodified lines21 }22 }23 24 Hono.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 linesmodified:src/request.ts+6 added-3 removed
6 unmodified lines7 type ValidatedData = Record<string, any>8 9 declare 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 lines74 75 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 linesmodified:src/types.ts+5 added
76 unmodified lines77 >,78 next: Next79 ): Response | Promise<Response | undefined | void>80 }81+82+export interface ExecutionContext {83+ waitUntil(promise: Promise<any>): void84+ passThroughOnException(): void85+}modified:package.json+2 added-2 removed
247 unmodified lines248 "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 lines280 },281 "engines": {282 "node": ">=16.0.0"283 }284-}284+}modified:tsconfig.json+4 added-2 removed
10 unmodified lines11 "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 linesmodified:yarn.lock+4 added-4 removed
483 unmodified lines484 version "0.2.3"485 resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39"486 integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==487 488-"@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==492 493 "@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