Skip to content

Commit

Permalink
refactor: support new @cloudflare/worker-types (#673)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
yusukebe committed Nov 22, 2022
1 parent 5456709 commit 1eb49b8
Show file tree
Hide file tree
Showing 25 changed files with 82 additions and 165 deletions.
9 changes: 5 additions & 4 deletions deno_dist/context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ExecutionContext } from './types.ts'
import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './types.ts'
import type { CookieOptions } from './utils/cookie.ts'
import { serialize } from './utils/cookie.ts'
Expand All @@ -14,7 +15,7 @@ export class Context<
E extends Partial<Environment> = Environment,
S extends Partial<Schema> = Schema
> {
req: Request<P, S extends Schema ? SchemaToProp<S> : S>
req: Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>
env: E['Bindings']
finalized: boolean
error: Error | undefined = undefined
Expand All @@ -29,13 +30,13 @@ export class Context<
private notFoundHandler: NotFoundHandler<E>

constructor(
req: Request<P>,
req: Request<unknown, P>,
env: E['Bindings'] = {},
executionCtx: FetchEvent | ExecutionContext | undefined = undefined,
notFoundHandler: NotFoundHandler<E> = () => new Response()
) {
this._executionCtx = executionCtx
this.req = req as Request<P, S extends Schema ? SchemaToProp<S> : S>
this.req = req as unknown as Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>
this.env = env || ({} as Bindings)

this.notFoundHandler = notFoundHandler
Expand All @@ -52,7 +53,7 @@ export class Context<

get executionCtx(): ExecutionContext {
if (this._executionCtx) {
return this._executionCtx
return this._executionCtx as ExecutionContext
} else {
throw Error('This context has no ExecutionContext')
}
Expand Down
9 changes: 5 additions & 4 deletions deno_dist/hono.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { RegExpRouter } from './router/reg-exp-router/index.ts'
import { SmartRouter } from './router/smart-router/index.ts'
import { StaticRouter } from './router/static-router/index.ts'
import { TrieRouter } from './router/trie-router/index.ts'
import type { ExecutionContext } from './types.ts'
import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types.ts'
import { getPathFromURL, mergePath } from './utils/url.ts'
import type { Schema } from './validator/schema.ts'
Expand Down Expand Up @@ -78,10 +79,10 @@ export class Hono<

const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]
allMethods.map((method) => {
this[method] = <Path extends string, Env extends Environment, Data extends Schema>(
args1: Path | Handler<ParamKeys<Path>, Env, Data>,
...args: [Handler<ParamKeys<Path>, Env, Data>]
): this => {
this[method] = <Env extends Environment, Data extends Schema>(
args1: string | Handler<string, Env, Data>,
...args: Handler<string, Env, Data>[]
) => {
if (typeof args1 === 'string') {
this.path = args1
} else {
Expand Down
2 changes: 2 additions & 0 deletions deno_dist/middleware/compress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const compress = (options?: CompressionOptions): MiddlewareHandler => {
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)
Expand Down
49 changes: 0 additions & 49 deletions deno_dist/middleware/serve-static/serve-static.ts

This file was deleted.

9 changes: 6 additions & 3 deletions deno_dist/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ type ValidatedData = Record<string, any>

declare global {
interface Request<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
CfHostMetadata = unknown,
ParamKeyType extends string = string,
Data extends ValidatedData = ValidatedData
> {
Expand Down Expand Up @@ -73,9 +75,10 @@ export function extendRequestPrototype() {
Request.prototype.header = function (this: Request, name?: string) {
if (!this.headerData) {
this.headerData = {}
for (const [key, value] of this.headers) {
this.headerData[key] = value
}
this.headers.forEach((value, key) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.headerData![key] = value
})
}
if (name) {
return this.headerData[name.toLowerCase()]
Expand Down
5 changes: 5 additions & 0 deletions deno_dist/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,8 @@ export interface CustomHandler<
next: Next
): Response | Promise<Response | undefined | void>
}

export interface ExecutionContext {
waitUntil(promise: Promise<any>): void
passThroughOnException(): void
}
8 changes: 4 additions & 4 deletions deno_dist/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export async function parseBody<BodyType extends BodyData>(
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
}
47 changes: 0 additions & 47 deletions deno_dist/utils/cloudflare.ts

This file was deleted.

2 changes: 1 addition & 1 deletion deno_dist/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const createHash = async (data: Data, algorithm: Algorithm): Promise<stri
{
name: algorithm.name,
},
sourceBuffer
sourceBuffer as ArrayBuffer
)
const hash = Array.prototype.map
.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@
"bun"
],
"devDependencies": {
"@cloudflare/workers-types": "^3.16.0",
"@cloudflare/workers-types": "^4.20221111.1",
"@types/crypto-js": "^4.1.1",
"@types/glob": "^8.0.0",
"@types/jest": "^29.0.2",
Expand Down Expand Up @@ -281,4 +281,4 @@
"engines": {
"node": ">=16.0.0"
}
}
}
9 changes: 5 additions & 4 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ExecutionContext } from './types'
import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './types'
import type { CookieOptions } from './utils/cookie'
import { serialize } from './utils/cookie'
Expand All @@ -14,7 +15,7 @@ export class Context<
E extends Partial<Environment> = Environment,
S extends Partial<Schema> = Schema
> {
req: Request<P, S extends Schema ? SchemaToProp<S> : S>
req: Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>
env: E['Bindings']
finalized: boolean
error: Error | undefined = undefined
Expand All @@ -29,13 +30,13 @@ export class Context<
private notFoundHandler: NotFoundHandler<E>

constructor(
req: Request<P>,
req: Request<unknown, P>,
env: E['Bindings'] = {},
executionCtx: FetchEvent | ExecutionContext | undefined = undefined,
notFoundHandler: NotFoundHandler<E> = () => new Response()
) {
this._executionCtx = executionCtx
this.req = req as Request<P, S extends Schema ? SchemaToProp<S> : S>
this.req = req as unknown as Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>
this.env = env || ({} as Bindings)

this.notFoundHandler = notFoundHandler
Expand All @@ -52,7 +53,7 @@ export class Context<

get executionCtx(): ExecutionContext {
if (this._executionCtx) {
return this._executionCtx
return this._executionCtx as ExecutionContext
} else {
throw Error('This context has no ExecutionContext')
}
Expand Down
9 changes: 5 additions & 4 deletions src/hono.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { RegExpRouter } from './router/reg-exp-router'
import { SmartRouter } from './router/smart-router'
import { StaticRouter } from './router/static-router'
import { TrieRouter } from './router/trie-router'
import type { ExecutionContext } from './types'
import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types'
import { getPathFromURL, mergePath } from './utils/url'
import type { Schema } from './validator/schema'
Expand Down Expand Up @@ -78,10 +79,10 @@ export class Hono<

const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]
allMethods.map((method) => {
this[method] = <Path extends string, Env extends Environment, Data extends Schema>(
args1: Path | Handler<ParamKeys<Path>, Env, Data>,
...args: [Handler<ParamKeys<Path>, Env, Data>]
): this => {
this[method] = <Env extends Environment, Data extends Schema>(
args1: string | Handler<string, Env, Data>,
...args: Handler<string, Env, Data>[]
) => {
if (typeof args1 === 'string') {
this.path = args1
} else {
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ declare module './hono' {
}

Hono.prototype.fire = function () {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
addEventListener('fetch', (event: FetchEvent): void => {
void event.respondWith(this.handleEvent(event))
})
Expand Down
8 changes: 1 addition & 7 deletions src/middleware/basic-auth/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,8 @@ import { Hono } from '../../hono'
import { basicAuth } from '.'

describe('Basic Auth by Middleware', () => {
const crypto = global.crypto
let handlerExecuted: boolean
beforeAll(() => {
global.crypto = require('crypto').webcrypto
})
afterAll(() => {
global.crypto = crypto
})

beforeEach(() => {
handlerExecuted = false
})
Expand Down
2 changes: 2 additions & 0 deletions src/middleware/compress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const compress = (options?: CompressionOptions): MiddlewareHandler => {
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)
Expand Down
16 changes: 2 additions & 14 deletions src/middleware/jwt/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,8 @@ import { jwt } from '.'

describe('JWT', () => {
describe('Credentials in header', () => {
const crypto = global.crypto
let handlerExecuted: boolean
beforeAll(() => {
global.crypto = require('crypto').webcrypto
})
afterAll(() => {
global.crypto = crypto
})

beforeEach(() => {
handlerExecuted = false
})
Expand Down Expand Up @@ -124,14 +118,8 @@ describe('JWT', () => {
})

describe('Credentials in cookie', () => {
const crypto = global.crypto
let handlerExecuted: boolean
beforeAll(() => {
global.crypto = require('crypto').webcrypto
})
afterAll(() => {
global.crypto = crypto
})

beforeEach(() => {
handlerExecuted = false
})
Expand Down
2 changes: 2 additions & 0 deletions src/middleware/serve-static/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// @denoify-ignore
import type { KVNamespace } from '@cloudflare/workers-types'
import type { MiddlewareHandler } from '../../types'
import { getContentFromKVAsset } from '../../utils/cloudflare'
import { getFilePath } from '../../utils/filepath'
Expand Down
9 changes: 6 additions & 3 deletions src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ type ValidatedData = Record<string, any>

declare global {
interface Request<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
CfHostMetadata = unknown,
ParamKeyType extends string = string,
Data extends ValidatedData = ValidatedData
> {
Expand Down Expand Up @@ -73,9 +75,10 @@ export function extendRequestPrototype() {
Request.prototype.header = function (this: Request, name?: string) {
if (!this.headerData) {
this.headerData = {}
for (const [key, value] of this.headers) {
this.headerData[key] = value
}
this.headers.forEach((value, key) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.headerData![key] = value
})
}
if (name) {
return this.headerData[name.toLowerCase()]
Expand Down
Loading

0 comments on commit 1eb49b8

Please sign in to comment.