Skip to content

Commit

Permalink
feat: implemented Remix server adapter and runtime for Netlify
Browse files Browse the repository at this point in the history
  • Loading branch information
nickytonline committed Jan 25, 2023
1 parent 4f12aea commit 7809450
Show file tree
Hide file tree
Showing 18 changed files with 1,319 additions and 3,004 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,5 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

build/
3,965 changes: 967 additions & 2,998 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
"version": "1.0.0",
"description": "Remix adapter and server runtime for Netlify",
"main": "index.js",
"workspaces": [
"packages/remix-server-adapter",
"packages/remix-server-runtime"
],
"scripts": {
"test": "vitest",
"coverage": "vitest run --coverage"
Expand All @@ -26,5 +30,8 @@
"prettier": "^2.8.3",
"typescript": "^4.9.4",
"vitest": "^0.28.2"
},
"dependencies": {
"@netlify/edge-functions": "^2.0.0"
}
}
21 changes: 21 additions & 0 deletions packages/remix-server-adapter/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License Copyright (c) 2023 Nick Taylor

Permission is hereby granted, free of
charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice
(including the next paragraph) shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
1 change: 1 addition & 0 deletions packages/remix-server-adapter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## Remix Adapter for Netlify
40 changes: 40 additions & 0 deletions packages/remix-server-adapter/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "@netlify/remix-server-adapter",
"version": "1.0.0",
"description": "Remix Adapter for Netlify Edge",
"types": "./build/src/index.d.ts",
"main": "./build/src/index.js",
"exports": {
".": "./build/src/index.js"
},
"files": [
"build/src/**/*.js",
"build/src/**/*.js.map",
"build/src/**/*.d.ts",
"build/src/**/*.d.ts.map",
"resources/**/*",
"LICENSE",
"README.md"
],
"scripts": {
"prepack": "npm run clean && npm run compile",
"compile": "tsc --build tsconfig.json",
"clean": "rm -rf build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/netlify/remix-compute.git"
},
"keywords": [
"remix",
"netlify"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/netlify/remix-compute/issues"
},
"homepage": "https://github.com/netlify/remix-compute#readme",
"dependencies": {
"@netlify/remix-server-runtime": "^1.0.0"
}
}
16 changes: 16 additions & 0 deletions packages/remix-server-adapter/src/globals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
Remix provides `process.env.NODE_ENV` at compile time.
Declare types for `process` here so that they are available in Deno.
*/

interface ProcessEnv {
NODE_ENV: 'development' | 'production' | 'test'
}
interface Process {
env: ProcessEnv
}
// deno-lint-ignore no-unused-vars no-var
var process: Process

// @ts-ignore
globalThis.process ||= { env: Deno.env.toObject() }
4 changes: 4 additions & 0 deletions packages/remix-server-adapter/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import './globals'

export type { GetLoadContextFunction, RequestHandler } from './server'
export { createRequestHandler } from './server'
57 changes: 57 additions & 0 deletions packages/remix-server-adapter/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { AppLoadContext, ServerBuild } from '@netlify/remix-server-runtime'
import { createRequestHandler as createRemixRequestHandler } from '@netlify/remix-server-runtime'
import type { Context } from '@netlify/edge-functions'

type LoadContext = AppLoadContext & Context

/**
* A function that returns the value to use as `context` in route `loader` and
* `action` functions.
*
* You can think of this as an escape hatch that allows you to pass
* environment/platform-specific values through to your loader/action.
*/
export type GetLoadContextFunction = (request: Request, context: Context) => Promise<LoadContext> | LoadContext

export type RequestHandler = (request: Request, context: LoadContext) => Promise<Response | void>

export function createRequestHandler({
build,
mode,
getLoadContext,
}: {
build: ServerBuild
mode?: string
getLoadContext?: GetLoadContextFunction
}): RequestHandler {
let remixHandler = createRemixRequestHandler(build, mode)

let assetPath = build.assets.url.split('/').slice(0, -1).join('/')

return async (request: Request, context: LoadContext): Promise<Response | void> => {
let { pathname } = new URL(request.url)
// Skip the handler for static files
if (pathname.startsWith(`${assetPath}/`)) {
return
}
try {
let loadContext = (await getLoadContext?.(request, context)) || context

let response = await remixHandler(request, loadContext)
if (response.status === 404) {
// Check if there is a matching static file
let originResponse = await context.next({
sendConditionalRequest: true,
})
if (originResponse.status !== 404) {
return originResponse
}
}
return response
} catch (error: unknown) {
console.error(error)

return new Response('Internal Error', { status: 500 })
}
}
}
13 changes: 13 additions & 0 deletions packages/remix-server-adapter/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "./build"
},
"include": [
"./src"
],
// "references": [
// { "path": "../remix-server-runtime/tsconfig.json"}
// ]
}
21 changes: 21 additions & 0 deletions packages/remix-server-runtime/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License Copyright (c) 2023 Nick Taylor

Permission is hereby granted, free of
charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice
(including the next paragraph) shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
1 change: 1 addition & 0 deletions packages/remix-server-runtime/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Remix Server Runtime for Netlify
24 changes: 24 additions & 0 deletions packages/remix-server-runtime/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@netlify/remix-server-runtime",
"version": "1.0.0",
"description": "Remix Runtime for Netlify Edge",
"types": "./build/src/index.d.ts",
"main": "./build/src/index.js",
"scripts": {
"prepack": "npm run clean && npm run compile",
"compile": "tsc --build tsconfig.json",
"clean": "rm -rf build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/netlify/remix-compute.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/netlify/remix-compute/issues"
},
"homepage": "https://github.com/netlify/remix-compute#readme",
"dependencies": {
"@remix-run/server-runtime": "^1.11.1"
}
}
46 changes: 46 additions & 0 deletions packages/remix-server-runtime/src/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { SignFunction, UnsignFunction } from '@remix-run/server-runtime'

const encoder = new TextEncoder()

export const sign: SignFunction = async (value, secret) => {
const data = encoder.encode(value)
const key = await createKey(secret, ['sign'])
const signature = await crypto.subtle.sign('HMAC', key, data)
const hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/=+$/, '')

return value + '.' + hash
}

export const unsign: UnsignFunction = async (cookie, secret) => {
const value = cookie.slice(0, cookie.lastIndexOf('.'))
const hash = cookie.slice(cookie.lastIndexOf('.') + 1)

const data = encoder.encode(value)
const key = await createKey(secret, ['verify'])
const signature = byteStringToUint8Array(atob(hash))
const valid = await crypto.subtle.verify('HMAC', key, signature, data)

return valid ? value : false
}

async function createKey(secret: string, usages: CryptoKey['usages']): Promise<CryptoKey> {
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
usages,
)

return key
}

function byteStringToUint8Array(byteString: string): Uint8Array {
const array = new Uint8Array(byteString.length)

for (let i = 0; i < byteString.length; i++) {
array[i] = byteString.charCodeAt(i)
}

return array
}
13 changes: 13 additions & 0 deletions packages/remix-server-runtime/src/implementations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {
createCookieFactory,
createCookieSessionStorageFactory,
createMemorySessionStorageFactory,
createSessionStorageFactory,
} from '@remix-run/server-runtime'

import { sign, unsign } from './crypto'

export const createCookie = createCookieFactory({ sign, unsign })
export const createCookieSessionStorage = createCookieSessionStorageFactory(createCookie)
export const createSessionStorage = createSessionStorageFactory(createCookie)
export const createMemorySessionStorage = createMemorySessionStorageFactory(createSessionStorage)
64 changes: 64 additions & 0 deletions packages/remix-server-runtime/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export {
createCookie,
createCookieSessionStorage,
createMemorySessionStorage,
createSessionStorage,
} from './implementations'

export {
createRequestHandler,
createSession,
isCookie,
isSession,
json,
MaxPartSizeExceededError,
redirect,
unstable_composeUploadHandlers,
unstable_createMemoryUploadHandler,
unstable_parseMultipartFormData,
} from '@remix-run/server-runtime'

// Remix server runtime packages should re-export these types
export type {
ActionArgs,
ActionFunction,
AppData,
AppLoadContext,
Cookie,
CookieOptions,
CookieParseOptions,
CookieSerializeOptions,
CookieSignatureOptions,
DataFunctionArgs,
EntryContext,
ErrorBoundaryComponent,
HandleDataRequestFunction,
HandleDocumentRequestFunction,
HeadersFunction,
HtmlLinkDescriptor,
HtmlMetaDescriptor,
LinkDescriptor,
LinksFunction,
LoaderArgs,
LoaderFunction,
MemoryUploadHandlerFilterArgs,
MemoryUploadHandlerOptions,
MetaDescriptor,
MetaFunction,
PageLinkDescriptor,
RequestHandler,
RouteComponent,
RouteHandle,
SerializeFrom,
ServerBuild,
ServerEntryModule,
Session,
SessionData,
SessionIdStorageStrategy,
SessionStorage,
SignFunction,
TypedResponse,
UnsignFunction,
UploadHandlerPart,
UploadHandler,
} from '@remix-run/server-runtime'
13 changes: 13 additions & 0 deletions packages/remix-server-runtime/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "./build"
},
"include": [
"./src"
],
// "references": [
// { "path": "../remix-server-runtime/tsconfig.json"}
// ]
}
Loading

0 comments on commit 7809450

Please sign in to comment.