Skip to content

Commit

Permalink
Migrate worker to wrangler 2 and TypeScript
Browse files Browse the repository at this point in the history
Modernizations to make it easier to add Durable Objects.
  • Loading branch information
mihaip committed Jun 1, 2022
1 parent 643faae commit e756f57
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 73 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ Common development tasks, all done via `npm run`:
Common deployment tasks (also done via `npm run`)

- `build`: Rebuild for either local use (in the `build/` directory) or for Cloudflare Worker use
- `worker-preview`: Preview built assets in a Cloudflare Worker (requires a separate `build` invocation)
- `worker-dev`: Preview built assets in a local Cloudflare Worker (requires a separate `build` invocation, result will be running at http://localhost:3128)
- `worker-deploy`: Deploy built assets to the live version of the Cloudflare Worker (requires a separate `build` invocation)

### Dependencies

Dependencies can be installed with:

```
npm install -g wrangler
npm install
pip3 install -r requirements.txt
npm run build-xadmaster
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"worker-preview": "wrangler preview --watch",
"worker-dev": "wrangler dev --local --port=3128",
"worker-deploy": "wrangler publish --env production"
},
"eslintConfig": {
Expand Down
94 changes: 50 additions & 44 deletions workers-site/index.js → workers-site/index.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,34 @@
import {getAssetFromKV} from "@cloudflare/kv-asset-handler";
// @ts-expect-error
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
const manifest = JSON.parse(manifestJSON);

/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false;
type Env = {
__STATIC_CONTENT: string;
};
const handler: ExportedHandler<Env> = {fetch: handleRequest};

addEventListener("fetch", event => {
try {
event.respondWith(handleEvent(event));
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
})
);
}
event.respondWith(new Response("Internal Error", {status: 500}));
}
});
export default handler;

async function handleEvent(event) {
const url = new URL(event.request.url);
const options = {};
async function handleRequest(
request: Request,
env: Env,
ctx: ExecutionContext
) {
const url = new URL(request.url);
const fetchEvent = {
request,
waitUntil(promise: Promise<any>) {
return ctx.waitUntil(promise);
},
};

try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
};
}
const page = await getAssetFromKV(event, options);
const page = await getAssetFromKV(fetchEvent, {
mapRequestToAsset,
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: manifest,
});
const response = new Response(page.body, page);
const {pathname} = url;

Expand Down Expand Up @@ -77,20 +70,33 @@ async function handleEvent(event) {
return response;
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
const notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req =>
new Request(`${new URL(req.url).origin}/404.html`, req),
});
try {
const notFoundResponse = await getAssetFromKV(fetchEvent, {
mapRequestToAsset: req =>
new Request(`${new URL(req.url).origin}/404.html`, req),
});

return new Response(notFoundResponse.body, {
...notFoundResponse,
status: 404,
});
} catch (e) {}
}
return new Response(notFoundResponse.body, {
...notFoundResponse,
status: 404,
});
} catch (e) {}

return new Response(e.message || e.toString(), {status: 500});
}
}

// Override default mapRequestToAsset to not append index.html to unknown
// MIME types (which is what some of the extensions like .wasmz and .jsz
// end up with).
function mapRequestToAsset(request: Request): Request {
const parsedUrl = new URL(request.url);
let pathname = parsedUrl.pathname;

if (pathname.endsWith("/")) {
pathname = pathname.concat("index.html");
}

parsedUrl.pathname = pathname;
return new Request(parsedUrl.toString(), request);
}
20 changes: 13 additions & 7 deletions workers-site/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 12 additions & 10 deletions workers-site/package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
{
"private": true,
"name": "worker",
"version": "1.0.0",
"description": "A template for kick starting a Cloudflare Workers project",
"main": "index.js",
"author": "Ashley Lewis <ashleymichal@gmail.com>",
"license": "MIT",
"dependencies": {
"@cloudflare/kv-asset-handler": "~0.1.2"
}
"private": true,
"name": "worker",
"version": "1.0.0",
"description": "Cloudflare Worker for serving Infinite Mac",
"main": "index.ts",
"license": "Apache",
"dependencies": {
"@cloudflare/kv-asset-handler": "~0.2.0"
},
"devDependencies": {
"@cloudflare/workers-types": "^3.11.0"
}
}
8 changes: 8 additions & 0 deletions workers-site/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"lib": ["ES2020"],
"types": ["@cloudflare/workers-types"]
}
}
20 changes: 10 additions & 10 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
name = "transparent-mac"
type = 'webpack'
account_id = '2ccb840de076261467812cbc32f8aa47'
route = ''
zone_id = ''
usage_model = ''
workers_dev = true
target_type = "webpack"
account_id = "2ccb840de076261467812cbc32f8aa47"
workers_dev = false
compatibility_date = "2021-11-08"
main = "workers-site/index.ts"

[site]
bucket = "./build"
entry-point = "workers-site"
exclude = ["BasiliskII.wasm.map"]

[env.production]
zone_id = "768b712e6dad883eb4c3aefbd5df8c80"
route = "mac.persistent.info/*"
routes = [
{pattern = "system7.app/*", zone_name = "system7.app"},
{pattern = "macos8.app/*", zone_name = "macos8.app"},
{pattern = "kanjitalk7.app/*", zone_name = "kanjitalk7.app"},
{pattern = "mac.persistent.info/*", zone_name = "persistent.info"},
]

0 comments on commit e756f57

Please sign in to comment.