feat: modular domain driven boilerplate
This commit is contained in:
@@ -1,28 +0,0 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCy5ZoXkKP9mZTk
|
||||
sKbQdSwspHZqyMH33Gby23+9ycNHMIww7djcWFfPRW4s7tu3SNaac6qVg9OI43+Z
|
||||
6BPXxuh4nhQ4LX5No9iVEmcWvZtKE4ghwzsoU0llT7+aKl9UYvgqU1YX4zyfiyo2
|
||||
bW0nVPasEHTyjLCVPK5BKlq+UmuyJTVcduALDnVETpUefu5Vca6tIRXsOovvAf5b
|
||||
zmcxPccaXIatR/AeipxT0YWoInn8dxD3kyFgTPXtinuBZxvp6MUeSs5IE8OJRJRP
|
||||
PEo1MQ9HFw9aYRIn9uIkbARbNZMGz77zB1+0TrPGyKOB5lLReWGMUFAJhjLrnTsY
|
||||
z19se4kNAgMBAAECgf9QkG6A6ViiHIMnUskIDeP5Xir19d9kbGwrcn0F2OXYaX+l
|
||||
Oot9w3KM6loRJx380/zk/e0Uch1MeZ2fyqQRUmAGQIzkXUm6LUWIekYQN6vZ3JlP
|
||||
YA2/M+otdd8Tpws9hFSDMUlx0SP3GAi0cE48xdBkVAT0NjZ3Jjor7Wv6GLe//Kzg
|
||||
1OVrbPAA/+RrPB+BQn5nmZFT0aLuLpyxB4f4ArHG/8DEBY49Syy7/3Ke0kfHMnhl
|
||||
5Eg5Yau89wSLqEoUSuQvNixu/5nTTQ6v1VYPVG8D1hn773SbNoY9o5vZOPRl1P0q
|
||||
9YC/qpzPJkm/A5TZLsoalIxuGTdwts+DaEeoKmECgYEA5CddLQbMNu9kYElxpSA3
|
||||
xXoTL71ZBCQsWExmJrcGe2lQhGO40lF8jE6QnEvMt0mp8Dg9n2ih4J87+2Ozb0fp
|
||||
2G2ilNeMxM7keywA/+Cwg71QyImppU0lQ5PYLv+pllfxN8FPpLBluy7rDahzphkn
|
||||
1rijqI5d4bHNG6IgD2ynteECgYEAyLs2eBWxX39Jff3OdpSVmHf7NtacbtsUf1qM
|
||||
RJSvLsiSwKn39n1+Y6ebzftxm/XD/j8FbN8XvMZMI4OrlfzP+YJaTybIbHrLzCE2
|
||||
B5E9j0GbJRhJ/D3l9FQBGdY4g5yC4mgbncXURQqqQTtKk2d+ixZSrw8iyDGN+aMJ
|
||||
ybqZoK0CgYALb6GvARk5Y7R/Uw8cPMou3tiZWv9cQsfqQSIZrLDpfLTpfeokuKrq
|
||||
iYGcI/yF725SOS91jxQWI0Upa6zx1gP1skEk/szyjIBNYD5IlSWj5NhoxOW5AG3u
|
||||
vjlm2a/RdmUD62+njKP8xvRHQftSBw7FJ4okh8ZS6suiJ/U9cK/TYQKBgFg+jTyP
|
||||
dNGhuKJN0NUqjvVfUa4S/ORzJXizStTfdIAhpvpR/nN7SfPvfDw6nQBOM+JyvCTX
|
||||
kqznlBNM0EL4yElNN/xx9UxTU4Ki2wjKngB7fAP7wJLGd3BI+c7s8R1S0etMj091
|
||||
59KOVLimoytYJTZqEuFoywatWlfzh9sKUH1lAoGBAID6mqGL3SZhh+i2/kAytfzw
|
||||
UswTQqA0CCBTzN/Eo1QozmUVTLQPj8rBchNSoiSc92y+lPIL8ePdU7imRB77i+9D
|
||||
9MSmc5u3ACACOSkwF0JCEGN+Rju4HR5wwm3h6Kvf/FQ3yvSEOKAWhqXIY95qtYTU
|
||||
j3O+iJbY32pbQsawIAkw
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -1,9 +0,0 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsuWaF5Cj/ZmU5LCm0HUs
|
||||
LKR2asjB99xm8tt/vcnDRzCMMO3Y3FhXz0VuLO7bt0jWmnOqlYPTiON/megT18bo
|
||||
eJ4UOC1+TaPYlRJnFr2bShOIIcM7KFNJZU+/mipfVGL4KlNWF+M8n4sqNm1tJ1T2
|
||||
rBB08oywlTyuQSpavlJrsiU1XHbgCw51RE6VHn7uVXGurSEV7DqL7wH+W85nMT3H
|
||||
GlyGrUfwHoqcU9GFqCJ5/HcQ95MhYEz17Yp7gWcb6ejFHkrOSBPDiUSUTzxKNTEP
|
||||
RxcPWmESJ/biJGwEWzWTBs++8wdftE6zxsijgeZS0XlhjFBQCYYy6507GM9fbHuJ
|
||||
DQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -1,88 +0,0 @@
|
||||
import { cerbos } from "./cerbos.ts";
|
||||
import type { Principal } from "./principal.ts";
|
||||
import { Resource } from "./resources.ts";
|
||||
|
||||
export function access(principal: Principal) {
|
||||
return {
|
||||
/**
|
||||
* Check if a principal is allowed to perform an action on a resource.
|
||||
*
|
||||
* @param resource - Resource which we are validating.
|
||||
* @param action - Action which we are validating.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* await access.isAllowed(
|
||||
* {
|
||||
* kind: "document",
|
||||
* id: "1",
|
||||
* attr: { owner: "user@example.com" },
|
||||
* },
|
||||
* "view"
|
||||
* ); // => true
|
||||
*/
|
||||
isAllowed(resource: Resource, action: string) {
|
||||
return cerbos.isAllowed({ principal, resource, action });
|
||||
},
|
||||
|
||||
/**
|
||||
* Check a principal's permissions on a resource.
|
||||
*
|
||||
* @param resource - Resource which we are validating.
|
||||
* @param actions - Actions which we are validating.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* const decision = await access.checkResource(
|
||||
* {
|
||||
* kind: "document",
|
||||
* id: "1",
|
||||
* attr: { owner: "user@example.com" },
|
||||
* },
|
||||
* ["view", "edit"],
|
||||
* );
|
||||
*
|
||||
* decision.isAllowed("view"); // => true
|
||||
*/
|
||||
checkResource(resource: Resource, actions: string[]) {
|
||||
return cerbos.checkResource({ principal, resource, actions });
|
||||
},
|
||||
|
||||
/**
|
||||
* Check a principal's permissions on a set of resources.
|
||||
*
|
||||
* @param resources - Resources which we are validating.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* const decision = await access.checkResources([
|
||||
* {
|
||||
* resource: {
|
||||
* kind: "document",
|
||||
* id: "1",
|
||||
* attr: { owner: "user@example.com" },
|
||||
* },
|
||||
* actions: ["view", "edit"],
|
||||
* },
|
||||
* {
|
||||
* resource: {
|
||||
* kind: "image",
|
||||
* id: "1",
|
||||
* attr: { owner: "user@example.com" },
|
||||
* },
|
||||
* actions: ["delete"],
|
||||
* },
|
||||
* ]);
|
||||
*
|
||||
* decision.isAllowed({
|
||||
* resource: { kind: "document", id: "1" },
|
||||
* action: "view",
|
||||
* }); // => true
|
||||
*/
|
||||
checkResources(resources: { resource: Resource; actions: string[] }[]) {
|
||||
return cerbos.checkResources({ principal, resources });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type Access = ReturnType<typeof access>;
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Auth } from "@valkyr/auth";
|
||||
|
||||
import { access } from "./access.ts";
|
||||
import { config } from "./config.ts";
|
||||
import { principal } from "./principal.ts";
|
||||
import { resources } from "./resources.ts";
|
||||
|
||||
export const auth = new Auth({
|
||||
principal,
|
||||
resources,
|
||||
access,
|
||||
jwt: {
|
||||
algorithm: "RS256",
|
||||
privateKey: config.privateKey,
|
||||
publicKey: config.publicKey,
|
||||
issuer: "http://localhost",
|
||||
audience: "http://localhost",
|
||||
},
|
||||
});
|
||||
|
||||
export type Session = typeof auth.$session;
|
||||
@@ -1,8 +0,0 @@
|
||||
import { HTTP } from "@cerbos/http";
|
||||
|
||||
export const cerbos = new HTTP("http://localhost:3592", {
|
||||
adminCredentials: {
|
||||
username: "cerbos",
|
||||
password: "cerbosAdmin",
|
||||
},
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import type { SerializeOptions } from "cookie";
|
||||
|
||||
import { getEnvironmentVariable, toBoolean } from "~libraries/config/mod.ts";
|
||||
|
||||
export const config = {
|
||||
privateKey: getEnvironmentVariable(
|
||||
"AUTH_PRIVATE_KEY",
|
||||
await readFile(resolve(import.meta.dirname!, ".keys", "private"), "utf-8"),
|
||||
),
|
||||
publicKey: getEnvironmentVariable(
|
||||
"AUTH_PUBLIC_KEY",
|
||||
await readFile(resolve(import.meta.dirname!, ".keys", "public"), "utf-8"),
|
||||
),
|
||||
cookie: (maxAge: number) =>
|
||||
({
|
||||
httpOnly: true,
|
||||
secure: getEnvironmentVariable("AUTH_COOKIE_SECURE", toBoolean, "false"), // Set to true for HTTPS in production
|
||||
maxAge,
|
||||
path: "/",
|
||||
sameSite: "strict",
|
||||
}) satisfies SerializeOptions,
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
import { auth } from "./auth.ts";
|
||||
|
||||
export * from "./auth.ts";
|
||||
export * from "./config.ts";
|
||||
|
||||
export type Auth = typeof auth;
|
||||
@@ -1,18 +0,0 @@
|
||||
import { RoleSchema } from "@platform/spec/account/role.ts";
|
||||
import { PrincipalProvider } from "@valkyr/auth";
|
||||
|
||||
import { db } from "~stores/read-store/database.ts";
|
||||
|
||||
export const principal = new PrincipalProvider(RoleSchema, {}, async function (id: string) {
|
||||
const account = await db.collection("accounts").findOne({ id });
|
||||
if (account === null) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
roles: account.roles,
|
||||
attributes: {},
|
||||
};
|
||||
});
|
||||
|
||||
export type Principal = typeof principal.$principal;
|
||||
@@ -1,10 +0,0 @@
|
||||
import { ResourceRegistry } from "@valkyr/auth";
|
||||
|
||||
export const resources = new ResourceRegistry([
|
||||
{
|
||||
kind: "account",
|
||||
attr: {},
|
||||
},
|
||||
] as const);
|
||||
|
||||
export type Resource = typeof resources.$resource;
|
||||
@@ -1,21 +0,0 @@
|
||||
import { parseArgs } from "@std/cli";
|
||||
|
||||
import { Parser, toString } from "./parsers.ts";
|
||||
|
||||
export function getArgsVariable(key: string, fallback?: any): string;
|
||||
export function getArgsVariable<T extends Parser>(key: string, parse: T, fallback?: any): ReturnType<T>;
|
||||
export function getArgsVariable<T extends Parser>(key: string, parse?: T, fallback?: any): ReturnType<T> {
|
||||
if (typeof parse === "string") {
|
||||
fallback = parse;
|
||||
parse = undefined;
|
||||
}
|
||||
const flags = parseArgs(Deno.args);
|
||||
const value = flags[key];
|
||||
if (value === undefined) {
|
||||
if (fallback !== undefined) {
|
||||
return parse ? parse(fallback) : fallback;
|
||||
}
|
||||
throw new Error(`Config Exception: Missing ${key} variable in arguments`);
|
||||
}
|
||||
return parse ? parse(value) : (toString(value) as any);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { load } from "@std/dotenv";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { Env, Parser, toServiceEnv, toString } from "./parsers.ts";
|
||||
|
||||
const env = await load();
|
||||
|
||||
/**
|
||||
* Get an environment variable and parse it to the desired type.
|
||||
*
|
||||
* @param key - Environment key to resolve.
|
||||
* @param parse - Parser function to convert the value to the desired type. Default: `string`.
|
||||
*/
|
||||
export function getEnvironmentVariable(key: string, fallback?: any): string;
|
||||
export function getEnvironmentVariable<T extends Parser>(key: string, parse: T, fallback?: any): ReturnType<T>;
|
||||
export function getEnvironmentVariable<T extends Parser>(key: string, parse?: T, fallback?: any): ReturnType<T> {
|
||||
if (typeof parse === "string") {
|
||||
fallback = parse;
|
||||
parse = undefined;
|
||||
}
|
||||
const value = env[key] ?? Deno.env.get(key);
|
||||
if (value === undefined) {
|
||||
if (fallback !== undefined) {
|
||||
return parse ? parse(fallback) : fallback;
|
||||
}
|
||||
throw new Error(`Config Exception: Missing ${key} variable in configuration`);
|
||||
}
|
||||
return parse ? parse(value) : (toString(value) as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an environment variable, select value based on ENV map and parse it to the desired type. Can be used with simple primitives or objects / arrays
|
||||
*
|
||||
* @export
|
||||
* @param {{
|
||||
* key: string;
|
||||
* envFallback?: FallbackEnvMap;
|
||||
* fallback: string;
|
||||
* validation: z.ZodTypeAny,
|
||||
* }} options
|
||||
* @param {string} options.key - the name of the env variable
|
||||
* @param {object} options.envFallback - map with env specific fallbacks that will be used if none value provided
|
||||
* @param {string} options.envFallback.local - example "local" SERVICE_ENV target fallback value
|
||||
* @param {string} options.fallback - string fallback that will be used if no env variable found
|
||||
* @param {z.ZodTypeAny} options.validation - Zod validation object or validation primitive
|
||||
* @returns {z.infer<typeof validation>} - Returns the inferred type of the validation provided
|
||||
*/
|
||||
export function validateEnvVariable({
|
||||
key,
|
||||
envFallback,
|
||||
fallback,
|
||||
validation,
|
||||
}: {
|
||||
key: string;
|
||||
validation: z.ZodTypeAny;
|
||||
envFallback?: FallbackEnvMap;
|
||||
fallback?: string;
|
||||
}): z.infer<typeof validation> {
|
||||
const serviceEnv = getEnvironmentVariable("SERVICE_ENV", toServiceEnv, "local");
|
||||
const providedValue = env[key] ?? Deno.env.get(key);
|
||||
const fallbackValue = typeof envFallback === "object" ? (envFallback[serviceEnv] ?? fallback) : fallback;
|
||||
const toBeUsed = providedValue ?? fallbackValue;
|
||||
try {
|
||||
if (typeof toBeUsed === "string" && (toBeUsed.trim().startsWith("{") || toBeUsed.trim().startsWith("["))) {
|
||||
return validation.parse(JSON.parse(toBeUsed));
|
||||
}
|
||||
return validation.parse(toBeUsed);
|
||||
} catch (e) {
|
||||
throw new Deno.errors.InvalidData(`Config Exception: Missing valid ${key} variable in configuration`, { cause: e });
|
||||
}
|
||||
}
|
||||
|
||||
type FallbackEnvMap = Partial<Record<Env, string>> & {
|
||||
testing?: string;
|
||||
local?: string;
|
||||
stg?: string;
|
||||
demo?: string;
|
||||
prod?: string;
|
||||
};
|
||||
@@ -1,98 +0,0 @@
|
||||
const SERVICE_ENV = ["testing", "local", "stg", "demo", "prod"] as const;
|
||||
|
||||
/**
|
||||
* Convert an variable to a string.
|
||||
*
|
||||
* @param value - Value to convert.
|
||||
*/
|
||||
export function toString(value: unknown): string {
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
return value.toString();
|
||||
}
|
||||
throw new Error(`Config Exception: Cannot convert ${value} to string`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an variable to a number.
|
||||
*
|
||||
* @param value - Value to convert.
|
||||
*/
|
||||
export function toNumber(value: unknown): number {
|
||||
if (typeof value === "number") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return parseInt(value);
|
||||
}
|
||||
throw new Error(`Config Exception: Cannot convert ${value} to number`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an variable to a boolean.
|
||||
*
|
||||
* @param value - Value to convert.
|
||||
*/
|
||||
export function toBoolean(value: unknown): boolean {
|
||||
if (typeof value === "boolean") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return value === "true" || value === "1";
|
||||
}
|
||||
throw new Error(`Config Exception: Cannot convert ${value} to boolean`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a variable to an array of strings.
|
||||
*
|
||||
* Expects a comma seprated, eg. foo,bar,foobar
|
||||
*
|
||||
* @param value - Value to convert.
|
||||
*/
|
||||
export function toArray(value: unknown): string[] {
|
||||
if (typeof value === "string") {
|
||||
if (value === "") {
|
||||
return [];
|
||||
}
|
||||
return value.split(",");
|
||||
}
|
||||
throw new Error(`Config Exception: Cannot convert ${value} to array`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the given value is a valid SERVICE_ENV variable.
|
||||
*
|
||||
* @param value - Value to validate.
|
||||
*/
|
||||
export function toServiceEnv(value: unknown): Env {
|
||||
assertServiceEnv(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Assertions
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
function assertServiceEnv(value: unknown): asserts value is Env {
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`Config Exception: Env ${value} is not a string`);
|
||||
}
|
||||
if ((SERVICE_ENV as unknown as string[]).includes(value) === false) {
|
||||
throw new Error(`Config Exception: Invalid env ${value} provided`);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Types
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
export type Parser = (value: unknown) => any;
|
||||
|
||||
export type Env = (typeof SERVICE_ENV)[number];
|
||||
@@ -1,3 +0,0 @@
|
||||
export * from "./libraries/args.ts";
|
||||
export * from "./libraries/environment.ts";
|
||||
export * from "./libraries/parsers.ts";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./password.ts";
|
||||
@@ -1,11 +0,0 @@
|
||||
import * as bcrypt from "@felix/bcrypt";
|
||||
|
||||
export const password = { hash, verify };
|
||||
|
||||
async function hash(password: string): Promise<string> {
|
||||
return bcrypt.hash(password);
|
||||
}
|
||||
|
||||
async function verify(password: string, hash: string): Promise<boolean> {
|
||||
return bcrypt.verify(password, hash);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { config } from "../config.ts";
|
||||
import { getMongoClient } from "../connection.ts";
|
||||
import { container } from "../container.ts";
|
||||
|
||||
container.set("client", getMongoClient(config.mongo));
|
||||
@@ -1,48 +0,0 @@
|
||||
import { Collection, type CollectionOptions, type Db, type Document, type MongoClient } from "mongodb";
|
||||
|
||||
import { container } from "./container.ts";
|
||||
|
||||
export function getDatabaseAccessor<TSchemas extends Record<string, Document>>(
|
||||
database: string,
|
||||
): DatabaseAccessor<TSchemas> {
|
||||
let instance: Db | undefined;
|
||||
return {
|
||||
get db(): Db {
|
||||
if (instance === undefined) {
|
||||
instance = this.client.db(database);
|
||||
}
|
||||
return instance;
|
||||
},
|
||||
get client(): MongoClient {
|
||||
return container.get("client");
|
||||
},
|
||||
collection<TSchema extends keyof TSchemas>(
|
||||
name: TSchema,
|
||||
options?: CollectionOptions,
|
||||
): Collection<TSchemas[TSchema]> {
|
||||
return this.db.collection<TSchemas[TSchema]>(name.toString(), options);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type DatabaseAccessor<TSchemas extends Record<string, Document>> = {
|
||||
/**
|
||||
* Database for given accessor.
|
||||
*/
|
||||
db: Db;
|
||||
|
||||
/**
|
||||
* Lazy loaded mongo client.
|
||||
*/
|
||||
client: MongoClient;
|
||||
|
||||
/**
|
||||
* Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
|
||||
*
|
||||
* Collection namespace validation is performed server-side.
|
||||
*
|
||||
* @param name - Collection name we wish to access.
|
||||
* @param options - Optional settings for the command.
|
||||
*/
|
||||
collection<TSchema extends keyof TSchemas>(name: TSchema, options?: CollectionOptions): Collection<TSchemas[TSchema]>;
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
import { getEnvironmentVariable, toNumber } from "~libraries/config/mod.ts";
|
||||
|
||||
export const config = {
|
||||
mongo: {
|
||||
host: getEnvironmentVariable("DB_MONGO_HOST", "localhost"),
|
||||
port: getEnvironmentVariable("DB_MONGO_PORT", toNumber, "27017"),
|
||||
user: getEnvironmentVariable("DB_MONGO_USER", "root"),
|
||||
pass: getEnvironmentVariable("DB_MONGO_PASSWORD", "password"),
|
||||
},
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
import { MongoClient } from "mongodb";
|
||||
|
||||
export function getMongoClient(config: MongoConnectionInfo) {
|
||||
return new MongoClient(getConnectionUrl(config));
|
||||
}
|
||||
|
||||
export function getConnectionUrl({ host, port, user, pass }: MongoConnectionInfo): MongoConnectionUrl {
|
||||
return `mongodb://${user}:${pass}@${host}:${port}`;
|
||||
}
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Types
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
export type MongoConnectionUrl = `mongodb://${string}:${string}@${string}:${number}`;
|
||||
|
||||
export type MongoConnectionInfo = {
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
pass: string;
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
import { Container } from "@valkyr/inverse";
|
||||
import { MongoClient } from "mongodb";
|
||||
|
||||
export const container = new Container<{
|
||||
client: MongoClient;
|
||||
}>("database");
|
||||
@@ -1,3 +0,0 @@
|
||||
import type { CreateIndexesOptions, IndexSpecification } from "mongodb";
|
||||
|
||||
export const idIndex: [IndexSpecification, CreateIndexesOptions] = [{ id: 1 }, { unique: true }];
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { CreateIndexesOptions, Db, IndexSpecification } from "mongodb";
|
||||
|
||||
import { getCollectionsSet } from "./utilities.ts";
|
||||
|
||||
/**
|
||||
* Takes a mongo database and registers the event store collections and
|
||||
* indexes defined internally.
|
||||
*
|
||||
* @param db - Mongo database to register event store collections against.
|
||||
* @param registrars - List of registrars to register with the database.
|
||||
* @param logger - Logger method to print internal logs.
|
||||
*/
|
||||
export async function register(db: Db, registrars: Registrar[], logger?: (...args: any[]) => any) {
|
||||
const list = await getCollectionsSet(db);
|
||||
for (const { name, indexes } of registrars) {
|
||||
if (list.has(name) === false) {
|
||||
await db.createCollection(name);
|
||||
}
|
||||
for (const [indexSpec, options] of indexes) {
|
||||
await db.collection(name).createIndex(indexSpec, options);
|
||||
logger?.("Mongo Event Store > Collection '%s' is indexed [%O] with options %O", name, indexSpec, options ?? {});
|
||||
}
|
||||
logger?.("Mongo Event Store > Collection '%s' is registered", name);
|
||||
}
|
||||
}
|
||||
|
||||
export type Registrar = {
|
||||
name: string;
|
||||
indexes: [IndexSpecification, CreateIndexesOptions?][];
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
import type { Db } from "mongodb";
|
||||
import z, { ZodType } from "zod";
|
||||
|
||||
/**
|
||||
* Get a Set of collections that exists on a given mongo database instance.
|
||||
*
|
||||
* @param db - Mongo database to fetch collection list for.
|
||||
*/
|
||||
export async function getCollectionsSet(db: Db) {
|
||||
return db
|
||||
.listCollections()
|
||||
.toArray()
|
||||
.then((collections) => new Set(collections.map((c) => c.name)));
|
||||
}
|
||||
|
||||
export function toParsedDocuments<TSchema extends ZodType>(
|
||||
schema: TSchema,
|
||||
): (documents: unknown[]) => Promise<z.infer<TSchema>[]> {
|
||||
return async function (documents: unknown[]) {
|
||||
const parsed = [];
|
||||
for (const document of documents) {
|
||||
parsed.push(await schema.parseAsync(document));
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
}
|
||||
|
||||
export function toParsedDocument<TSchema extends ZodType>(
|
||||
schema: TSchema,
|
||||
): (document?: unknown) => Promise<z.infer<TSchema> | undefined> {
|
||||
return async function (document: unknown) {
|
||||
if (document === undefined || document === null) {
|
||||
return undefined;
|
||||
}
|
||||
return schema.parseAsync(document);
|
||||
};
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { HexValue } from "./color/hex.ts";
|
||||
import { type BGColor, type Color, hexToBgColor, hexToColor, type Modifier, styles } from "./color/styles.ts";
|
||||
|
||||
export const chalk = {
|
||||
color(hex: HexValue): (value: string) => string {
|
||||
const color = hexToColor(hex);
|
||||
return (value: string) => `${color}${value}${styles.modifier.reset}`;
|
||||
},
|
||||
bgColor(hex: HexValue): (value: string) => string {
|
||||
const color = hexToBgColor(hex);
|
||||
return (value: string) => `${color}${value}${styles.modifier.reset}`;
|
||||
},
|
||||
} as Chalk;
|
||||
|
||||
for (const key in styles.modifier) {
|
||||
chalk[key as Modifier] = function (value: string) {
|
||||
return toModifiedValue(key as Modifier, value);
|
||||
};
|
||||
}
|
||||
|
||||
for (const key in styles.color) {
|
||||
chalk[key as Color] = function (value: string) {
|
||||
return toColorValue(key as Color, value);
|
||||
};
|
||||
}
|
||||
|
||||
for (const key in styles.bgColor) {
|
||||
chalk[key as BGColor] = function (value: string) {
|
||||
return toBGColorValue(key as BGColor, value);
|
||||
};
|
||||
}
|
||||
|
||||
function toModifiedValue(key: Modifier, value: string): string {
|
||||
return `${styles.modifier[key]}${value}${styles.modifier.reset}`;
|
||||
}
|
||||
|
||||
function toColorValue(key: Color, value: string): string {
|
||||
return `${styles.color[key]}${value}${styles.modifier.reset}`;
|
||||
}
|
||||
|
||||
function toBGColorValue(key: BGColor, value: string): string {
|
||||
return `${styles.bgColor[key]}${value}${styles.modifier.reset}`;
|
||||
}
|
||||
|
||||
type Chalk = Record<Modifier | Color | BGColor, (value: string) => string> & {
|
||||
color(hex: HexValue): (value: string) => string;
|
||||
bgColor(hex: HexValue): (value: string) => string;
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import { rgbToAnsi256 } from "./rgb.ts";
|
||||
|
||||
/**
|
||||
* Convert provided hex value to closest 256-Color value.
|
||||
*
|
||||
* @param hex - Hex to convert.
|
||||
*/
|
||||
export function hexToAnsi256(hex: HexValue) {
|
||||
const { r, g, b } = hexToRGB(hex);
|
||||
return rgbToAnsi256(r, g, b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take a hex value and return its RGB values.
|
||||
*
|
||||
* @param hex - Hex to convert to RGB
|
||||
* @returns
|
||||
*/
|
||||
export function hexToRGB(hex: HexValue): { r: number; g: number; b: number } {
|
||||
return {
|
||||
r: parseInt(hex.slice(1, 3), 16),
|
||||
g: parseInt(hex.slice(3, 5), 16),
|
||||
b: parseInt(hex.slice(5, 7), 16),
|
||||
};
|
||||
}
|
||||
|
||||
export type HexValue =
|
||||
`#${string | number}${string | number}${string | number}${string | number}${string | number}${string | number}`;
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* Convert RGB to the nearest 256-color ANSI value
|
||||
*
|
||||
* @param r - Red value.
|
||||
* @param g - Green value.
|
||||
* @param b - Blue value.
|
||||
*/
|
||||
export function rgbToAnsi256(r: number, g: number, b: number): number {
|
||||
if (r === g && g === b) {
|
||||
if (r < 8) return 16;
|
||||
if (r > 248) return 231;
|
||||
return Math.round(((r - 8) / 247) * 24) + 232;
|
||||
}
|
||||
|
||||
// Map RGB to 6×6×6 color cube (16–231)
|
||||
const conv = (val: number) => Math.round(val / 51);
|
||||
const ri = conv(r);
|
||||
const gi = conv(g);
|
||||
const bi = conv(b);
|
||||
|
||||
return 16 + 36 * ri + 6 * gi + bi;
|
||||
}
|
||||
|
||||
export type RGB = { r: number; g: number; b: number };
|
||||
@@ -1,76 +0,0 @@
|
||||
import { hexToAnsi256, HexValue } from "./hex.ts";
|
||||
import { toEscapeSequence } from "./utilities.ts";
|
||||
|
||||
export const styles = {
|
||||
modifier: {
|
||||
reset: toEscapeSequence(0), // Reset to normal
|
||||
bold: toEscapeSequence(1), // Bold text
|
||||
dim: toEscapeSequence(2), // Dim text
|
||||
italic: toEscapeSequence(3), // Italic text
|
||||
underline: toEscapeSequence(4), // Underlined text
|
||||
overline: toEscapeSequence(53), // Overline text
|
||||
inverse: toEscapeSequence(7), // Inverse
|
||||
hidden: toEscapeSequence(8), // Hidden text
|
||||
strikethrough: toEscapeSequence(9), // Strikethrough
|
||||
},
|
||||
|
||||
color: {
|
||||
black: toEscapeSequence(30), // Black color
|
||||
red: toEscapeSequence(31), // Red color
|
||||
green: toEscapeSequence(32), // Green color
|
||||
yellow: toEscapeSequence(33), // Yellow color
|
||||
blue: toEscapeSequence(34), // Blue color
|
||||
magenta: toEscapeSequence(35), // Magenta color
|
||||
cyan: toEscapeSequence(36), // Cyan color
|
||||
white: toEscapeSequence(37), // White color
|
||||
orange: hexToColor("#FFA500"),
|
||||
|
||||
// Bright colors
|
||||
blackBright: toEscapeSequence(90),
|
||||
gray: toEscapeSequence(90), // Alias for blackBright
|
||||
grey: toEscapeSequence(90), // Alias for blackBright
|
||||
redBright: toEscapeSequence(91),
|
||||
greenBright: toEscapeSequence(92),
|
||||
yellowBright: toEscapeSequence(93),
|
||||
blueBright: toEscapeSequence(94),
|
||||
magentaBright: toEscapeSequence(95),
|
||||
cyanBright: toEscapeSequence(96),
|
||||
whiteBright: toEscapeSequence(97),
|
||||
},
|
||||
|
||||
bgColor: {
|
||||
bgBlack: toEscapeSequence(40),
|
||||
bgRed: toEscapeSequence(41),
|
||||
bgGreen: toEscapeSequence(42),
|
||||
bgYellow: toEscapeSequence(43),
|
||||
bgBlue: toEscapeSequence(44),
|
||||
bgMagenta: toEscapeSequence(45),
|
||||
bgCyan: toEscapeSequence(46),
|
||||
bgWhite: toEscapeSequence(47),
|
||||
bgOrange: hexToBgColor("#FFA500"),
|
||||
|
||||
// Bright background colors
|
||||
bgBlackBright: toEscapeSequence(100),
|
||||
bgGray: toEscapeSequence(100), // Alias for bgBlackBright
|
||||
bgGrey: toEscapeSequence(100), // Alias for bgBlackBright
|
||||
bgRedBright: toEscapeSequence(101),
|
||||
bgGreenBright: toEscapeSequence(102),
|
||||
bgYellowBright: toEscapeSequence(103),
|
||||
bgBlueBright: toEscapeSequence(104),
|
||||
bgMagentaBright: toEscapeSequence(105),
|
||||
bgCyanBright: toEscapeSequence(106),
|
||||
bgWhiteBright: toEscapeSequence(107),
|
||||
},
|
||||
};
|
||||
|
||||
export function hexToColor(hex: HexValue): string {
|
||||
return toEscapeSequence(`38;5;${hexToAnsi256(hex)}`); // Foreground color
|
||||
}
|
||||
|
||||
export function hexToBgColor(hex: HexValue): string {
|
||||
return toEscapeSequence(`48;5;${hexToAnsi256(hex)}`); // Background color
|
||||
}
|
||||
|
||||
export type Modifier = keyof typeof styles.modifier;
|
||||
export type Color = keyof typeof styles.color;
|
||||
export type BGColor = keyof typeof styles.bgColor;
|
||||
@@ -1,3 +0,0 @@
|
||||
export function toEscapeSequence(value: string | number): `\x1b[${string}m` {
|
||||
return `\x1b[${value}m`;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { getArgsVariable } from "~libraries/config/mod.ts";
|
||||
|
||||
export const config = {
|
||||
level: getArgsVariable("LOG_LEVEL", "info"),
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
import { EventValidationError } from "@valkyr/event-store";
|
||||
|
||||
import type { Level } from "../level.ts";
|
||||
import { getTracedAt } from "../stack.ts";
|
||||
|
||||
export function toEventStoreLog(arg: any, level: Level): any {
|
||||
if (arg instanceof EventValidationError) {
|
||||
const obj: any = {
|
||||
origin: "EventStore",
|
||||
message: arg.message,
|
||||
at: getTracedAt(arg.stack, "/api/domains"),
|
||||
data: arg.errors,
|
||||
};
|
||||
if (level === "debug") {
|
||||
obj.stack = arg.stack;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { ServerError } from "@platform/relay";
|
||||
|
||||
import type { Level } from "../level.ts";
|
||||
import { getTracedAt } from "../stack.ts";
|
||||
|
||||
export function toServerLog(arg: any, level: Level): any {
|
||||
if (arg instanceof ServerError) {
|
||||
const obj: any = {
|
||||
message: arg.message,
|
||||
data: arg.data,
|
||||
at: getTracedAt(arg.stack, "/api/domains"),
|
||||
};
|
||||
if (level === "debug") {
|
||||
obj.stack = arg.stack;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export const logLevel = {
|
||||
debug: 0,
|
||||
info: 1,
|
||||
warning: 2,
|
||||
error: 3,
|
||||
};
|
||||
|
||||
export type Level = "debug" | "error" | "warning" | "info";
|
||||
@@ -1,95 +0,0 @@
|
||||
import { chalk } from "./chalk.ts";
|
||||
import { type Level, logLevel } from "./level.ts";
|
||||
|
||||
export class Logger {
|
||||
#level: Level = "info";
|
||||
#config: Config;
|
||||
|
||||
constructor(config: Config) {
|
||||
this.#config = config;
|
||||
}
|
||||
|
||||
get #prefix(): [string?] {
|
||||
if (this.#config.prefix !== undefined) {
|
||||
return [chalk.bold(chalk.green(this.#config.prefix))];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the highest logging level in the order of debug, info, warn, error.
|
||||
*
|
||||
* When value is 'info', info, warn and error will be logged and debug
|
||||
* will be ignored.
|
||||
*
|
||||
* @param value Highest log level.
|
||||
*/
|
||||
level(value: Level): this {
|
||||
this.#level = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new logger instance with the given name as prefix.
|
||||
*
|
||||
* @param name - Prefix name.
|
||||
*/
|
||||
prefix(name: string): Logger {
|
||||
return new Logger({ prefix: name, loggers: this.#config.loggers }).level(this.#level);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a debug message to terminal.
|
||||
*/
|
||||
debug(...args: any[]) {
|
||||
if (this.#isLevelEnabled(0)) {
|
||||
console.log(new Date(), chalk.bold("Debug"), ...this.#prefix, ...args.map(this.#toFormattedArg));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a info message to terminal.
|
||||
*/
|
||||
info(...args: any[]) {
|
||||
if (this.#isLevelEnabled(1)) {
|
||||
console.log(new Date(), chalk.bold(chalk.blue("Info")), ...this.#prefix, ...args.map(this.#toFormattedArg));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a warning message to terminal.
|
||||
*/
|
||||
warn(...args: any[]) {
|
||||
if (this.#isLevelEnabled(2)) {
|
||||
console.log(new Date(), chalk.bold(chalk.orange("Warning")), ...this.#prefix, ...args.map(this.#toFormattedArg));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a errpr message to terminal.
|
||||
*/
|
||||
error(...args: any[]) {
|
||||
if (this.#isLevelEnabled(3)) {
|
||||
console.log(new Date(), chalk.bold(chalk.red("Error")), ...this.#prefix, ...args.map(this.#toFormattedArg));
|
||||
}
|
||||
}
|
||||
|
||||
#isLevelEnabled(level: 0 | 1 | 2 | 3): boolean {
|
||||
return level >= logLevel[this.#level];
|
||||
}
|
||||
|
||||
#toFormattedArg = (arg: any): string => {
|
||||
for (const logger of this.#config.loggers) {
|
||||
const res = logger(arg, this.#level);
|
||||
if (res !== undefined) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return arg;
|
||||
};
|
||||
}
|
||||
|
||||
type Config = {
|
||||
prefix?: string;
|
||||
loggers: ((arg: any, level: Level) => any)[];
|
||||
};
|
||||
@@ -1,7 +0,0 @@
|
||||
import { toEventStoreLog } from "./format/event-store.ts";
|
||||
import { toServerLog } from "./format/server.ts";
|
||||
import { Logger } from "./logger.ts";
|
||||
|
||||
export const logger = new Logger({
|
||||
loggers: [toServerLog, toEventStoreLog],
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
/**
|
||||
* Fetch the most closest relevant error from the local code base so it can
|
||||
* be more easily traced to its source.
|
||||
*
|
||||
* @param stack - Error stack.
|
||||
* @param search - Relevant stack line search value.
|
||||
*/
|
||||
export function getTracedAt(stack: string | undefined, search: string): string | undefined {
|
||||
if (stack === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const firstMatch = stack.split("\n").find((line) => line.includes(search));
|
||||
if (firstMatch === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return firstMatch
|
||||
.replace(/^.*?(file:\/\/\/)/, "$1")
|
||||
.replace(/\)$/, "")
|
||||
.trim();
|
||||
}
|
||||
@@ -1,415 +0,0 @@
|
||||
import {
|
||||
BadRequestError,
|
||||
ForbiddenError,
|
||||
InternalServerError,
|
||||
NotFoundError,
|
||||
NotImplementedError,
|
||||
Route,
|
||||
RouteMethod,
|
||||
ServerError,
|
||||
type ServerErrorResponse,
|
||||
UnauthorizedError,
|
||||
ZodValidationError,
|
||||
} from "@platform/relay";
|
||||
import { treeifyError } from "zod";
|
||||
|
||||
import { logger } from "~libraries/logger/mod.ts";
|
||||
|
||||
import { getRequestContext } from "./context.ts";
|
||||
import { req } from "./request.ts";
|
||||
|
||||
const SUPPORTED_MEHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
||||
|
||||
export class Api {
|
||||
readonly #index = new Map<string, Route>();
|
||||
|
||||
/**
|
||||
* Route maps funneling registered routes to the specific methods supported by
|
||||
* the relay instance.
|
||||
*/
|
||||
readonly routes: Routes = {
|
||||
POST: [],
|
||||
GET: [],
|
||||
PUT: [],
|
||||
PATCH: [],
|
||||
DELETE: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* List of paths in the '${method} ${path}' format allowing us to quickly throw
|
||||
* errors if a duplicate route path is being added.
|
||||
*/
|
||||
readonly #paths = new Set<string>();
|
||||
|
||||
/**
|
||||
* Instantiate a new Api instance.
|
||||
*
|
||||
* @param routes - Initial list of routes to register with the api.
|
||||
*/
|
||||
constructor(routes: Route[] = []) {
|
||||
this.register(routes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register relays with the API instance allowing for decoupled registration
|
||||
* of server side handling of relay contracts.
|
||||
*
|
||||
* @param routes - Relays to register with the instance.
|
||||
*/
|
||||
register(routes: Route[]): this {
|
||||
const methods: (keyof typeof this.routes)[] = [];
|
||||
for (const route of routes) {
|
||||
const path = `${route.method} ${route.path}`;
|
||||
if (this.#paths.has(path)) {
|
||||
throw new Error(`Router > Path ${path} already exists`);
|
||||
}
|
||||
this.#paths.add(path);
|
||||
this.routes[route.method].push(route);
|
||||
methods.push(route.method);
|
||||
this.#index.set(`${route.method} ${route.path}`, route);
|
||||
}
|
||||
for (const method of methods) {
|
||||
this.routes[method].sort(byStaticPriority);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes request and returns a `Response` instance.
|
||||
*
|
||||
* @param request - REST request to pass to a route handler.
|
||||
*/
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
// ### Route
|
||||
// Locate a route matching the incoming request method and path.
|
||||
|
||||
const resolved = this.#getResolvedRoute(request.method, url.pathname);
|
||||
if (resolved === undefined) {
|
||||
return toResponse(
|
||||
new NotFoundError(`Invalid routing path provided for ${request.url}`, {
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
}),
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
// ### Handle
|
||||
// Execute request and return a response.
|
||||
|
||||
const response = await this.#getRouteResponse(resolved, request).catch((error) =>
|
||||
this.#getErrorResponse(error, resolved.route, request),
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to resolve a route based on the given method and pathname.
|
||||
*
|
||||
* @param method - HTTP method.
|
||||
* @param url - HTTP request url.
|
||||
*/
|
||||
#getResolvedRoute(method: string, url: string): ResolvedRoute | undefined {
|
||||
assertMethod(method);
|
||||
for (const route of this.routes[method]) {
|
||||
if (route.match(url) === true) {
|
||||
return { route, params: route.getParsedParams(url) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the request on the given route and return a `Response` instance.
|
||||
*
|
||||
* @param resolved - Route and paramter details resolved for the request.
|
||||
* @param request - Request instance to resolve.
|
||||
*/
|
||||
async #getRouteResponse({ route, params }: ResolvedRoute, request: Request): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
// ### Args
|
||||
// Arguments is passed to every route handler and provides a suite of functionality
|
||||
// and request data.
|
||||
|
||||
const args: any[] = [];
|
||||
|
||||
// ### Input
|
||||
// Generate route input which contains a map fo params, query, and/or body. If
|
||||
// none of these are present then the input is not added to the final argument
|
||||
// context of the handler.
|
||||
|
||||
const input: {
|
||||
params?: object;
|
||||
query?: object;
|
||||
body?: unknown;
|
||||
} = {
|
||||
params: undefined,
|
||||
query: undefined,
|
||||
body: undefined,
|
||||
};
|
||||
|
||||
// ### Access
|
||||
// Check the access requirements of the route and run any additional checks
|
||||
// if nessesary before proceeding with further request handling.
|
||||
// 1. All routes needs access assignment, else we consider it an internal error.
|
||||
// 2. If access requires a session we throw Unauthorized if the request is not authenticated.
|
||||
// 3. If access is an array of access resources, we check that each resources can be
|
||||
// accessed by the request.
|
||||
|
||||
if (route.state.access === undefined) {
|
||||
return toResponse(
|
||||
new InternalServerError(`Route '${route.method} ${route.path}' is missing access assignment.`),
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
if (route.state.access === "authenticated" && req.isAuthenticated === false) {
|
||||
return toResponse(new UnauthorizedError(), request);
|
||||
}
|
||||
|
||||
if (Array.isArray(route.state.access)) {
|
||||
for (const hasAccess of route.state.access) {
|
||||
if (hasAccess() === false) {
|
||||
return toResponse(new ForbiddenError(), request);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ### Params
|
||||
// If the route has params we want to coerce the values to the expected types.
|
||||
|
||||
if (route.state.params !== undefined) {
|
||||
const result = await route.state.params.safeParseAsync(params);
|
||||
if (result.success === false) {
|
||||
return toResponse(new ZodValidationError("Invalid request params", treeifyError(result.error)), request);
|
||||
}
|
||||
input.params = result.data;
|
||||
}
|
||||
|
||||
// ### Query
|
||||
// If the route has a query schema we need to validate and parse the query.
|
||||
|
||||
if (route.state.query !== undefined) {
|
||||
const result = await route.state.query.safeParseAsync(toQuery(url.searchParams) ?? {});
|
||||
if (result.success === false) {
|
||||
return toResponse(new ZodValidationError("Invalid request query", treeifyError(result.error)), request);
|
||||
}
|
||||
input.query = result.data;
|
||||
}
|
||||
|
||||
// ### Body
|
||||
// If the route has a body schema we need to validate and parse the body.
|
||||
|
||||
if (route.state.body !== undefined) {
|
||||
const body = await this.#getRequestBody(request);
|
||||
const result = await route.state.body.safeParseAsync(body);
|
||||
if (result.success === false) {
|
||||
return toResponse(new ZodValidationError("Invalid request body", treeifyError(result.error)), request);
|
||||
}
|
||||
input.body = result.data;
|
||||
}
|
||||
|
||||
if (input.params !== undefined || input.query !== undefined || input.body !== undefined) {
|
||||
args.push(input);
|
||||
}
|
||||
|
||||
// ### Context
|
||||
// Request context pass to every route as the last argument.
|
||||
|
||||
args.push(getRequestContext(request));
|
||||
|
||||
// ### Handler
|
||||
// Execute the route handler and apply the result.
|
||||
|
||||
if (route.state.handle === undefined) {
|
||||
return toResponse(new NotImplementedError(`Path '${route.method} ${route.path}' is not implemented.`), request);
|
||||
}
|
||||
|
||||
return toResponse(await route.state.handle(...args), request);
|
||||
}
|
||||
|
||||
#getErrorResponse(error: unknown, route: Route, request: Request): Response {
|
||||
if (route?.state.hooks?.onError !== undefined) {
|
||||
return route.state.hooks.onError(error);
|
||||
}
|
||||
if (error instanceof ServerError) {
|
||||
return toResponse(error, request);
|
||||
}
|
||||
logger.error(error);
|
||||
if (error instanceof Error) {
|
||||
return toResponse(new InternalServerError(error.message), request);
|
||||
}
|
||||
return toResponse(new InternalServerError(), request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves request body and returns it.
|
||||
*
|
||||
* @param request - Request to resolve body from.
|
||||
* @param files - Files to populate if present.
|
||||
*/
|
||||
async #getRequestBody(request: Request): Promise<Record<string, unknown>> {
|
||||
let body: Record<string, unknown> = {};
|
||||
|
||||
const type = request.headers.get("content-type");
|
||||
if (!type || request.method === "GET") {
|
||||
return body;
|
||||
}
|
||||
|
||||
if (type.includes("json")) {
|
||||
body = await request.json();
|
||||
}
|
||||
|
||||
if (type.includes("application/x-www-form-urlencoded") || type.includes("multipart/form-data")) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
for (const [name, value] of Array.from(formData.entries())) {
|
||||
body[name] = value;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
throw new BadRequestError(`Malformed FormData`, { error });
|
||||
}
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Helpers
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Assert that the given method string is a valid routing method.
|
||||
*
|
||||
* @param candidate - Method candidate.
|
||||
*/
|
||||
function assertMethod(candidate: string): asserts candidate is RouteMethod {
|
||||
if (!SUPPORTED_MEHODS.includes(candidate)) {
|
||||
throw new Error(`Router > Unsupported method '${candidate}'`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorting method for routes to ensure that static properties takes precedence
|
||||
* for when a route is matched against incoming requests.
|
||||
*
|
||||
* @param a - Route A
|
||||
* @param b - Route B
|
||||
*/
|
||||
function byStaticPriority(a: Route, b: Route) {
|
||||
const aSegments = a.path.split("/");
|
||||
const bSegments = b.path.split("/");
|
||||
|
||||
const maxLength = Math.max(aSegments.length, bSegments.length);
|
||||
|
||||
for (let i = 0; i < maxLength; i++) {
|
||||
const aSegment = aSegments[i] || "";
|
||||
const bSegment = bSegments[i] || "";
|
||||
|
||||
const isADynamic = aSegment.startsWith(":");
|
||||
const isBDynamic = bSegment.startsWith(":");
|
||||
|
||||
if (isADynamic !== isBDynamic) {
|
||||
return isADynamic ? 1 : -1;
|
||||
}
|
||||
|
||||
if (isADynamic === false && aSegment !== bSegment) {
|
||||
return aSegment.localeCompare(bSegment);
|
||||
}
|
||||
}
|
||||
|
||||
return a.path.localeCompare(b.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and return query object from the provided search parameters, or undefined
|
||||
* if the search parameters does not have any entries.
|
||||
*
|
||||
* @param searchParams - Search params to create a query object from.
|
||||
*/
|
||||
function toQuery(searchParams: URLSearchParams): object | undefined {
|
||||
if (searchParams.size === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const result: Record<string, string> = {};
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a server side request result and returns a fetch Response.
|
||||
*
|
||||
* @param result - Result to send back as a Response.
|
||||
* @param request - Request instance.
|
||||
*/
|
||||
export function toResponse(result: unknown, request: Request): Response {
|
||||
const method = request.method;
|
||||
|
||||
if (result instanceof Response) {
|
||||
if (method === "HEAD") {
|
||||
return new Response(null, {
|
||||
status: result.status,
|
||||
statusText: result.statusText,
|
||||
headers: new Headers(result.headers),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if (result instanceof ServerError) {
|
||||
const body = JSON.stringify({
|
||||
error: {
|
||||
status: result.status,
|
||||
message: result.message,
|
||||
data: result.data,
|
||||
},
|
||||
} satisfies ServerErrorResponse);
|
||||
|
||||
return new Response(method === "HEAD" ? null : body, {
|
||||
statusText: result.message || "Internal Server Error",
|
||||
status: result.status || 500,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const body = JSON.stringify({
|
||||
data: result ?? null,
|
||||
});
|
||||
|
||||
return new Response(method === "HEAD" ? null : body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Types
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
type Routes = {
|
||||
POST: Route[];
|
||||
GET: Route[];
|
||||
PUT: Route[];
|
||||
PATCH: Route[];
|
||||
DELETE: Route[];
|
||||
};
|
||||
|
||||
type ResolvedRoute = {
|
||||
route: Route;
|
||||
params: any;
|
||||
};
|
||||
@@ -1,68 +0,0 @@
|
||||
import { ServerContext } from "@platform/relay";
|
||||
|
||||
import type { Sockets } from "~libraries/socket/sockets.ts";
|
||||
|
||||
import { Access } from "../auth/access.ts";
|
||||
import { Session } from "../auth/auth.ts";
|
||||
import { Principal } from "../auth/principal.ts";
|
||||
import { req } from "./request.ts";
|
||||
|
||||
declare module "@platform/relay" {
|
||||
interface ServerContext {
|
||||
/**
|
||||
* Current request instance being handled.
|
||||
*/
|
||||
request: Request;
|
||||
|
||||
/**
|
||||
* Is the request authenticated.
|
||||
*/
|
||||
isAuthenticated: boolean;
|
||||
|
||||
/**
|
||||
* Get request session instance.
|
||||
*/
|
||||
session: Session;
|
||||
|
||||
/**
|
||||
* Get request principal.
|
||||
*/
|
||||
principal: Principal;
|
||||
|
||||
/**
|
||||
* Get access control session.
|
||||
*/
|
||||
access: Access;
|
||||
|
||||
/**
|
||||
* Sockets instance attached to the server.
|
||||
*/
|
||||
sockets: Sockets;
|
||||
}
|
||||
}
|
||||
|
||||
export function getRequestContext(request: Request): ServerContext {
|
||||
return {
|
||||
request,
|
||||
|
||||
get isAuthenticated(): boolean {
|
||||
return req.isAuthenticated;
|
||||
},
|
||||
|
||||
get session(): Session {
|
||||
return req.session;
|
||||
},
|
||||
|
||||
get principal(): Principal {
|
||||
return req.session.principal;
|
||||
},
|
||||
|
||||
get access(): Access {
|
||||
return req.session.access;
|
||||
},
|
||||
|
||||
get sockets(): Sockets {
|
||||
return req.sockets;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export * from "./api.ts";
|
||||
export * from "./context.ts";
|
||||
export * from "./modules.ts";
|
||||
export * from "./request.ts";
|
||||
export * from "./storage.ts";
|
||||
@@ -1,40 +0,0 @@
|
||||
import { Route } from "@platform/relay";
|
||||
|
||||
/**
|
||||
* Resolve and return all routes that has been created under any 'routes'
|
||||
* folders that can be found under the given path.
|
||||
*
|
||||
* If the filter is empty, all paths are resolved, otherwise only paths
|
||||
* declared in the array is resolved.
|
||||
*
|
||||
* @param path - Path to resolve routes from.
|
||||
* @param filter - List of modules to include.
|
||||
* @param routes - List of routes that has been resolved.
|
||||
*/
|
||||
export async function resolveRoutes(path: string, routes: Route[] = []): Promise<Route[]> {
|
||||
for await (const entry of Deno.readDir(path)) {
|
||||
if (entry.isDirectory === true) {
|
||||
await loadRoutes(`${path}/${entry.name}`, routes, [name]);
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
async function loadRoutes(path: string, routes: Route[], modules: string[]): Promise<void> {
|
||||
for await (const entry of Deno.readDir(path)) {
|
||||
if (entry.isDirectory === true) {
|
||||
await loadRoutes(`${path}/${entry.name}`, routes, [...modules, entry.name]);
|
||||
} else {
|
||||
if (!entry.name.endsWith(".ts") || entry.name.endsWith("i9n.ts")) {
|
||||
continue;
|
||||
}
|
||||
const { default: route } = (await import(`${path}/${entry.name}`)) as { default: Route };
|
||||
if (route instanceof Route === false) {
|
||||
throw new Error(
|
||||
`Router Violation: Could not load '${path}/${entry.name}' as it does not export a default Route instance.`,
|
||||
);
|
||||
}
|
||||
routes.push(route);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { InternalServerError, UnauthorizedError } from "@platform/relay";
|
||||
|
||||
import { Session } from "../auth/auth.ts";
|
||||
import { storage } from "./storage.ts";
|
||||
|
||||
export const req = {
|
||||
get store() {
|
||||
const store = storage.getStore();
|
||||
if (store === undefined) {
|
||||
throw new InternalServerError("AsyncLocalStorage not defined.");
|
||||
}
|
||||
return store;
|
||||
},
|
||||
|
||||
get sockets() {
|
||||
if (this.store.sockets === undefined) {
|
||||
throw new InternalServerError("Sockets not defined.");
|
||||
}
|
||||
return this.store.sockets;
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if the request is authenticated.
|
||||
*/
|
||||
get isAuthenticated(): boolean {
|
||||
return this.session !== undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get current session.
|
||||
*/
|
||||
get session(): Session {
|
||||
if (this.store.session === undefined) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
return this.store.session;
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets the meta information stored in the request.
|
||||
*/
|
||||
get info() {
|
||||
return this.store.info;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get current session.
|
||||
*/
|
||||
getSession(): Session | undefined {
|
||||
return this.store.session;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get store that is potentially undefined.
|
||||
* Typically used when utility functions might run in and out of request scope.
|
||||
*/
|
||||
getStore() {
|
||||
return storage.getStore();
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type ReqContext = typeof req;
|
||||
@@ -1,19 +0,0 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
|
||||
import type { Session } from "~libraries/auth/mod.ts";
|
||||
import type { Sockets } from "~libraries/socket/sockets.ts";
|
||||
|
||||
export const storage = new AsyncLocalStorage<Storage>();
|
||||
|
||||
export type Storage = {
|
||||
session?: Session;
|
||||
info: {
|
||||
method: string;
|
||||
start: number;
|
||||
end?: number;
|
||||
};
|
||||
sockets?: Sockets;
|
||||
response: {
|
||||
headers: Headers;
|
||||
};
|
||||
};
|
||||
@@ -1,81 +0,0 @@
|
||||
import type { Params } from "@valkyr/json-rpc";
|
||||
|
||||
import { Sockets } from "./sockets.ts";
|
||||
|
||||
export class Channels {
|
||||
readonly #channels = new Map<string, Sockets>();
|
||||
|
||||
/**
|
||||
* Add a new channel.
|
||||
*
|
||||
* @param channel
|
||||
*/
|
||||
add(channel: string): this {
|
||||
this.#channels.set(channel, new Sockets());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a channel.
|
||||
*
|
||||
* @param channel
|
||||
*/
|
||||
del(channel: string): this {
|
||||
this.#channels.delete(channel);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add socket to the given channel. If the channel does not exist it is
|
||||
* automatically created.
|
||||
*
|
||||
* @param channel - Channel to add socket to.
|
||||
* @param socket - Socket to add to the channel.
|
||||
*/
|
||||
join(channel: string, socket: WebSocket): this {
|
||||
const sockets = this.#channels.get(channel);
|
||||
if (sockets === undefined) {
|
||||
this.#channels.set(channel, new Sockets().add(socket));
|
||||
} else {
|
||||
sockets.add(socket);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a socket from the given channel.
|
||||
*
|
||||
* @param channel - Channel to leave.
|
||||
* @param socket - Socket to remove from the channel.
|
||||
*/
|
||||
leave(channel: string, socket: WebSocket): this {
|
||||
this.#channels.get(channel)?.del(socket);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a JSON-RPC notification to all sockets in given channel.
|
||||
*
|
||||
* @param channel - Channel to emit method to.
|
||||
* @param method - Method to send the notification to.
|
||||
* @param params - Message data to send to the clients.
|
||||
*/
|
||||
notify(channel: string, method: string, params: Params): this {
|
||||
this.#channels.get(channel)?.notify(method, params);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transmits data to all registered WebSocket connections in the given channel.
|
||||
* Data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
|
||||
*
|
||||
* @param channel - Channel to emit message to.
|
||||
* @param data - Data to send to each connected socket in the channel.
|
||||
*/
|
||||
send(channel: string, data: string | ArrayBufferLike | Blob | ArrayBufferView): this {
|
||||
this.#channels.get(channel)?.send(data);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
export const channels = new Channels();
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { Params } from "@valkyr/json-rpc";
|
||||
|
||||
export class Sockets {
|
||||
readonly #sockets = new Set<WebSocket>();
|
||||
|
||||
/**
|
||||
* Add a socket to the pool.
|
||||
*
|
||||
* @param socket - WebSocket to add.
|
||||
*/
|
||||
add(socket: WebSocket): this {
|
||||
this.#sockets.add(socket);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a socket from the pool.
|
||||
*
|
||||
* @param socket - WebSocket to remove.
|
||||
*/
|
||||
del(socket: WebSocket): this {
|
||||
this.#sockets.delete(socket);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a JSON-RPC notification to all connected sockets.
|
||||
*
|
||||
* @param method - Method to send the notification to.
|
||||
* @param params - Message data to send to the clients.
|
||||
*/
|
||||
notify(method: string, params: Params): this {
|
||||
this.send(JSON.stringify({ jsonrpc: "2.0", method, params }));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transmits data to all registered WebSocket connections. Data can be a string,
|
||||
* a Blob, an ArrayBuffer, or an ArrayBufferView.
|
||||
*
|
||||
* @param data - Data to send to each connected socket.
|
||||
*/
|
||||
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): this {
|
||||
this.#sockets.forEach((socket) => socket.send(data));
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
export const sockets = new Sockets();
|
||||
@@ -1,61 +0,0 @@
|
||||
import { toJsonRpc } from "@valkyr/json-rpc";
|
||||
|
||||
import { Session } from "~libraries/auth/mod.ts";
|
||||
import { logger } from "~libraries/logger/mod.ts";
|
||||
import { asyncLocalStorage } from "~libraries/server/storage.ts";
|
||||
|
||||
import { sockets } from "./sockets.ts";
|
||||
|
||||
export function upgrade(request: Request, session?: Session) {
|
||||
const { socket, response } = Deno.upgradeWebSocket(request);
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
logger.prefix("Socket").info("socket connected", { session });
|
||||
sockets.add(socket);
|
||||
});
|
||||
|
||||
socket.addEventListener("close", () => {
|
||||
logger.prefix("Socket").info("socket disconnected", { session });
|
||||
sockets.del(socket);
|
||||
});
|
||||
|
||||
socket.addEventListener("message", (event) => {
|
||||
if (event.data === "ping") {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = toJsonRpc(event.data);
|
||||
|
||||
logger.prefix("Socket").info(message);
|
||||
|
||||
asyncLocalStorage.run(
|
||||
{
|
||||
session,
|
||||
info: {
|
||||
method: message.method!,
|
||||
start: Date.now(),
|
||||
},
|
||||
sockets,
|
||||
response: {
|
||||
headers: new Headers(),
|
||||
},
|
||||
},
|
||||
async () => {
|
||||
// api
|
||||
// .send(body)
|
||||
// .then((response) => {
|
||||
// if (response !== undefined) {
|
||||
// logger.info({ response });
|
||||
// socket.send(JSON.stringify(response));
|
||||
// }
|
||||
// })
|
||||
// .catch((error) => {
|
||||
// logger.info({ error });
|
||||
// socket.send(JSON.stringify(error));
|
||||
// });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
Reference in New Issue
Block a user