Comparing version 0.1.5 to 0.1.6
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.EdgeQL = void 0; | ||
const schema_1 = require("@graphql-tools/schema"); | ||
const graphql_1 = require("graphql"); | ||
const compose_1 = require("./compose"); | ||
const context_1 = require("./context/context"); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var app_exports = {}; | ||
__export(app_exports, { | ||
EdgeQL: () => EdgeQL | ||
}); | ||
module.exports = __toCommonJS(app_exports); | ||
var import_schema = require("@graphql-tools/schema"); | ||
var import_graphql = require("graphql"); | ||
var import_compose = require("./compose"); | ||
var import_context = require("./context/context"); | ||
class EdgeQL { | ||
constructor() { | ||
this.schemas = []; | ||
this.middlewares = []; | ||
this.fetch = async (request, env, exeContext) => { | ||
if (request.method !== 'GET' && request.method !== 'POST') { | ||
return new Response('GraphQL only supports GET and POST requests.', { | ||
status: 405, | ||
}); | ||
constructor() { | ||
this.schemas = []; | ||
this.middlewares = []; | ||
this.fetch = async (request, env, exeContext) => { | ||
if (request.method !== "GET" && request.method !== "POST") { | ||
return new Response("GraphQL only supports GET and POST requests.", { | ||
status: 405 | ||
}); | ||
} | ||
let ctx; | ||
try { | ||
ctx = new import_context.Context(request, env, exeContext); | ||
} catch (e) { | ||
return new Response( | ||
JSON.stringify({ | ||
data: null, | ||
errors: [ | ||
new import_graphql.GraphQLError(`GraphQL params error: ${e}`, { | ||
extensions: { | ||
status: 400 | ||
} | ||
}) | ||
] | ||
}) | ||
); | ||
} | ||
await ctx.graphql.init(ctx.http.request); | ||
ctx.graphql.schema = this.graph; | ||
await (0, import_compose.compose)([...this.middlewares, this.execute])(ctx); | ||
return ctx.json(); | ||
}; | ||
} | ||
async execute(ctx) { | ||
if (!ctx.graphql.query) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new import_graphql.GraphQLError("Must provide query string", { | ||
extensions: { | ||
status: 400 | ||
} | ||
let ctx; | ||
try { | ||
ctx = new context_1.Context(request, env, exeContext); | ||
}) | ||
] | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.document) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new import_graphql.GraphQLError(`could not generate document from query: ${ctx.graphql.query}`, { | ||
extensions: { | ||
status: 400 | ||
} | ||
catch (e) { | ||
return new Response(JSON.stringify({ | ||
data: null, | ||
errors: [ | ||
new graphql_1.GraphQLError(`GraphQL params error: ${e}`, { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
})); | ||
}) | ||
] | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.schema) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new import_graphql.GraphQLError("no schem registerred yet", { | ||
extensions: { | ||
status: 400 | ||
} | ||
await ctx.graphql.init(ctx.http.request); | ||
ctx.graphql.schema = this.graph; | ||
await (0, compose_1.compose)([...this.middlewares, this.execute])(ctx); | ||
return ctx.json(); | ||
}; | ||
}) | ||
] | ||
}; | ||
return; | ||
} | ||
async execute(ctx) { | ||
if (!ctx.graphql.query) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new graphql_1.GraphQLError('Must provide query string', { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.document) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new graphql_1.GraphQLError(`could not generate document from query: ${ctx.graphql.query}`, { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.schema) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new graphql_1.GraphQLError('no schem registerred yet', { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
}; | ||
return; | ||
} | ||
try { | ||
const res = await (0, graphql_1.execute)({ | ||
schema: ctx.graphql.schema, | ||
document: ctx.graphql.document ?? null, | ||
rootValue: null, | ||
contextValue: ctx, | ||
variableValues: ctx.graphql.variables, | ||
operationName: ctx.graphql.operationName, | ||
}); | ||
ctx.http.status = 200; | ||
ctx.http.body = res; | ||
return; | ||
} | ||
catch (contextError) { | ||
ctx.http.status = 500; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new graphql_1.GraphQLError(`GraphQL execution context error: ${contextError}`, { | ||
extensions: { | ||
status: 500, | ||
}, | ||
}), | ||
], | ||
}; | ||
} | ||
try { | ||
const res = await (0, import_graphql.execute)({ | ||
schema: ctx.graphql.schema, | ||
document: ctx.graphql.document ?? null, | ||
rootValue: null, | ||
contextValue: ctx, | ||
variableValues: ctx.graphql.variables, | ||
operationName: ctx.graphql.operationName | ||
}); | ||
ctx.http.status = 200; | ||
ctx.http.body = res; | ||
return; | ||
} catch (contextError) { | ||
ctx.http.status = 500; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new import_graphql.GraphQLError(`GraphQL execution context error: ${contextError}`, { | ||
extensions: { | ||
status: 500 | ||
} | ||
}) | ||
] | ||
}; | ||
} | ||
use(fn) { | ||
this.middlewares.push(fn); | ||
} | ||
handle(...args) { | ||
if (args.length === 1 && typeof args[0] === 'object') { | ||
const schemaValidationErrors = (0, graphql_1.validateSchema)(args[0]); | ||
if (schemaValidationErrors.length > 0) { | ||
throw new Error(`Invalid schema: ${args[0]}`); | ||
} | ||
this.schemas.push(args[0]); | ||
} | ||
use(fn) { | ||
this.middlewares.push(fn); | ||
} | ||
handle(...args) { | ||
if (args.length === 1 && typeof args[0] === "object") { | ||
const schemaValidationErrors = (0, import_graphql.validateSchema)(args[0]); | ||
if (schemaValidationErrors.length > 0) { | ||
throw new Error(`Invalid schema: ${args[0]}`); | ||
} | ||
this.schemas.push(args[0]); | ||
} else if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "function") { | ||
const s = (0, import_graphql.buildSchema)(args[0]); | ||
const typs = ["Query", "Mutation", "Subscription"]; | ||
const fields = []; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof import_graphql.GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
fields.push(obj.getFields()[f]); | ||
} | ||
} | ||
else if (args.length === 2 && typeof args[0] === 'string' && typeof args[1] === 'function') { | ||
const s = (0, graphql_1.buildSchema)(args[0]); | ||
const typs = ['Query', 'Mutation', 'Subscription']; | ||
const fields = []; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof graphql_1.GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
fields.push(obj.getFields()[f]); | ||
} | ||
} | ||
} | ||
if (fields.length !== 1) { | ||
throw new Error("only one of Query, Mutation, Subscription is allowed"); | ||
} else { | ||
fields[0].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.args = arg; | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.info = info; | ||
return await args[1](ctx); | ||
}; | ||
} | ||
this.schemas.push(s); | ||
} else if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "object") { | ||
const s = (0, import_graphql.buildSchema)(args[0]); | ||
const typs = ["Query", "Mutation", "Subscription"]; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof import_graphql.GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
if (args[1][f]) { | ||
obj.getFields()[f].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.args = arg; | ||
ctx.graphql.info = info; | ||
const fn = args[1][f]; | ||
return await fn(ctx); | ||
}; | ||
} else { | ||
throw new Error(`no resolve function for ${obj.getFields()[f]}`); | ||
} | ||
if (fields.length !== 1) { | ||
throw new Error('only one of Query, Mutation, Subscription is allowed'); | ||
} | ||
else { | ||
fields[0].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.args = arg; | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.info = info; | ||
return await args[1](ctx); | ||
}; | ||
} | ||
this.schemas.push(s); | ||
} | ||
} | ||
else if (args.length === 2 && typeof args[0] === 'string' && typeof args[1] === 'object') { | ||
const s = (0, graphql_1.buildSchema)(args[0]); | ||
const typs = ['Query', 'Mutation', 'Subscription']; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof graphql_1.GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
if (args[1][f]) { | ||
obj.getFields()[f].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.args = arg; | ||
ctx.graphql.info = info; | ||
const fn = args[1][f]; | ||
return await fn(ctx); | ||
}; | ||
} | ||
else { | ||
throw new Error(`no resolve function for ${obj.getFields()[f]}`); | ||
} | ||
} | ||
} | ||
} | ||
this.schemas.push(s); | ||
} | ||
else { | ||
throw new Error('invalid of parameters for register'); | ||
} | ||
this.graph = (0, schema_1.mergeSchemas)({ schemas: this.schemas ?? [] }); | ||
} | ||
this.schemas.push(s); | ||
} else { | ||
throw new Error("invalid of parameters for register"); | ||
} | ||
this.graph = (0, import_schema.mergeSchemas)({ schemas: this.schemas ?? [] }); | ||
} | ||
} | ||
exports.EdgeQL = EdgeQL; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
EdgeQL | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.compose = void 0; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var compose_exports = {}; | ||
__export(compose_exports, { | ||
compose: () => compose | ||
}); | ||
module.exports = __toCommonJS(compose_exports); | ||
function compose(middleware) { | ||
for (const fn of middleware) { | ||
if (typeof fn !== 'function') { | ||
throw new TypeError('Middleware must be composed of functions!'); | ||
} | ||
for (const fn of middleware) { | ||
if (typeof fn !== "function") { | ||
throw new TypeError("Middleware must be composed of functions!"); | ||
} | ||
return (context, next) => { | ||
// last called middleware # | ||
let index = -1; | ||
return dispatch(0); | ||
function dispatch(i) { | ||
if (i <= index) { | ||
return Promise.reject(new Error('next() called multiple times')); | ||
} | ||
index = i; | ||
let fn = middleware[i]; | ||
if (i === middleware.length && next) { | ||
fn = next; | ||
} | ||
if (!fn) { | ||
return Promise.resolve(); | ||
} | ||
try { | ||
const ctx = fn(context, async () => { | ||
await dispatch(i + 1); | ||
}); | ||
return Promise.resolve(ctx); | ||
} | ||
catch (err) { | ||
return Promise.reject(err); | ||
} | ||
} | ||
}; | ||
} | ||
return (context, next) => { | ||
let index = -1; | ||
return dispatch(0); | ||
function dispatch(i) { | ||
if (i <= index) { | ||
return Promise.reject(new Error("next() called multiple times")); | ||
} | ||
index = i; | ||
let fn = middleware[i]; | ||
if (i === middleware.length && next) { | ||
fn = next; | ||
} | ||
if (!fn) { | ||
return Promise.resolve(); | ||
} | ||
try { | ||
const ctx = fn(context, async () => { | ||
await dispatch(i + 1); | ||
}); | ||
return Promise.resolve(ctx); | ||
} catch (err) { | ||
return Promise.reject(err); | ||
} | ||
} | ||
}; | ||
} | ||
exports.compose = compose; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
compose | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Context = void 0; | ||
const graphql_1 = require("./graphql"); | ||
const http_1 = require("./http"); | ||
const runtime_1 = require("./runtime"); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var context_exports = {}; | ||
__export(context_exports, { | ||
Context: () => Context | ||
}); | ||
module.exports = __toCommonJS(context_exports); | ||
var import_graphql = require("./graphql"); | ||
var import_http = require("./http"); | ||
var import_runtime = require("./runtime"); | ||
class Context { | ||
constructor(request, env, exeContext) { | ||
this.runtime = new runtime_1.RuntimeContext(env, exeContext); | ||
this.http = new http_1.HttpContext(request); | ||
this.graphql = new graphql_1.GraphQLContext(); | ||
constructor(request, env, exeContext) { | ||
this.runtime = new import_runtime.RuntimeContext(env, exeContext); | ||
this.http = new import_http.HttpContext(request); | ||
this.graphql = new import_graphql.GraphQLContext(); | ||
} | ||
json() { | ||
return this.http.toJSON(); | ||
} | ||
set(key, value) { | ||
this._map || (this._map = {}); | ||
this._map[key] = value; | ||
} | ||
get(key) { | ||
if (!this._map) { | ||
return void 0; | ||
} | ||
json() { | ||
return this.http.toJSON(); | ||
} | ||
set(key, value) { | ||
this._map ||= {}; | ||
this._map[key] = value; | ||
} | ||
get(key) { | ||
if (!this._map) { | ||
return undefined; | ||
} | ||
return this._map[key]; | ||
} | ||
return this._map[key]; | ||
} | ||
} | ||
exports.Context = Context; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
Context | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.GraphQLContext = void 0; | ||
const graphql_1 = require("graphql"); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var graphql_exports = {}; | ||
__export(graphql_exports, { | ||
GraphQLContext: () => GraphQLContext | ||
}); | ||
module.exports = __toCommonJS(graphql_exports); | ||
var import_graphql = require("graphql"); | ||
class GraphQLContext { | ||
async init(request) { | ||
const contentType = request.headers.get('content-type'); | ||
switch (contentType) { | ||
case 'application/graphql': { | ||
const query = await request.text(); | ||
this.query = query; | ||
break; | ||
} | ||
case 'application/json': { | ||
const { query, operationName, variables, extensions } = (await request.json()); | ||
this.query = query; | ||
this.variables = variables; | ||
this.operationName = operationName; | ||
this.extensions = extensions; | ||
break; | ||
} | ||
case 'application/x-www-form-urlencoded': { | ||
const text = await request.text(); | ||
const searchParams = new URLSearchParams(text); | ||
searchParams.forEach((v, k) => { | ||
if (k === 'query') { | ||
this.query = v; | ||
} | ||
else if (k === 'variables') { | ||
this.variables = JSON.parse(v); | ||
} | ||
else if (k === 'operationName') { | ||
this.operationName = v; | ||
} | ||
}); | ||
break; | ||
} | ||
} | ||
if (this.query) { | ||
this.document = (0, graphql_1.parse)(this.query); | ||
} | ||
async init(request) { | ||
const contentType = request.headers.get("content-type"); | ||
switch (contentType) { | ||
case "application/graphql": { | ||
const query = await request.text(); | ||
this.query = query; | ||
break; | ||
} | ||
case "application/json": { | ||
const { query, operationName, variables, extensions } = await request.json(); | ||
this.query = query; | ||
this.variables = variables; | ||
this.operationName = operationName; | ||
this.extensions = extensions; | ||
break; | ||
} | ||
case "application/x-www-form-urlencoded": { | ||
const text = await request.text(); | ||
const searchParams = new URLSearchParams(text); | ||
searchParams.forEach((v, k) => { | ||
if (k === "query") { | ||
this.query = v; | ||
} else if (k === "variables") { | ||
this.variables = JSON.parse(v); | ||
} else if (k === "operationName") { | ||
this.operationName = v; | ||
} | ||
}); | ||
break; | ||
} | ||
} | ||
set query(query) { | ||
this._query = query; | ||
if (this.query) { | ||
this.document = (0, import_graphql.parse)(this.query); | ||
} | ||
get query() { | ||
return this._query; | ||
} | ||
set operationName(operationName) { | ||
this._operationName = operationName; | ||
} | ||
get operationName() { | ||
return this._operationName; | ||
} | ||
set variables(variables) { | ||
this._variables = variables; | ||
} | ||
get variables() { | ||
return this._variables; | ||
} | ||
set extensions(extensions) { | ||
this._extensions = extensions; | ||
} | ||
get extensions() { | ||
return this._extensions; | ||
} | ||
set parents(value) { | ||
this._parents = value; | ||
} | ||
get parents() { | ||
return this._parents; | ||
} | ||
set args(value) { | ||
this._args = value; | ||
} | ||
get args() { | ||
return this._args; | ||
} | ||
set info(value) { | ||
this._info = value; | ||
} | ||
get info() { | ||
return this._info; | ||
} | ||
set document(document) { | ||
this._document = document; | ||
} | ||
get document() { | ||
return this._document; | ||
} | ||
get schema() { | ||
return this._schema; | ||
} | ||
set schema(schema) { | ||
this._schema = schema; | ||
} | ||
} | ||
set query(query) { | ||
this._query = query; | ||
} | ||
get query() { | ||
return this._query; | ||
} | ||
set operationName(operationName) { | ||
this._operationName = operationName; | ||
} | ||
get operationName() { | ||
return this._operationName; | ||
} | ||
set variables(variables) { | ||
this._variables = variables; | ||
} | ||
get variables() { | ||
return this._variables; | ||
} | ||
set extensions(extensions) { | ||
this._extensions = extensions; | ||
} | ||
get extensions() { | ||
return this._extensions; | ||
} | ||
set parents(value) { | ||
this._parents = value; | ||
} | ||
get parents() { | ||
return this._parents; | ||
} | ||
set args(value) { | ||
this._args = value; | ||
} | ||
get args() { | ||
return this._args; | ||
} | ||
set info(value) { | ||
this._info = value; | ||
} | ||
get info() { | ||
return this._info; | ||
} | ||
set document(document) { | ||
this._document = document; | ||
} | ||
get document() { | ||
return this._document; | ||
} | ||
get schema() { | ||
return this._schema; | ||
} | ||
set schema(schema) { | ||
this._schema = schema; | ||
} | ||
} | ||
exports.GraphQLContext = GraphQLContext; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
GraphQLContext | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.HttpContext = void 0; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var http_exports = {}; | ||
__export(http_exports, { | ||
HttpContext: () => HttpContext | ||
}); | ||
module.exports = __toCommonJS(http_exports); | ||
class HttpContext { | ||
constructor(request) { | ||
this._headers = new Headers(); | ||
this.request = request; | ||
} | ||
toJSON() { | ||
this.headers.set('content-type', 'application/json'); | ||
return new Response(JSON.stringify(this.body), { | ||
status: this.status ?? 200, | ||
statusText: this.statusText ?? '', | ||
headers: this.headers, | ||
}); | ||
} | ||
toText() { | ||
return new Response(this.body, { | ||
status: this.status ?? 200, | ||
headers: this.headers, | ||
}); | ||
} | ||
set status(status) { | ||
this._status = status; | ||
} | ||
get status() { | ||
return this._status; | ||
} | ||
set statusText(text) { | ||
this._statusText = text; | ||
} | ||
get statusText() { | ||
return this._statusText; | ||
} | ||
get headers() { | ||
return this._headers; | ||
} | ||
set body(body) { | ||
this._body = body; | ||
} | ||
get body() { | ||
return this._body; | ||
} | ||
constructor(request) { | ||
this._headers = new Headers(); | ||
this.request = request; | ||
} | ||
toJSON() { | ||
this.headers.set("content-type", "application/json"); | ||
return new Response(JSON.stringify(this.body), { | ||
status: this.status ?? 200, | ||
statusText: this.statusText ?? "", | ||
headers: this.headers | ||
}); | ||
} | ||
toText() { | ||
return new Response(this.body, { | ||
status: this.status ?? 200, | ||
headers: this.headers | ||
}); | ||
} | ||
set status(status) { | ||
this._status = status; | ||
} | ||
get status() { | ||
return this._status; | ||
} | ||
set statusText(text) { | ||
this._statusText = text; | ||
} | ||
get statusText() { | ||
return this._statusText; | ||
} | ||
get headers() { | ||
return this._headers; | ||
} | ||
set body(body) { | ||
this._body = body; | ||
} | ||
get body() { | ||
return this._body; | ||
} | ||
} | ||
exports.HttpContext = HttpContext; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
HttpContext | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.RuntimeContext = void 0; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var runtime_exports = {}; | ||
__export(runtime_exports, { | ||
RuntimeContext: () => RuntimeContext | ||
}); | ||
module.exports = __toCommonJS(runtime_exports); | ||
class RuntimeContext { | ||
constructor(env, exeContext) { | ||
this.env = env; | ||
this.exeContext = exeContext; | ||
} | ||
constructor(env, exeContext) { | ||
this.env = env; | ||
this.exeContext = exeContext; | ||
} | ||
} | ||
exports.RuntimeContext = RuntimeContext; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
RuntimeContext | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Context = exports.EdgeQL = void 0; | ||
var app_1 = require("./app"); | ||
Object.defineProperty(exports, "EdgeQL", { enumerable: true, get: function () { return app_1.EdgeQL; } }); | ||
var context_1 = require("./context/context"); | ||
Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_1.Context; } }); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var src_exports = {}; | ||
__export(src_exports, { | ||
Context: () => import_context.Context, | ||
EdgeQL: () => import_app.EdgeQL | ||
}); | ||
module.exports = __toCommonJS(src_exports); | ||
var import_app = require("./app"); | ||
var import_context = require("./context/context"); | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
Context, | ||
EdgeQL | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.jwt = void 0; | ||
const jwt_1 = require("../../utils/jwt"); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var jwt_exports = {}; | ||
__export(jwt_exports, { | ||
jwt: () => jwt | ||
}); | ||
module.exports = __toCommonJS(jwt_exports); | ||
var import_jwt = require("../../utils/jwt"); | ||
const jwt = (options) => { | ||
if (!options) { | ||
throw new Error('JWT auth middleware requires options for "secret'); | ||
if (!options) { | ||
throw new Error('JWT auth middleware requires options for "secret'); | ||
} | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); | ||
} | ||
return async (ctx, next) => { | ||
const credentials = ctx.http.request.headers.get("Authorization"); | ||
let token; | ||
if (credentials) { | ||
const parts = credentials.split(/\s+/); | ||
if (parts.length !== 2) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = "Unauthorized"; | ||
ctx.http.headers.set( | ||
"WWW-Authenticate", | ||
`Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="invalid credentials structure"` | ||
); | ||
return; | ||
} else { | ||
token = parts[1]; | ||
} | ||
} | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.'); | ||
if (!token) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = "Unauthorized"; | ||
ctx.http.headers.set( | ||
"WWW-Authenticate", | ||
`Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="no authorization included in request"` | ||
); | ||
return; | ||
} | ||
return async (ctx, next) => { | ||
const credentials = ctx.http.request.headers.get('Authorization'); | ||
let token; | ||
if (credentials) { | ||
const parts = credentials.split(/\s+/); | ||
if (parts.length !== 2) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = 'Unauthorized'; | ||
ctx.http.headers.set('WWW-Authenticate', `Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="invalid credentials structure"`); | ||
return; | ||
} | ||
else { | ||
token = parts[1]; | ||
} | ||
} | ||
if (!token) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = 'Unauthorized'; | ||
ctx.http.headers.set('WWW-Authenticate', `Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="no authorization included in request"`); | ||
return; | ||
} | ||
let authorized = false; | ||
let msg = ''; | ||
try { | ||
authorized = await jwt_1.Jwt.verify(token, options.secret, options.alg); | ||
} | ||
catch (e) { | ||
msg = `${e}`; | ||
} | ||
if (!authorized) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = msg; | ||
ctx.http.headers.set('WWW-Authenticate', `Bearer realm="${ctx.http.request.url}",error="invalid_token",error_description="token verification failure"`); | ||
return; | ||
} | ||
await next(); | ||
}; | ||
let authorized = false; | ||
let msg = ""; | ||
try { | ||
authorized = await import_jwt.Jwt.verify(token, options.secret, options.alg); | ||
} catch (e) { | ||
msg = `${e}`; | ||
} | ||
if (!authorized) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = msg; | ||
ctx.http.headers.set( | ||
"WWW-Authenticate", | ||
`Bearer realm="${ctx.http.request.url}",error="invalid_token",error_description="token verification failure"` | ||
); | ||
return; | ||
} | ||
await next(); | ||
}; | ||
}; | ||
exports.jwt = jwt; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
jwt | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.wallclock = void 0; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var wallclock_exports = {}; | ||
__export(wallclock_exports, { | ||
wallclock: () => wallclock | ||
}); | ||
module.exports = __toCommonJS(wallclock_exports); | ||
const wallclock = async (ctx, next) => { | ||
const startedAt = new Date(); | ||
await next(); | ||
const endedAt = new Date(); | ||
ctx.http.headers.set('x-edgeql-wallclock', `${endedAt.getTime() - startedAt.getTime()}`); | ||
const startedAt = new Date(); | ||
await next(); | ||
const endedAt = new Date(); | ||
ctx.http.headers.set("x-edgeql-wallclock", `${endedAt.getTime() - startedAt.getTime()}`); | ||
}; | ||
exports.wallclock = wallclock; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
wallclock | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var types_exports = {}; | ||
module.exports = __toCommonJS(types_exports); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.arrayBufferToBase64URL = exports.arrayBufferToBase64 = exports.utf8ToUint8Array = exports.decodeBase64URL = exports.encodeBase64URL = exports.decodeBase64 = exports.encodeBase64 = void 0; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var encode_exports = {}; | ||
__export(encode_exports, { | ||
arrayBufferToBase64: () => arrayBufferToBase64, | ||
arrayBufferToBase64URL: () => arrayBufferToBase64URL, | ||
decodeBase64: () => decodeBase64, | ||
decodeBase64URL: () => decodeBase64URL, | ||
encodeBase64: () => encodeBase64, | ||
encodeBase64URL: () => encodeBase64URL, | ||
utf8ToUint8Array: () => utf8ToUint8Array | ||
}); | ||
module.exports = __toCommonJS(encode_exports); | ||
const encodeBase64 = (str) => { | ||
if (str === null) { | ||
throw new TypeError('1st argument of "encodeBase64" should not be null.'); | ||
} | ||
try { | ||
const encoder = new TextEncoder(); | ||
const bytes = encoder.encode(str); | ||
return btoa(String.fromCharCode(...bytes)); | ||
} | ||
catch { } | ||
try { | ||
return Buffer.from(str).toString('base64'); | ||
} | ||
catch (e) { | ||
console.error('If you want to do "encodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
if (str === null) { | ||
throw new TypeError('1st argument of "encodeBase64" should not be null.'); | ||
} | ||
try { | ||
const encoder = new TextEncoder(); | ||
const bytes = encoder.encode(str); | ||
return btoa(String.fromCharCode(...bytes)); | ||
} catch { | ||
} | ||
try { | ||
return Buffer.from(str).toString("base64"); | ||
} catch (e) { | ||
console.error('If you want to do "encodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
}; | ||
exports.encodeBase64 = encodeBase64; | ||
const decodeBase64 = (str) => { | ||
if (str === null) { | ||
throw new TypeError('1st argument of "decodeBase64" should not be null.'); | ||
} | ||
try { | ||
const text = atob(str); | ||
const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0))); | ||
const decoder = new TextDecoder(); | ||
return decoder.decode(bytes); | ||
} | ||
catch { } | ||
try { | ||
return Buffer.from(str, 'base64').toString(); | ||
} | ||
catch (e) { | ||
console.error('If you want to do "decodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
if (str === null) { | ||
throw new TypeError('1st argument of "decodeBase64" should not be null.'); | ||
} | ||
try { | ||
const text = atob(str); | ||
const bytes = new Uint8Array(text.split("").map((c) => c.charCodeAt(0))); | ||
const decoder = new TextDecoder(); | ||
return decoder.decode(bytes); | ||
} catch { | ||
} | ||
try { | ||
return Buffer.from(str, "base64").toString(); | ||
} catch (e) { | ||
console.error('If you want to do "decodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
}; | ||
exports.decodeBase64 = decodeBase64; | ||
const encodeBase64URL = (str) => { | ||
return (0, exports.encodeBase64)(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); | ||
return encodeBase64(str).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); | ||
}; | ||
exports.encodeBase64URL = encodeBase64URL; | ||
const decodeBase64URL = (str) => { | ||
const pad = (s) => { | ||
const diff = s.length % 4; | ||
if (diff === 2) { | ||
return `${s}==`; | ||
} | ||
if (diff === 3) { | ||
return `${s}=`; | ||
} | ||
return s; | ||
}; | ||
return (0, exports.decodeBase64)(pad(str).replace(/-/g, '+').replace('_', '/')); | ||
const pad = (s) => { | ||
const diff = s.length % 4; | ||
if (diff === 2) { | ||
return `${s}==`; | ||
} | ||
if (diff === 3) { | ||
return `${s}=`; | ||
} | ||
return s; | ||
}; | ||
return decodeBase64(pad(str).replace(/-/g, "+").replace("_", "/")); | ||
}; | ||
exports.decodeBase64URL = decodeBase64URL; | ||
const utf8ToUint8Array = (str) => { | ||
const encoder = new TextEncoder(); | ||
return encoder.encode(str); | ||
const encoder = new TextEncoder(); | ||
return encoder.encode(str); | ||
}; | ||
exports.utf8ToUint8Array = utf8ToUint8Array; | ||
const arrayBufferToBase64 = async (buf) => { | ||
if (typeof btoa === 'function') { | ||
return btoa(String.fromCharCode(...new Uint8Array(buf))); | ||
} | ||
try { | ||
return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64'); | ||
} | ||
catch (e) { } | ||
return ''; | ||
if (typeof btoa === "function") { | ||
return btoa(String.fromCharCode(...new Uint8Array(buf))); | ||
} | ||
try { | ||
return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString("base64"); | ||
} catch (e) { | ||
} | ||
return ""; | ||
}; | ||
exports.arrayBufferToBase64 = arrayBufferToBase64; | ||
const arrayBufferToBase64URL = async (buf) => { | ||
return (await (0, exports.arrayBufferToBase64)(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); | ||
return (await arrayBufferToBase64(buf)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); | ||
}; | ||
exports.arrayBufferToBase64URL = arrayBufferToBase64URL; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
arrayBufferToBase64, | ||
arrayBufferToBase64URL, | ||
decodeBase64, | ||
decodeBase64URL, | ||
encodeBase64, | ||
encodeBase64URL, | ||
utf8ToUint8Array | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Jwt = void 0; | ||
exports.Jwt = require("./jwt"); | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var jwt_exports = {}; | ||
__export(jwt_exports, { | ||
Jwt: () => Jwt | ||
}); | ||
module.exports = __toCommonJS(jwt_exports); | ||
var Jwt = __toESM(require("./jwt"), 1); | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
Jwt | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.decode = exports.verify = exports.sign = void 0; | ||
const encode_1 = require("../../utils/encode"); | ||
const types_1 = require("./types"); | ||
const types_2 = require("./types"); | ||
var CryptoKeyFormat; | ||
(function (CryptoKeyFormat) { | ||
CryptoKeyFormat["RAW"] = "raw"; | ||
CryptoKeyFormat["PKCS8"] = "pkcs8"; | ||
CryptoKeyFormat["SPKI"] = "spki"; | ||
CryptoKeyFormat["JWK"] = "jwk"; | ||
})(CryptoKeyFormat || (CryptoKeyFormat = {})); | ||
var CryptoKeyUsage; | ||
(function (CryptoKeyUsage) { | ||
CryptoKeyUsage["Ecrypt"] = "encrypt"; | ||
CryptoKeyUsage["Decrypt"] = "decrypt"; | ||
CryptoKeyUsage["Sign"] = "sign"; | ||
CryptoKeyUsage["Verify"] = "verify"; | ||
CryptoKeyUsage["Deriverkey"] = "deriveKey"; | ||
CryptoKeyUsage["DeriveBits"] = "deriveBits"; | ||
CryptoKeyUsage["WrapKey"] = "wrapKey"; | ||
CryptoKeyUsage["UnwrapKey"] = "unwrapKey"; | ||
})(CryptoKeyUsage || (CryptoKeyUsage = {})); | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var jwt_exports = {}; | ||
__export(jwt_exports, { | ||
decode: () => decode, | ||
sign: () => sign, | ||
verify: () => verify | ||
}); | ||
module.exports = __toCommonJS(jwt_exports); | ||
var import_encode = require("../../utils/encode"); | ||
var import_types = require("./types"); | ||
var import_types2 = require("./types"); | ||
var CryptoKeyFormat = /* @__PURE__ */ ((CryptoKeyFormat2) => { | ||
CryptoKeyFormat2["RAW"] = "raw"; | ||
CryptoKeyFormat2["PKCS8"] = "pkcs8"; | ||
CryptoKeyFormat2["SPKI"] = "spki"; | ||
CryptoKeyFormat2["JWK"] = "jwk"; | ||
return CryptoKeyFormat2; | ||
})(CryptoKeyFormat || {}); | ||
var CryptoKeyUsage = /* @__PURE__ */ ((CryptoKeyUsage2) => { | ||
CryptoKeyUsage2["Ecrypt"] = "encrypt"; | ||
CryptoKeyUsage2["Decrypt"] = "decrypt"; | ||
CryptoKeyUsage2["Sign"] = "sign"; | ||
CryptoKeyUsage2["Verify"] = "verify"; | ||
CryptoKeyUsage2["Deriverkey"] = "deriveKey"; | ||
CryptoKeyUsage2["DeriveBits"] = "deriveBits"; | ||
CryptoKeyUsage2["WrapKey"] = "wrapKey"; | ||
CryptoKeyUsage2["UnwrapKey"] = "unwrapKey"; | ||
return CryptoKeyUsage2; | ||
})(CryptoKeyUsage || {}); | ||
const param = (name) => { | ||
switch (name.toUpperCase()) { | ||
case 'HS256': | ||
return { | ||
name: 'HMAC', | ||
hash: { | ||
name: 'SHA-256', | ||
}, | ||
}; | ||
case 'HS384': | ||
return { | ||
name: 'HMAC', | ||
hash: { | ||
name: 'SHA-384', | ||
}, | ||
}; | ||
case 'HS512': | ||
return { | ||
name: 'HMAC', | ||
hash: { | ||
name: 'SHA-512', | ||
}, | ||
}; | ||
default: | ||
throw new types_2.JwtAlgorithmNotImplemented(name); | ||
} | ||
switch (name.toUpperCase()) { | ||
case "HS256": | ||
return { | ||
name: "HMAC", | ||
hash: { | ||
name: "SHA-256" | ||
} | ||
}; | ||
case "HS384": | ||
return { | ||
name: "HMAC", | ||
hash: { | ||
name: "SHA-384" | ||
} | ||
}; | ||
case "HS512": | ||
return { | ||
name: "HMAC", | ||
hash: { | ||
name: "SHA-512" | ||
} | ||
}; | ||
default: | ||
throw new import_types2.JwtAlgorithmNotImplemented(name); | ||
} | ||
}; | ||
const signing = async (data, secret, alg = types_1.AlgorithmTypes.HS256) => { | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.'); | ||
} | ||
const cryptoKey = await crypto.subtle.importKey(CryptoKeyFormat.RAW, (0, encode_1.utf8ToUint8Array)(secret), param(alg), false, [CryptoKeyUsage.Sign]); | ||
return await crypto.subtle.sign(param(alg), cryptoKey, (0, encode_1.utf8ToUint8Array)(data)); | ||
const signing = async (data, secret, alg = import_types.AlgorithmTypes.HS256) => { | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); | ||
} | ||
const cryptoKey = await crypto.subtle.importKey( | ||
"raw" /* RAW */, | ||
(0, import_encode.utf8ToUint8Array)(secret), | ||
param(alg), | ||
false, | ||
["sign" /* Sign */] | ||
); | ||
return await crypto.subtle.sign(param(alg), cryptoKey, (0, import_encode.utf8ToUint8Array)(data)); | ||
}; | ||
const sign = async (payload, secret, alg = types_1.AlgorithmTypes.HS256) => { | ||
const encodedPayload = await (0, encode_1.encodeBase64URL)(JSON.stringify(payload)); | ||
const encodedHeader = await (0, encode_1.encodeBase64URL)(JSON.stringify({ alg, typ: 'JWT' })); | ||
const partialToken = `${encodedHeader}.${encodedPayload}`; | ||
const signature = await (0, encode_1.arrayBufferToBase64URL)(await signing(partialToken, secret, alg)); | ||
return `${partialToken}.${signature}`; | ||
const sign = async (payload, secret, alg = import_types.AlgorithmTypes.HS256) => { | ||
const encodedPayload = await (0, import_encode.encodeBase64URL)(JSON.stringify(payload)); | ||
const encodedHeader = await (0, import_encode.encodeBase64URL)(JSON.stringify({ alg, typ: "JWT" })); | ||
const partialToken = `${encodedHeader}.${encodedPayload}`; | ||
const signature = await (0, import_encode.arrayBufferToBase64URL)(await signing(partialToken, secret, alg)); | ||
return `${partialToken}.${signature}`; | ||
}; | ||
exports.sign = sign; | ||
const verify = async (token, secret, alg = types_1.AlgorithmTypes.HS256) => { | ||
const tokenParts = token.split('.'); | ||
if (tokenParts.length !== 3) { | ||
throw new types_2.JwtTokenInvalid(token); | ||
} | ||
const { payload } = (0, exports.decode)(token); | ||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) { | ||
throw new types_2.JwtTokenNotBefore(token); | ||
} | ||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) { | ||
throw new types_2.JwtTokenExpired(token); | ||
} | ||
const signature = await (0, encode_1.arrayBufferToBase64URL)(await signing(tokenParts.slice(0, 2).join('.'), secret, alg)); | ||
if (signature !== tokenParts[2]) { | ||
throw new types_2.JwtTokenSignatureMismatched(token); | ||
} | ||
return true; | ||
const verify = async (token, secret, alg = import_types.AlgorithmTypes.HS256) => { | ||
const tokenParts = token.split("."); | ||
if (tokenParts.length !== 3) { | ||
throw new import_types2.JwtTokenInvalid(token); | ||
} | ||
const { payload } = decode(token); | ||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1e3)) { | ||
throw new import_types2.JwtTokenNotBefore(token); | ||
} | ||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1e3)) { | ||
throw new import_types2.JwtTokenExpired(token); | ||
} | ||
const signature = await (0, import_encode.arrayBufferToBase64URL)( | ||
await signing(tokenParts.slice(0, 2).join("."), secret, alg) | ||
); | ||
if (signature !== tokenParts[2]) { | ||
throw new import_types2.JwtTokenSignatureMismatched(token); | ||
} | ||
return true; | ||
}; | ||
exports.verify = verify; | ||
// eslint-disable-next-line | ||
const decode = (token) => { | ||
try { | ||
const [h, p] = token.split('.'); | ||
const header = JSON.parse((0, encode_1.decodeBase64URL)(h)); | ||
const payload = JSON.parse((0, encode_1.decodeBase64URL)(p)); | ||
return { | ||
header, | ||
payload, | ||
}; | ||
} | ||
catch (e) { | ||
throw new types_2.JwtTokenInvalid(token); | ||
} | ||
try { | ||
const [h, p] = token.split("."); | ||
const header = JSON.parse((0, import_encode.decodeBase64URL)(h)); | ||
const payload = JSON.parse((0, import_encode.decodeBase64URL)(p)); | ||
return { | ||
header, | ||
payload | ||
}; | ||
} catch (e) { | ||
throw new import_types2.JwtTokenInvalid(token); | ||
} | ||
}; | ||
exports.decode = decode; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
decode, | ||
sign, | ||
verify | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.AlgorithmTypes = exports.JwtTokenSignatureMismatched = exports.JwtTokenExpired = exports.JwtTokenNotBefore = exports.JwtTokenInvalid = exports.JwtAlorithmNotImplemented = exports.JwtAlgorithmNotImplemented = void 0; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var types_exports = {}; | ||
__export(types_exports, { | ||
AlgorithmTypes: () => AlgorithmTypes, | ||
JwtAlgorithmNotImplemented: () => JwtAlgorithmNotImplemented, | ||
JwtAlorithmNotImplemented: () => JwtAlorithmNotImplemented, | ||
JwtTokenExpired: () => JwtTokenExpired, | ||
JwtTokenInvalid: () => JwtTokenInvalid, | ||
JwtTokenNotBefore: () => JwtTokenNotBefore, | ||
JwtTokenSignatureMismatched: () => JwtTokenSignatureMismatched | ||
}); | ||
module.exports = __toCommonJS(types_exports); | ||
class JwtAlgorithmNotImplemented extends Error { | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = 'JwtAlgorithmNotImplemented'; | ||
} | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = "JwtAlgorithmNotImplemented"; | ||
} | ||
} | ||
exports.JwtAlgorithmNotImplemented = JwtAlgorithmNotImplemented; | ||
/** | ||
* Export for backward compatibility | ||
* @deprecated Use JwtAlgorithmNotImplemented instead | ||
**/ | ||
exports.JwtAlorithmNotImplemented = JwtAlgorithmNotImplemented; | ||
const JwtAlorithmNotImplemented = JwtAlgorithmNotImplemented; | ||
class JwtTokenInvalid extends Error { | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = 'JwtTokenInvalid'; | ||
} | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = "JwtTokenInvalid"; | ||
} | ||
} | ||
exports.JwtTokenInvalid = JwtTokenInvalid; | ||
class JwtTokenNotBefore extends Error { | ||
constructor(token) { | ||
super(`token (${token}) is being used before it's valid`); | ||
this.name = 'JwtTokenNotBefore'; | ||
} | ||
constructor(token) { | ||
super(`token (${token}) is being used before it's valid`); | ||
this.name = "JwtTokenNotBefore"; | ||
} | ||
} | ||
exports.JwtTokenNotBefore = JwtTokenNotBefore; | ||
class JwtTokenExpired extends Error { | ||
constructor(token) { | ||
super(`token (${token}) expired`); | ||
this.name = 'JwtTokenExpired'; | ||
} | ||
constructor(token) { | ||
super(`token (${token}) expired`); | ||
this.name = "JwtTokenExpired"; | ||
} | ||
} | ||
exports.JwtTokenExpired = JwtTokenExpired; | ||
class JwtTokenSignatureMismatched extends Error { | ||
constructor(token) { | ||
super(`token(${token}) signature mismatched`); | ||
this.name = 'JwtTokenSignatureMismatched'; | ||
} | ||
constructor(token) { | ||
super(`token(${token}) signature mismatched`); | ||
this.name = "JwtTokenSignatureMismatched"; | ||
} | ||
} | ||
exports.JwtTokenSignatureMismatched = JwtTokenSignatureMismatched; | ||
var AlgorithmTypes; | ||
(function (AlgorithmTypes) { | ||
AlgorithmTypes["HS256"] = "HS256"; | ||
AlgorithmTypes["HS384"] = "HS384"; | ||
AlgorithmTypes["HS512"] = "HS512"; | ||
})(AlgorithmTypes || (exports.AlgorithmTypes = AlgorithmTypes = {})); | ||
var AlgorithmTypes = /* @__PURE__ */ ((AlgorithmTypes2) => { | ||
AlgorithmTypes2["HS256"] = "HS256"; | ||
AlgorithmTypes2["HS384"] = "HS384"; | ||
AlgorithmTypes2["HS512"] = "HS512"; | ||
return AlgorithmTypes2; | ||
})(AlgorithmTypes || {}); | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
AlgorithmTypes, | ||
JwtAlgorithmNotImplemented, | ||
JwtAlorithmNotImplemented, | ||
JwtTokenExpired, | ||
JwtTokenInvalid, | ||
JwtTokenNotBefore, | ||
JwtTokenSignatureMismatched | ||
}); |
@@ -1,172 +0,171 @@ | ||
import { mergeSchemas } from '@graphql-tools/schema'; | ||
import { buildSchema, validateSchema, GraphQLObjectType, execute, GraphQLError } from 'graphql'; | ||
import { compose } from './compose'; | ||
import { Context } from './context/context'; | ||
export class EdgeQL { | ||
constructor() { | ||
this.schemas = []; | ||
this.middlewares = []; | ||
this.fetch = async (request, env, exeContext) => { | ||
if (request.method !== 'GET' && request.method !== 'POST') { | ||
return new Response('GraphQL only supports GET and POST requests.', { | ||
status: 405, | ||
}); | ||
// src/app.ts | ||
import { mergeSchemas } from "@graphql-tools/schema"; | ||
import { buildSchema, validateSchema, GraphQLObjectType, execute, GraphQLError } from "graphql"; | ||
import { compose } from "./compose.js"; | ||
import { Context } from "./context/context.js"; | ||
var EdgeQL = class { | ||
constructor() { | ||
this.schemas = []; | ||
this.middlewares = []; | ||
this.fetch = async (request, env, exeContext) => { | ||
if (request.method !== "GET" && request.method !== "POST") { | ||
return new Response("GraphQL only supports GET and POST requests.", { | ||
status: 405 | ||
}); | ||
} | ||
let ctx; | ||
try { | ||
ctx = new Context(request, env, exeContext); | ||
} catch (e) { | ||
return new Response( | ||
JSON.stringify({ | ||
data: null, | ||
errors: [ | ||
new GraphQLError(`GraphQL params error: ${e}`, { | ||
extensions: { | ||
status: 400 | ||
} | ||
}) | ||
] | ||
}) | ||
); | ||
} | ||
await ctx.graphql.init(ctx.http.request); | ||
ctx.graphql.schema = this.graph; | ||
await compose([...this.middlewares, this.execute])(ctx); | ||
return ctx.json(); | ||
}; | ||
} | ||
async execute(ctx) { | ||
if (!ctx.graphql.query) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError("Must provide query string", { | ||
extensions: { | ||
status: 400 | ||
} | ||
let ctx; | ||
try { | ||
ctx = new Context(request, env, exeContext); | ||
}) | ||
] | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.document) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError(`could not generate document from query: ${ctx.graphql.query}`, { | ||
extensions: { | ||
status: 400 | ||
} | ||
catch (e) { | ||
return new Response(JSON.stringify({ | ||
data: null, | ||
errors: [ | ||
new GraphQLError(`GraphQL params error: ${e}`, { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
})); | ||
}) | ||
] | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.schema) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError("no schem registerred yet", { | ||
extensions: { | ||
status: 400 | ||
} | ||
await ctx.graphql.init(ctx.http.request); | ||
ctx.graphql.schema = this.graph; | ||
await compose([...this.middlewares, this.execute])(ctx); | ||
return ctx.json(); | ||
}; | ||
}) | ||
] | ||
}; | ||
return; | ||
} | ||
async execute(ctx) { | ||
if (!ctx.graphql.query) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError('Must provide query string', { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.document) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError(`could not generate document from query: ${ctx.graphql.query}`, { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
}; | ||
return; | ||
} | ||
if (!ctx.graphql.schema) { | ||
ctx.http.status = 400; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError('no schem registerred yet', { | ||
extensions: { | ||
status: 400, | ||
}, | ||
}), | ||
], | ||
}; | ||
return; | ||
} | ||
try { | ||
const res = await execute({ | ||
schema: ctx.graphql.schema, | ||
document: ctx.graphql.document ?? null, | ||
rootValue: null, | ||
contextValue: ctx, | ||
variableValues: ctx.graphql.variables, | ||
operationName: ctx.graphql.operationName, | ||
}); | ||
ctx.http.status = 200; | ||
ctx.http.body = res; | ||
return; | ||
} | ||
catch (contextError) { | ||
ctx.http.status = 500; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError(`GraphQL execution context error: ${contextError}`, { | ||
extensions: { | ||
status: 500, | ||
}, | ||
}), | ||
], | ||
}; | ||
} | ||
try { | ||
const res = await execute({ | ||
schema: ctx.graphql.schema, | ||
document: ctx.graphql.document ?? null, | ||
rootValue: null, | ||
contextValue: ctx, | ||
variableValues: ctx.graphql.variables, | ||
operationName: ctx.graphql.operationName | ||
}); | ||
ctx.http.status = 200; | ||
ctx.http.body = res; | ||
return; | ||
} catch (contextError) { | ||
ctx.http.status = 500; | ||
ctx.http.body = { | ||
data: null, | ||
errors: [ | ||
new GraphQLError(`GraphQL execution context error: ${contextError}`, { | ||
extensions: { | ||
status: 500 | ||
} | ||
}) | ||
] | ||
}; | ||
} | ||
use(fn) { | ||
this.middlewares.push(fn); | ||
} | ||
handle(...args) { | ||
if (args.length === 1 && typeof args[0] === 'object') { | ||
const schemaValidationErrors = validateSchema(args[0]); | ||
if (schemaValidationErrors.length > 0) { | ||
throw new Error(`Invalid schema: ${args[0]}`); | ||
} | ||
this.schemas.push(args[0]); | ||
} | ||
use(fn) { | ||
this.middlewares.push(fn); | ||
} | ||
handle(...args) { | ||
if (args.length === 1 && typeof args[0] === "object") { | ||
const schemaValidationErrors = validateSchema(args[0]); | ||
if (schemaValidationErrors.length > 0) { | ||
throw new Error(`Invalid schema: ${args[0]}`); | ||
} | ||
this.schemas.push(args[0]); | ||
} else if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "function") { | ||
const s = buildSchema(args[0]); | ||
const typs = ["Query", "Mutation", "Subscription"]; | ||
const fields = []; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
fields.push(obj.getFields()[f]); | ||
} | ||
} | ||
else if (args.length === 2 && typeof args[0] === 'string' && typeof args[1] === 'function') { | ||
const s = buildSchema(args[0]); | ||
const typs = ['Query', 'Mutation', 'Subscription']; | ||
const fields = []; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
fields.push(obj.getFields()[f]); | ||
} | ||
} | ||
} | ||
if (fields.length !== 1) { | ||
throw new Error("only one of Query, Mutation, Subscription is allowed"); | ||
} else { | ||
fields[0].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.args = arg; | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.info = info; | ||
return await args[1](ctx); | ||
}; | ||
} | ||
this.schemas.push(s); | ||
} else if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "object") { | ||
const s = buildSchema(args[0]); | ||
const typs = ["Query", "Mutation", "Subscription"]; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
if (args[1][f]) { | ||
obj.getFields()[f].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.args = arg; | ||
ctx.graphql.info = info; | ||
const fn = args[1][f]; | ||
return await fn(ctx); | ||
}; | ||
} else { | ||
throw new Error(`no resolve function for ${obj.getFields()[f]}`); | ||
} | ||
if (fields.length !== 1) { | ||
throw new Error('only one of Query, Mutation, Subscription is allowed'); | ||
} | ||
else { | ||
fields[0].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.args = arg; | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.info = info; | ||
return await args[1](ctx); | ||
}; | ||
} | ||
this.schemas.push(s); | ||
} | ||
} | ||
else if (args.length === 2 && typeof args[0] === 'string' && typeof args[1] === 'object') { | ||
const s = buildSchema(args[0]); | ||
const typs = ['Query', 'Mutation', 'Subscription']; | ||
for (const t of typs) { | ||
const obj = s.getTypeMap()[t]; | ||
if (obj instanceof GraphQLObjectType) { | ||
for (const f of Object.keys(obj.getFields())) { | ||
if (args[1][f]) { | ||
obj.getFields()[f].resolve = async (parents, arg, ctx, info) => { | ||
ctx.graphql.parents = parents; | ||
ctx.graphql.args = arg; | ||
ctx.graphql.info = info; | ||
const fn = args[1][f]; | ||
return await fn(ctx); | ||
}; | ||
} | ||
else { | ||
throw new Error(`no resolve function for ${obj.getFields()[f]}`); | ||
} | ||
} | ||
} | ||
} | ||
this.schemas.push(s); | ||
} | ||
else { | ||
throw new Error('invalid of parameters for register'); | ||
} | ||
this.graph = mergeSchemas({ schemas: this.schemas ?? [] }); | ||
} | ||
this.schemas.push(s); | ||
} else { | ||
throw new Error("invalid of parameters for register"); | ||
} | ||
} | ||
this.graph = mergeSchemas({ schemas: this.schemas ?? [] }); | ||
} | ||
}; | ||
export { | ||
EdgeQL | ||
}; |
@@ -1,34 +0,36 @@ | ||
export function compose(middleware) { | ||
for (const fn of middleware) { | ||
if (typeof fn !== 'function') { | ||
throw new TypeError('Middleware must be composed of functions!'); | ||
} | ||
// src/compose.ts | ||
function compose(middleware) { | ||
for (const fn of middleware) { | ||
if (typeof fn !== "function") { | ||
throw new TypeError("Middleware must be composed of functions!"); | ||
} | ||
return (context, next) => { | ||
// last called middleware # | ||
let index = -1; | ||
return dispatch(0); | ||
function dispatch(i) { | ||
if (i <= index) { | ||
return Promise.reject(new Error('next() called multiple times')); | ||
} | ||
index = i; | ||
let fn = middleware[i]; | ||
if (i === middleware.length && next) { | ||
fn = next; | ||
} | ||
if (!fn) { | ||
return Promise.resolve(); | ||
} | ||
try { | ||
const ctx = fn(context, async () => { | ||
await dispatch(i + 1); | ||
}); | ||
return Promise.resolve(ctx); | ||
} | ||
catch (err) { | ||
return Promise.reject(err); | ||
} | ||
} | ||
}; | ||
} | ||
return (context, next) => { | ||
let index = -1; | ||
return dispatch(0); | ||
function dispatch(i) { | ||
if (i <= index) { | ||
return Promise.reject(new Error("next() called multiple times")); | ||
} | ||
index = i; | ||
let fn = middleware[i]; | ||
if (i === middleware.length && next) { | ||
fn = next; | ||
} | ||
if (!fn) { | ||
return Promise.resolve(); | ||
} | ||
try { | ||
const ctx = fn(context, async () => { | ||
await dispatch(i + 1); | ||
}); | ||
return Promise.resolve(ctx); | ||
} catch (err) { | ||
return Promise.reject(err); | ||
} | ||
} | ||
}; | ||
} | ||
export { | ||
compose | ||
}; |
@@ -1,23 +0,27 @@ | ||
import { GraphQLContext } from './graphql'; | ||
import { HttpContext } from './http'; | ||
import { RuntimeContext } from './runtime'; | ||
export class Context { | ||
constructor(request, env, exeContext) { | ||
this.runtime = new RuntimeContext(env, exeContext); | ||
this.http = new HttpContext(request); | ||
this.graphql = new GraphQLContext(); | ||
// src/context/context.ts | ||
import { GraphQLContext } from "./graphql.js"; | ||
import { HttpContext } from "./http.js"; | ||
import { RuntimeContext } from "./runtime.js"; | ||
var Context = class { | ||
constructor(request, env, exeContext) { | ||
this.runtime = new RuntimeContext(env, exeContext); | ||
this.http = new HttpContext(request); | ||
this.graphql = new GraphQLContext(); | ||
} | ||
json() { | ||
return this.http.toJSON(); | ||
} | ||
set(key, value) { | ||
this._map || (this._map = {}); | ||
this._map[key] = value; | ||
} | ||
get(key) { | ||
if (!this._map) { | ||
return void 0; | ||
} | ||
json() { | ||
return this.http.toJSON(); | ||
} | ||
set(key, value) { | ||
this._map || (this._map = {}); | ||
this._map[key] = value; | ||
} | ||
get(key) { | ||
if (!this._map) { | ||
return undefined; | ||
} | ||
return this._map[key]; | ||
} | ||
} | ||
return this._map[key]; | ||
} | ||
}; | ||
export { | ||
Context | ||
}; |
@@ -1,94 +0,96 @@ | ||
import { parse } from 'graphql'; | ||
export class GraphQLContext { | ||
async init(request) { | ||
const contentType = request.headers.get('content-type'); | ||
switch (contentType) { | ||
case 'application/graphql': { | ||
const query = await request.text(); | ||
this.query = query; | ||
break; | ||
} | ||
case 'application/json': { | ||
const { query, operationName, variables, extensions } = (await request.json()); | ||
this.query = query; | ||
this.variables = variables; | ||
this.operationName = operationName; | ||
this.extensions = extensions; | ||
break; | ||
} | ||
case 'application/x-www-form-urlencoded': { | ||
const text = await request.text(); | ||
const searchParams = new URLSearchParams(text); | ||
searchParams.forEach((v, k) => { | ||
if (k === 'query') { | ||
this.query = v; | ||
} | ||
else if (k === 'variables') { | ||
this.variables = JSON.parse(v); | ||
} | ||
else if (k === 'operationName') { | ||
this.operationName = v; | ||
} | ||
}); | ||
break; | ||
} | ||
} | ||
if (this.query) { | ||
this.document = parse(this.query); | ||
} | ||
// src/context/graphql.ts | ||
import { parse } from "graphql"; | ||
var GraphQLContext = class { | ||
async init(request) { | ||
const contentType = request.headers.get("content-type"); | ||
switch (contentType) { | ||
case "application/graphql": { | ||
const query = await request.text(); | ||
this.query = query; | ||
break; | ||
} | ||
case "application/json": { | ||
const { query, operationName, variables, extensions } = await request.json(); | ||
this.query = query; | ||
this.variables = variables; | ||
this.operationName = operationName; | ||
this.extensions = extensions; | ||
break; | ||
} | ||
case "application/x-www-form-urlencoded": { | ||
const text = await request.text(); | ||
const searchParams = new URLSearchParams(text); | ||
searchParams.forEach((v, k) => { | ||
if (k === "query") { | ||
this.query = v; | ||
} else if (k === "variables") { | ||
this.variables = JSON.parse(v); | ||
} else if (k === "operationName") { | ||
this.operationName = v; | ||
} | ||
}); | ||
break; | ||
} | ||
} | ||
set query(query) { | ||
this._query = query; | ||
if (this.query) { | ||
this.document = parse(this.query); | ||
} | ||
get query() { | ||
return this._query; | ||
} | ||
set operationName(operationName) { | ||
this._operationName = operationName; | ||
} | ||
get operationName() { | ||
return this._operationName; | ||
} | ||
set variables(variables) { | ||
this._variables = variables; | ||
} | ||
get variables() { | ||
return this._variables; | ||
} | ||
set extensions(extensions) { | ||
this._extensions = extensions; | ||
} | ||
get extensions() { | ||
return this._extensions; | ||
} | ||
set parents(value) { | ||
this._parents = value; | ||
} | ||
get parents() { | ||
return this._parents; | ||
} | ||
set args(value) { | ||
this._args = value; | ||
} | ||
get args() { | ||
return this._args; | ||
} | ||
set info(value) { | ||
this._info = value; | ||
} | ||
get info() { | ||
return this._info; | ||
} | ||
set document(document) { | ||
this._document = document; | ||
} | ||
get document() { | ||
return this._document; | ||
} | ||
get schema() { | ||
return this._schema; | ||
} | ||
set schema(schema) { | ||
this._schema = schema; | ||
} | ||
} | ||
} | ||
set query(query) { | ||
this._query = query; | ||
} | ||
get query() { | ||
return this._query; | ||
} | ||
set operationName(operationName) { | ||
this._operationName = operationName; | ||
} | ||
get operationName() { | ||
return this._operationName; | ||
} | ||
set variables(variables) { | ||
this._variables = variables; | ||
} | ||
get variables() { | ||
return this._variables; | ||
} | ||
set extensions(extensions) { | ||
this._extensions = extensions; | ||
} | ||
get extensions() { | ||
return this._extensions; | ||
} | ||
set parents(value) { | ||
this._parents = value; | ||
} | ||
get parents() { | ||
return this._parents; | ||
} | ||
set args(value) { | ||
this._args = value; | ||
} | ||
get args() { | ||
return this._args; | ||
} | ||
set info(value) { | ||
this._info = value; | ||
} | ||
get info() { | ||
return this._info; | ||
} | ||
set document(document) { | ||
this._document = document; | ||
} | ||
get document() { | ||
return this._document; | ||
} | ||
get schema() { | ||
return this._schema; | ||
} | ||
set schema(schema) { | ||
this._schema = schema; | ||
} | ||
}; | ||
export { | ||
GraphQLContext | ||
}; |
@@ -1,41 +0,45 @@ | ||
export class HttpContext { | ||
constructor(request) { | ||
this._headers = new Headers(); | ||
this.request = request; | ||
} | ||
toJSON() { | ||
this.headers.set('content-type', 'application/json'); | ||
return new Response(JSON.stringify(this.body), { | ||
status: this.status ?? 200, | ||
statusText: this.statusText ?? '', | ||
headers: this.headers, | ||
}); | ||
} | ||
toText() { | ||
return new Response(this.body, { | ||
status: this.status ?? 200, | ||
headers: this.headers, | ||
}); | ||
} | ||
set status(status) { | ||
this._status = status; | ||
} | ||
get status() { | ||
return this._status; | ||
} | ||
set statusText(text) { | ||
this._statusText = text; | ||
} | ||
get statusText() { | ||
return this._statusText; | ||
} | ||
get headers() { | ||
return this._headers; | ||
} | ||
set body(body) { | ||
this._body = body; | ||
} | ||
get body() { | ||
return this._body; | ||
} | ||
} | ||
// src/context/http.ts | ||
var HttpContext = class { | ||
constructor(request) { | ||
this._headers = new Headers(); | ||
this.request = request; | ||
} | ||
toJSON() { | ||
this.headers.set("content-type", "application/json"); | ||
return new Response(JSON.stringify(this.body), { | ||
status: this.status ?? 200, | ||
statusText: this.statusText ?? "", | ||
headers: this.headers | ||
}); | ||
} | ||
toText() { | ||
return new Response(this.body, { | ||
status: this.status ?? 200, | ||
headers: this.headers | ||
}); | ||
} | ||
set status(status) { | ||
this._status = status; | ||
} | ||
get status() { | ||
return this._status; | ||
} | ||
set statusText(text) { | ||
this._statusText = text; | ||
} | ||
get statusText() { | ||
return this._statusText; | ||
} | ||
get headers() { | ||
return this._headers; | ||
} | ||
set body(body) { | ||
this._body = body; | ||
} | ||
get body() { | ||
return this._body; | ||
} | ||
}; | ||
export { | ||
HttpContext | ||
}; |
@@ -1,6 +0,10 @@ | ||
export class RuntimeContext { | ||
constructor(env, exeContext) { | ||
this.env = env; | ||
this.exeContext = exeContext; | ||
} | ||
} | ||
// src/context/runtime.ts | ||
var RuntimeContext = class { | ||
constructor(env, exeContext) { | ||
this.env = env; | ||
this.exeContext = exeContext; | ||
} | ||
}; | ||
export { | ||
RuntimeContext | ||
}; |
@@ -1,2 +0,7 @@ | ||
export { EdgeQL } from './app'; | ||
export { Context } from './context/context'; | ||
// src/index.ts | ||
import { EdgeQL } from "./app.js"; | ||
import { Context } from "./context/context.js"; | ||
export { | ||
Context, | ||
EdgeQL | ||
}; |
@@ -1,46 +0,57 @@ | ||
import { Jwt } from '../../utils/jwt'; | ||
export const jwt = (options) => { | ||
if (!options) { | ||
throw new Error('JWT auth middleware requires options for "secret'); | ||
// src/middleware/jwt/index.ts | ||
import { Jwt } from "../../utils/jwt/index.js"; | ||
var jwt = (options) => { | ||
if (!options) { | ||
throw new Error('JWT auth middleware requires options for "secret'); | ||
} | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); | ||
} | ||
return async (ctx, next) => { | ||
const credentials = ctx.http.request.headers.get("Authorization"); | ||
let token; | ||
if (credentials) { | ||
const parts = credentials.split(/\s+/); | ||
if (parts.length !== 2) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = "Unauthorized"; | ||
ctx.http.headers.set( | ||
"WWW-Authenticate", | ||
`Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="invalid credentials structure"` | ||
); | ||
return; | ||
} else { | ||
token = parts[1]; | ||
} | ||
} | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.'); | ||
if (!token) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = "Unauthorized"; | ||
ctx.http.headers.set( | ||
"WWW-Authenticate", | ||
`Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="no authorization included in request"` | ||
); | ||
return; | ||
} | ||
return async (ctx, next) => { | ||
const credentials = ctx.http.request.headers.get('Authorization'); | ||
let token; | ||
if (credentials) { | ||
const parts = credentials.split(/\s+/); | ||
if (parts.length !== 2) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = 'Unauthorized'; | ||
ctx.http.headers.set('WWW-Authenticate', `Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="invalid credentials structure"`); | ||
return; | ||
} | ||
else { | ||
token = parts[1]; | ||
} | ||
} | ||
if (!token) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = 'Unauthorized'; | ||
ctx.http.headers.set('WWW-Authenticate', `Bearer realm="${ctx.http.request.url}",error="invalid_request",error_description="no authorization included in request"`); | ||
return; | ||
} | ||
let authorized = false; | ||
let msg = ''; | ||
try { | ||
authorized = await Jwt.verify(token, options.secret, options.alg); | ||
} | ||
catch (e) { | ||
msg = `${e}`; | ||
} | ||
if (!authorized) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = msg; | ||
ctx.http.headers.set('WWW-Authenticate', `Bearer realm="${ctx.http.request.url}",error="invalid_token",error_description="token verification failure"`); | ||
return; | ||
} | ||
await next(); | ||
}; | ||
let authorized = false; | ||
let msg = ""; | ||
try { | ||
authorized = await Jwt.verify(token, options.secret, options.alg); | ||
} catch (e) { | ||
msg = `${e}`; | ||
} | ||
if (!authorized) { | ||
ctx.http.status = 401; | ||
ctx.http.statusText = msg; | ||
ctx.http.headers.set( | ||
"WWW-Authenticate", | ||
`Bearer realm="${ctx.http.request.url}",error="invalid_token",error_description="token verification failure"` | ||
); | ||
return; | ||
} | ||
await next(); | ||
}; | ||
}; | ||
export { | ||
jwt | ||
}; |
@@ -1,6 +0,10 @@ | ||
export const wallclock = async (ctx, next) => { | ||
const startedAt = new Date(); | ||
await next(); | ||
const endedAt = new Date(); | ||
ctx.http.headers.set('x-edgeql-wallclock', `${endedAt.getTime() - startedAt.getTime()}`); | ||
// src/middleware/wallclock/index.ts | ||
var wallclock = async (ctx, next) => { | ||
const startedAt = new Date(); | ||
await next(); | ||
const endedAt = new Date(); | ||
ctx.http.headers.set("x-edgeql-wallclock", `${endedAt.getTime() - startedAt.getTime()}`); | ||
}; | ||
export { | ||
wallclock | ||
}; |
@@ -1,70 +0,78 @@ | ||
export const encodeBase64 = (str) => { | ||
if (str === null) { | ||
throw new TypeError('1st argument of "encodeBase64" should not be null.'); | ||
} | ||
try { | ||
const encoder = new TextEncoder(); | ||
const bytes = encoder.encode(str); | ||
return btoa(String.fromCharCode(...bytes)); | ||
} | ||
catch { } | ||
try { | ||
return Buffer.from(str).toString('base64'); | ||
} | ||
catch (e) { | ||
console.error('If you want to do "encodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
// src/utils/encode.ts | ||
var encodeBase64 = (str) => { | ||
if (str === null) { | ||
throw new TypeError('1st argument of "encodeBase64" should not be null.'); | ||
} | ||
try { | ||
const encoder = new TextEncoder(); | ||
const bytes = encoder.encode(str); | ||
return btoa(String.fromCharCode(...bytes)); | ||
} catch { | ||
} | ||
try { | ||
return Buffer.from(str).toString("base64"); | ||
} catch (e) { | ||
console.error('If you want to do "encodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
}; | ||
export const decodeBase64 = (str) => { | ||
if (str === null) { | ||
throw new TypeError('1st argument of "decodeBase64" should not be null.'); | ||
var decodeBase64 = (str) => { | ||
if (str === null) { | ||
throw new TypeError('1st argument of "decodeBase64" should not be null.'); | ||
} | ||
try { | ||
const text = atob(str); | ||
const bytes = new Uint8Array(text.split("").map((c) => c.charCodeAt(0))); | ||
const decoder = new TextDecoder(); | ||
return decoder.decode(bytes); | ||
} catch { | ||
} | ||
try { | ||
return Buffer.from(str, "base64").toString(); | ||
} catch (e) { | ||
console.error('If you want to do "decodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
}; | ||
var encodeBase64URL = (str) => { | ||
return encodeBase64(str).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); | ||
}; | ||
var decodeBase64URL = (str) => { | ||
const pad = (s) => { | ||
const diff = s.length % 4; | ||
if (diff === 2) { | ||
return `${s}==`; | ||
} | ||
try { | ||
const text = atob(str); | ||
const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0))); | ||
const decoder = new TextDecoder(); | ||
return decoder.decode(bytes); | ||
if (diff === 3) { | ||
return `${s}=`; | ||
} | ||
catch { } | ||
try { | ||
return Buffer.from(str, 'base64').toString(); | ||
} | ||
catch (e) { | ||
console.error('If you want to do "decodeBase64", polyfill "buffer" module.'); | ||
throw e; | ||
} | ||
return s; | ||
}; | ||
return decodeBase64(pad(str).replace(/-/g, "+").replace("_", "/")); | ||
}; | ||
export const encodeBase64URL = (str) => { | ||
return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); | ||
var utf8ToUint8Array = (str) => { | ||
const encoder = new TextEncoder(); | ||
return encoder.encode(str); | ||
}; | ||
export const decodeBase64URL = (str) => { | ||
const pad = (s) => { | ||
const diff = s.length % 4; | ||
if (diff === 2) { | ||
return `${s}==`; | ||
} | ||
if (diff === 3) { | ||
return `${s}=`; | ||
} | ||
return s; | ||
}; | ||
return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/')); | ||
var arrayBufferToBase64 = async (buf) => { | ||
if (typeof btoa === "function") { | ||
return btoa(String.fromCharCode(...new Uint8Array(buf))); | ||
} | ||
try { | ||
return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString("base64"); | ||
} catch (e) { | ||
} | ||
return ""; | ||
}; | ||
export const utf8ToUint8Array = (str) => { | ||
const encoder = new TextEncoder(); | ||
return encoder.encode(str); | ||
var arrayBufferToBase64URL = async (buf) => { | ||
return (await arrayBufferToBase64(buf)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); | ||
}; | ||
export const arrayBufferToBase64 = async (buf) => { | ||
if (typeof btoa === 'function') { | ||
return btoa(String.fromCharCode(...new Uint8Array(buf))); | ||
} | ||
try { | ||
return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64'); | ||
} | ||
catch (e) { } | ||
return ''; | ||
export { | ||
arrayBufferToBase64, | ||
arrayBufferToBase64URL, | ||
decodeBase64, | ||
decodeBase64URL, | ||
encodeBase64, | ||
encodeBase64URL, | ||
utf8ToUint8Array | ||
}; | ||
export const arrayBufferToBase64URL = async (buf) => { | ||
return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); | ||
}; |
@@ -1,1 +0,5 @@ | ||
export * as Jwt from './jwt'; | ||
// src/utils/jwt/index.ts | ||
import * as Jwt from "./jwt.js"; | ||
export { | ||
Jwt | ||
}; |
@@ -1,95 +0,100 @@ | ||
import { utf8ToUint8Array, encodeBase64URL, arrayBufferToBase64URL, decodeBase64URL, } from '../../utils/encode'; | ||
import { AlgorithmTypes } from './types'; | ||
import { JwtTokenInvalid, JwtTokenNotBefore, JwtTokenExpired, JwtTokenSignatureMismatched, JwtAlgorithmNotImplemented, } from './types'; | ||
var CryptoKeyFormat; | ||
(function (CryptoKeyFormat) { | ||
CryptoKeyFormat["RAW"] = "raw"; | ||
CryptoKeyFormat["PKCS8"] = "pkcs8"; | ||
CryptoKeyFormat["SPKI"] = "spki"; | ||
CryptoKeyFormat["JWK"] = "jwk"; | ||
})(CryptoKeyFormat || (CryptoKeyFormat = {})); | ||
var CryptoKeyUsage; | ||
(function (CryptoKeyUsage) { | ||
CryptoKeyUsage["Ecrypt"] = "encrypt"; | ||
CryptoKeyUsage["Decrypt"] = "decrypt"; | ||
CryptoKeyUsage["Sign"] = "sign"; | ||
CryptoKeyUsage["Verify"] = "verify"; | ||
CryptoKeyUsage["Deriverkey"] = "deriveKey"; | ||
CryptoKeyUsage["DeriveBits"] = "deriveBits"; | ||
CryptoKeyUsage["WrapKey"] = "wrapKey"; | ||
CryptoKeyUsage["UnwrapKey"] = "unwrapKey"; | ||
})(CryptoKeyUsage || (CryptoKeyUsage = {})); | ||
const param = (name) => { | ||
switch (name.toUpperCase()) { | ||
case 'HS256': | ||
return { | ||
name: 'HMAC', | ||
hash: { | ||
name: 'SHA-256', | ||
}, | ||
}; | ||
case 'HS384': | ||
return { | ||
name: 'HMAC', | ||
hash: { | ||
name: 'SHA-384', | ||
}, | ||
}; | ||
case 'HS512': | ||
return { | ||
name: 'HMAC', | ||
hash: { | ||
name: 'SHA-512', | ||
}, | ||
}; | ||
default: | ||
throw new JwtAlgorithmNotImplemented(name); | ||
} | ||
// src/utils/jwt/jwt.ts | ||
import { | ||
utf8ToUint8Array, | ||
encodeBase64URL, | ||
arrayBufferToBase64URL, | ||
decodeBase64URL | ||
} from "../../utils/encode.js"; | ||
import { AlgorithmTypes } from "./types.js"; | ||
import { | ||
JwtTokenInvalid, | ||
JwtTokenNotBefore, | ||
JwtTokenExpired, | ||
JwtTokenSignatureMismatched, | ||
JwtAlgorithmNotImplemented | ||
} from "./types.js"; | ||
var param = (name) => { | ||
switch (name.toUpperCase()) { | ||
case "HS256": | ||
return { | ||
name: "HMAC", | ||
hash: { | ||
name: "SHA-256" | ||
} | ||
}; | ||
case "HS384": | ||
return { | ||
name: "HMAC", | ||
hash: { | ||
name: "SHA-384" | ||
} | ||
}; | ||
case "HS512": | ||
return { | ||
name: "HMAC", | ||
hash: { | ||
name: "SHA-512" | ||
} | ||
}; | ||
default: | ||
throw new JwtAlgorithmNotImplemented(name); | ||
} | ||
}; | ||
const signing = async (data, secret, alg = AlgorithmTypes.HS256) => { | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.'); | ||
} | ||
const cryptoKey = await crypto.subtle.importKey(CryptoKeyFormat.RAW, utf8ToUint8Array(secret), param(alg), false, [CryptoKeyUsage.Sign]); | ||
return await crypto.subtle.sign(param(alg), cryptoKey, utf8ToUint8Array(data)); | ||
var signing = async (data, secret, alg = AlgorithmTypes.HS256) => { | ||
if (!crypto.subtle || !crypto.subtle.importKey) { | ||
throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); | ||
} | ||
const cryptoKey = await crypto.subtle.importKey( | ||
"raw" /* RAW */, | ||
utf8ToUint8Array(secret), | ||
param(alg), | ||
false, | ||
["sign" /* Sign */] | ||
); | ||
return await crypto.subtle.sign(param(alg), cryptoKey, utf8ToUint8Array(data)); | ||
}; | ||
export const sign = async (payload, secret, alg = AlgorithmTypes.HS256) => { | ||
const encodedPayload = await encodeBase64URL(JSON.stringify(payload)); | ||
const encodedHeader = await encodeBase64URL(JSON.stringify({ alg, typ: 'JWT' })); | ||
const partialToken = `${encodedHeader}.${encodedPayload}`; | ||
const signature = await arrayBufferToBase64URL(await signing(partialToken, secret, alg)); | ||
return `${partialToken}.${signature}`; | ||
var sign = async (payload, secret, alg = AlgorithmTypes.HS256) => { | ||
const encodedPayload = await encodeBase64URL(JSON.stringify(payload)); | ||
const encodedHeader = await encodeBase64URL(JSON.stringify({ alg, typ: "JWT" })); | ||
const partialToken = `${encodedHeader}.${encodedPayload}`; | ||
const signature = await arrayBufferToBase64URL(await signing(partialToken, secret, alg)); | ||
return `${partialToken}.${signature}`; | ||
}; | ||
export const verify = async (token, secret, alg = AlgorithmTypes.HS256) => { | ||
const tokenParts = token.split('.'); | ||
if (tokenParts.length !== 3) { | ||
throw new JwtTokenInvalid(token); | ||
} | ||
const { payload } = decode(token); | ||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) { | ||
throw new JwtTokenNotBefore(token); | ||
} | ||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) { | ||
throw new JwtTokenExpired(token); | ||
} | ||
const signature = await arrayBufferToBase64URL(await signing(tokenParts.slice(0, 2).join('.'), secret, alg)); | ||
if (signature !== tokenParts[2]) { | ||
throw new JwtTokenSignatureMismatched(token); | ||
} | ||
return true; | ||
var verify = async (token, secret, alg = AlgorithmTypes.HS256) => { | ||
const tokenParts = token.split("."); | ||
if (tokenParts.length !== 3) { | ||
throw new JwtTokenInvalid(token); | ||
} | ||
const { payload } = decode(token); | ||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1e3)) { | ||
throw new JwtTokenNotBefore(token); | ||
} | ||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1e3)) { | ||
throw new JwtTokenExpired(token); | ||
} | ||
const signature = await arrayBufferToBase64URL( | ||
await signing(tokenParts.slice(0, 2).join("."), secret, alg) | ||
); | ||
if (signature !== tokenParts[2]) { | ||
throw new JwtTokenSignatureMismatched(token); | ||
} | ||
return true; | ||
}; | ||
// eslint-disable-next-line | ||
export const decode = (token) => { | ||
try { | ||
const [h, p] = token.split('.'); | ||
const header = JSON.parse(decodeBase64URL(h)); | ||
const payload = JSON.parse(decodeBase64URL(p)); | ||
return { | ||
header, | ||
payload, | ||
}; | ||
} | ||
catch (e) { | ||
throw new JwtTokenInvalid(token); | ||
} | ||
var decode = (token) => { | ||
try { | ||
const [h, p] = token.split("."); | ||
const header = JSON.parse(decodeBase64URL(h)); | ||
const payload = JSON.parse(decodeBase64URL(p)); | ||
return { | ||
header, | ||
payload | ||
}; | ||
} catch (e) { | ||
throw new JwtTokenInvalid(token); | ||
} | ||
}; | ||
export { | ||
decode, | ||
sign, | ||
verify | ||
}; |
@@ -1,41 +0,47 @@ | ||
export class JwtAlgorithmNotImplemented extends Error { | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = 'JwtAlgorithmNotImplemented'; | ||
} | ||
} | ||
/** | ||
* Export for backward compatibility | ||
* @deprecated Use JwtAlgorithmNotImplemented instead | ||
**/ | ||
export const JwtAlorithmNotImplemented = JwtAlgorithmNotImplemented; | ||
export class JwtTokenInvalid extends Error { | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = 'JwtTokenInvalid'; | ||
} | ||
} | ||
export class JwtTokenNotBefore extends Error { | ||
constructor(token) { | ||
super(`token (${token}) is being used before it's valid`); | ||
this.name = 'JwtTokenNotBefore'; | ||
} | ||
} | ||
export class JwtTokenExpired extends Error { | ||
constructor(token) { | ||
super(`token (${token}) expired`); | ||
this.name = 'JwtTokenExpired'; | ||
} | ||
} | ||
export class JwtTokenSignatureMismatched extends Error { | ||
constructor(token) { | ||
super(`token(${token}) signature mismatched`); | ||
this.name = 'JwtTokenSignatureMismatched'; | ||
} | ||
} | ||
export var AlgorithmTypes; | ||
(function (AlgorithmTypes) { | ||
AlgorithmTypes["HS256"] = "HS256"; | ||
AlgorithmTypes["HS384"] = "HS384"; | ||
AlgorithmTypes["HS512"] = "HS512"; | ||
})(AlgorithmTypes || (AlgorithmTypes = {})); | ||
// src/utils/jwt/types.ts | ||
var JwtAlgorithmNotImplemented = class extends Error { | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = "JwtAlgorithmNotImplemented"; | ||
} | ||
}; | ||
var JwtAlorithmNotImplemented = JwtAlgorithmNotImplemented; | ||
var JwtTokenInvalid = class extends Error { | ||
constructor(token) { | ||
super(`invalid JWT token: ${token}`); | ||
this.name = "JwtTokenInvalid"; | ||
} | ||
}; | ||
var JwtTokenNotBefore = class extends Error { | ||
constructor(token) { | ||
super(`token (${token}) is being used before it's valid`); | ||
this.name = "JwtTokenNotBefore"; | ||
} | ||
}; | ||
var JwtTokenExpired = class extends Error { | ||
constructor(token) { | ||
super(`token (${token}) expired`); | ||
this.name = "JwtTokenExpired"; | ||
} | ||
}; | ||
var JwtTokenSignatureMismatched = class extends Error { | ||
constructor(token) { | ||
super(`token(${token}) signature mismatched`); | ||
this.name = "JwtTokenSignatureMismatched"; | ||
} | ||
}; | ||
var AlgorithmTypes = /* @__PURE__ */ ((AlgorithmTypes2) => { | ||
AlgorithmTypes2["HS256"] = "HS256"; | ||
AlgorithmTypes2["HS384"] = "HS384"; | ||
AlgorithmTypes2["HS512"] = "HS512"; | ||
return AlgorithmTypes2; | ||
})(AlgorithmTypes || {}); | ||
export { | ||
AlgorithmTypes, | ||
JwtAlgorithmNotImplemented, | ||
JwtAlorithmNotImplemented, | ||
JwtTokenExpired, | ||
JwtTokenInvalid, | ||
JwtTokenNotBefore, | ||
JwtTokenSignatureMismatched | ||
}; |
{ | ||
"name": "edgeql", | ||
"version": "0.1.5", | ||
"version": "0.1.6", | ||
"author": "Minghe Huang <h.minghe@gmail.com> (https://github.com/metrue)", | ||
@@ -28,3 +28,3 @@ "license": "MIT", | ||
"scripts": { | ||
"build": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json", | ||
"build": "tsx scripts/build.ts", | ||
"prepublishOnly": "npm run build", | ||
@@ -48,2 +48,17 @@ "start": "http_proxy='' https_proxy='' wrangler dev", | ||
}, | ||
"./app": { | ||
"types": "./dist/esm/app.d.ts", | ||
"import": "./dist/esm/app.js", | ||
"require": "./dist/cjs/app.js" | ||
}, | ||
"./compose": { | ||
"types": "./dist/esm/compose.d.ts", | ||
"import": "./dist/esm/compse.js", | ||
"require": "./dist/cjs/compse.js" | ||
}, | ||
"./context/*": { | ||
"types": "./dist/esm/context/*.d.ts", | ||
"import": "./dist/esm/context/*.js", | ||
"require": "./dist/cjs/context/*.js" | ||
}, | ||
"./jwt": { | ||
@@ -100,7 +115,9 @@ "types": "./dist/esm/middleware/jwt/index.d.ts", | ||
"@types/jest": "^29.0.2", | ||
"@types/node": "^17.0.29", | ||
"@types/node": "^20.11.27", | ||
"@typescript-eslint/eslint-plugin": "^5.21.0", | ||
"@typescript-eslint/parser": "^5.21.0", | ||
"@vitest/coverage-v8": "^1.2.2", | ||
"arg": "^5.0.2", | ||
"eslint": "^8.56.0", | ||
"esbuild": "^0.15.12", | ||
"eslint-config-prettier": "^8.5.0", | ||
@@ -114,2 +131,3 @@ "eslint-define-config": "^1.4.0", | ||
"prettier": "^3.2.4", | ||
"tsx": "^4.7.1", | ||
"typescript": "^5.3.3", | ||
@@ -116,0 +134,0 @@ "vite": "^5.0.12", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
57685
26
30
1721
1