Skip to content

Commit

Permalink
feat: use modules and setup (#99)
Browse files Browse the repository at this point in the history
closes #98
  • Loading branch information
hugomrdias committed Oct 13, 2022
1 parent 849c13e commit b060c0b
Show file tree
Hide file tree
Showing 20 changed files with 934 additions and 658 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
"lint-staged": "^13.0.3",
"prettier": "2.7.1",
"simple-git-hooks": "^2.8.0",
"typescript": "^4.8.3",
"wrangler": "^2.1.8"
"typescript": "^4.8.4",
"wrangler": "^2.1.11"
},
"simple-git-hooks": {
"pre-commit": "npx lint-staged"
Expand Down
22 changes: 12 additions & 10 deletions packages/access-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "Access API",
"type": "module",
"main": "dist/worker.js",
"module": "dist/worker.js",
"private": true,
"scripts": {
"lint": "tsc --build && eslint '**/*.{js,ts}' && prettier --check '**/*.{js,ts,yml,json}' --ignore-path ../../.gitignore",
Expand Down Expand Up @@ -34,27 +35,27 @@
},
"devDependencies": {
"@cloudflare/workers-types": "^3.16.0",
"@sentry/cli": "^2.6.0",
"@sentry/webpack-plugin": "^1.16.0",
"@sentry/cli": "^2.7.0",
"@sentry/webpack-plugin": "^1.19.1",
"@types/assert": "^1.5.6",
"@types/git-rev-sync": "^2.0.0",
"@types/node": "^18.7.23",
"@types/node": "^18.8.5",
"assert": "^2.0.0",
"ava": "^4.3.3",
"better-sqlite3": "7.6.2",
"buffer": "^6.0.3",
"delay": "^5.0.0",
"dotenv": "^16.0.2",
"esbuild": "^0.15.8",
"dotenv": "^16.0.3",
"esbuild": "^0.15.10",
"execa": "^6.1.0",
"git-rev-sync": "^3.0.1",
"hd-scripts": "^2.1.0",
"miniflare": "^2.9.0",
"hd-scripts": "^3.0.1",
"miniflare": "^2.10.0",
"process": "^0.11.10",
"readable-stream": "^4.1.0",
"sade": "^1.7.4",
"typescript": "4.8.3",
"wrangler": "^2.1.8"
"typescript": "4.8.4",
"wrangler": "^2.1.11"
},
"eslintConfig": {
"extends": [
Expand Down Expand Up @@ -87,7 +88,8 @@
"test/**/*.test.js"
],
"nodeArguments": [
"--no-warnings"
"--no-warnings",
"--experimental-vm-modules"
],
"ignoredByWatcher": [
"./dist/*"
Expand Down
1 change: 1 addition & 0 deletions packages/access-api/scripts/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ prog
await build({
entryPoints: [path.join(__dirname, '../src/index.js')],
bundle: true,
format: 'esm',
outfile: 'dist/worker.js',
legalComments: 'external',
inject: [path.join(__dirname, 'node-globals.js')],
Expand Down
55 changes: 44 additions & 11 deletions packages/access-api/src/bindings.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Logging } from '@web3-storage/worker-utils/logging'
import type { Handler as _Handler } from '@web3-storage/worker-utils/router'
import type { SigningPrincipal } from '@ucanto/interface'
import type { config } from './config'
import { Email } from './utils/email.js'
Expand All @@ -18,21 +19,28 @@ export interface AnalyticsEngineEvent {
readonly blobs?: Array<ArrayBuffer | string | null>
}

declare global {
const ACCOUNTS: KVNamespace
const VALIDATIONS: KVNamespace
const W3ACCESS_METRICS: AnalyticsEngine
export interface Env {
// vars
ENV: string
DEBUG: string
// secrets
PRIVATE_KEY: string
SENTRY_DSN: string
POSTMARK_TOKEN: string
LOGTAIL_TOKEN: string
// bindings
ACCOUNTS: KVNamespace
VALIDATIONS: KVNamespace
W3ACCESS_METRICS: AnalyticsEngine
// eslint-disable-next-line @typescript-eslint/naming-convention
const __D1_BETA__: D1Database
__D1_BETA__: D1Database
}

export interface RouteContext {
params: Record<string, string>
log: Logging
keypair: SigningPrincipal
config: typeof config
url: URL
event: FetchEvent
email: Email
kvs: {
accounts: Accounts
Expand All @@ -41,7 +49,32 @@ export interface RouteContext {
db: D1QB
}

export type Handler = (
event: FetchEvent,
ctx: RouteContext
) => Promise<Response> | Response
export type Handler = _Handler<RouteContext>

export type Bindings = Record<
string,
| KVNamespace
| DurableObjectNamespace
| CryptoKey
| string
| D1Database
| AnalyticsEngine
>
declare namespace ModuleWorker {
type FetchHandler<Environment extends Bindings = Bindings> = (
request: Request,
env: Environment,
ctx: Pick<FetchEvent, 'waitUntil' | 'passThroughOnException'>
) => Promise<Response> | Response

type CronHandler<Environment extends Bindings = Bindings> = (
event: Omit<ScheduledEvent, 'waitUntil'>,
env: Environment,
ctx: Pick<ScheduledEvent, 'waitUntil'>
) => Promise<void> | void
}

export interface ModuleWorker {
fetch?: ModuleWorker.FetchHandler<Env>
scheduled?: ModuleWorker.CronHandler<Env>
}
25 changes: 12 additions & 13 deletions packages/access-api/src/config.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
export const config = loadConfigVariables()

/**
* Loads configuration variables from the global environment and returns a JS object
* keyed by variable names.
*
* @param {import("./bindings").Env} env
*/
export function loadConfigVariables() {
export function loadConfig(env) {
/** @type Record<string, string> */
const vars = {}

/** @type Record<string, unknown> */
const globals = globalThis

/** @type {Array<keyof env>} */
const required = [
'ENV',
'DEBUG',
Expand All @@ -22,7 +19,7 @@ export function loadConfigVariables() {
]

for (const name of required) {
const val = globals[name]
const val = env[name]
if (typeof val === 'string' && val.length > 0) {
vars[name] = val
} else {
Expand Down Expand Up @@ -55,11 +52,11 @@ export function loadConfigVariables() {
// bindings
METRICS:
/** @type {import("./bindings").AnalyticsEngine} */ (
globals.W3ACCESS_METRICS
env.W3ACCESS_METRICS
) || createAnalyticsEngine(),
ACCOUNTS,
VALIDATIONS,
DB: /** @type {D1Database} */ (globals.__D1_BETA__),
ACCOUNTS: env.ACCOUNTS,
VALIDATIONS: env.VALIDATIONS,
DB: /** @type {D1Database} */ (env.__D1_BETA__),
}
}

Expand All @@ -83,10 +80,12 @@ function parseRuntimeEnv(s) {
case 'test':
case 'dev':
case 'staging':
case 'production':
case 'production': {
return s
default:
}
default: {
throw new Error('invalid runtime environment name: ' + s)
}
}
}

Expand Down
35 changes: 19 additions & 16 deletions packages/access-api/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,23 @@ r.add('get', '/validate-ws', validateWS)
r.add('post', '/', postRoot)
r.add('post', '/raw', postRaw)

addEventListener('fetch', (event) => {
const env = getContext(event, {})
env.log.time('request')
event.respondWith(
r
.handle(event, env)
.then((rsp) => {
env.log.timeEnd('request')
return env.log.end(corsHeaders(event.request, rsp))
})
.catch((error) => {
return env.log.end(
corsHeaders(event.request, errorHandler(error, env.log))
/** @type {import('./bindings.js').ModuleWorker} */
const worker = {
fetch: async (request, env, ctx) => {
const context = getContext(request, env, ctx)
context.log.time('request')
try {
const rsp = await r.fetch(request, context, ctx)
return context.log.end(corsHeaders(request, rsp))
} catch (error) {
return context.log.end(
corsHeaders(
request,
errorHandler(/** @type {Error} */ (error), context.log)
)
})
)
})
)
}
},
}

export default worker
2 changes: 1 addition & 1 deletion packages/access-api/src/kvs/accounts.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class Accounts {
*
* @param {KVNamespace} kv
*/
constructor(kv = ACCOUNTS) {
constructor(kv) {
this.kv = kv
}

Expand Down
2 changes: 1 addition & 1 deletion packages/access-api/src/kvs/validations.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export class Validations {
*
* @param {KVNamespace} kv
*/
constructor(kv = VALIDATIONS) {
constructor(kv) {
this.kv = kv
}

Expand Down
4 changes: 1 addition & 3 deletions packages/access-api/src/routes/validate.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Validations } from '../kvs/validations.js'

/**
* @param {import('@web3-storage/worker-utils/router').ParsedRequest} req
* @param {import('../bindings.js').RouteContext} env
*/
export async function validate(req, env) {
const validations = new Validations()
const validations = env.kvs.validations
if (req.query && req.query.ucan) {
await validations.create(req.query.ucan)

Expand Down
20 changes: 3 additions & 17 deletions packages/access-api/src/routes/version.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,7 @@
import { JSONResponse } from '@web3-storage/worker-utils/response'
/**
* @param {import('@web3-storage/worker-utils/router').ParsedRequest} event
* @param {import('../bindings.js').RouteContext} env
*/
export async function version(event, env) {
// const inserted = await env.db.insert({
// tableName: 'accounts',
// data: {
// did: 'did:key:ztest',
// product: 'free',
// email: 'hugomrdias@gmail.com',
// agent: 'did:key:zagent',
// },
// returning: '*',
// })
// console.log('🚀 ~ file: version.js ~ line 15 ~ version ~ inserted', inserted)
// console.log(new Date(inserted.results[0].inserted_at).toISOString())

/** @type {import('../bindings.js').Handler} */
export async function version(event, env, ctx) {
return new JSONResponse({
version: env.config.VERSION,
commit: env.config.COMMITHASH,
Expand Down
Loading

0 comments on commit b060c0b

Please sign in to comment.