added format command and added trailing commas to reduce conflicts

This commit is contained in:
dswbx
2025-02-26 20:06:03 +01:00
parent 88b5359f1c
commit 7743f71a11
414 changed files with 3622 additions and 3610 deletions

View File

@@ -9,7 +9,7 @@ import {
type Field,
FieldPrototype,
make,
type em as prototypeEm
type em as prototypeEm,
} from "data";
import { Entity } from "data";
import type { Hono } from "hono";
@@ -33,7 +33,7 @@ export abstract class Module<Schema extends TSchema = TSchema, ConfigSchema = St
constructor(
initial?: Partial<Static<Schema>>,
protected _ctx?: ModuleBuildContext
protected _ctx?: ModuleBuildContext,
) {
this._schema = new SchemaObject(this.getSchema(), initial, {
forceParse: this.useForceParse(),
@@ -42,13 +42,13 @@ export abstract class Module<Schema extends TSchema = TSchema, ConfigSchema = St
},
restrictPaths: this.getRestrictedPaths(),
overwritePaths: this.getOverwritePaths(),
onBeforeUpdate: this.onBeforeUpdate.bind(this)
onBeforeUpdate: this.onBeforeUpdate.bind(this),
});
}
static ctx_flags = {
sync_required: false,
ctx_reload_required: false
ctx_reload_required: false,
} as {
// signal that a sync is required at the end of build
sync_required: boolean;
@@ -124,7 +124,7 @@ export abstract class Module<Schema extends TSchema = TSchema, ConfigSchema = St
forceParse: this.useForceParse(),
restrictPaths: this.getRestrictedPaths(),
overwritePaths: this.getOverwritePaths(),
onBeforeUpdate: this.onBeforeUpdate.bind(this)
onBeforeUpdate: this.onBeforeUpdate.bind(this),
});
}
@@ -169,7 +169,7 @@ export abstract class Module<Schema extends TSchema = TSchema, ConfigSchema = St
// replace entity (mainly to keep the ensured type)
this.ctx.em.__replaceEntity(
new Entity(instance.name, instance.fields, instance.config, entity.type)
new Entity(instance.name, instance.fields, instance.config, entity.type),
);
}
@@ -190,7 +190,7 @@ export abstract class Module<Schema extends TSchema = TSchema, ConfigSchema = St
protected setEntityFieldConfigs(
parent: Field,
child: Field,
props: string[] = ["hidden", "fillable", "required"]
props: string[] = ["hidden", "fillable", "required"],
) {
let changes = 0;
for (const prop of props) {
@@ -205,7 +205,7 @@ export abstract class Module<Schema extends TSchema = TSchema, ConfigSchema = St
protected replaceEntityField(
_entity: string | Entity,
field: Field | string,
_newField: Field | FieldPrototype
_newField: Field | FieldPrototype,
) {
const entity = this.ctx.em.entity(_entity);
const name = typeof field === "string" ? field : field.name;

View File

@@ -28,7 +28,7 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
constructor(
protected readonly _options: Partial<Options> = {},
fetcher?: typeof fetch
fetcher?: typeof fetch,
) {
this.fetcher = fetcher ?? fetch;
}
@@ -42,7 +42,7 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
host: "http://localhost",
token: undefined,
...this.getDefaultOptions(),
...this._options
...this._options,
} as Options;
}
@@ -61,7 +61,7 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
protected request<Data = any>(
_input: TInput,
_query?: Record<string, any> | URLSearchParams,
_init?: RequestInit
_init?: RequestInit,
): FetchPromise<ResponseObject<Data>> {
const method = _init?.method ?? "GET";
const input = Array.isArray(_input) ? _input.join("/") : _input;
@@ -104,23 +104,23 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
..._init,
method,
body,
headers
headers,
});
return new FetchPromise(request, {
fetcher: this.fetcher,
verbose: this.options.verbose
verbose: this.options.verbose,
});
}
get<Data = any>(
_input: TInput,
_query?: Record<string, any> | URLSearchParams,
_init?: RequestInit
_init?: RequestInit,
) {
return this.request<Data>(_input, _query, {
..._init,
method: "GET"
method: "GET",
});
}
@@ -128,7 +128,7 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
return this.request<Data>(_input, undefined, {
..._init,
body,
method: "POST"
method: "POST",
});
}
@@ -136,7 +136,7 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
return this.request<Data>(_input, undefined, {
..._init,
body,
method: "PATCH"
method: "PATCH",
});
}
@@ -144,14 +144,14 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
return this.request<Data>(_input, undefined, {
..._init,
body,
method: "PUT"
method: "PUT",
});
}
delete<Data = any>(_input: TInput, _init?: RequestInit) {
return this.request<Data>(_input, undefined, {
..._init,
method: "DELETE"
method: "DELETE",
});
}
}
@@ -169,7 +169,7 @@ export type ResponseObject<Body = any, Data = Body extends { data: infer R } ? R
export function createResponseProxy<Body = any, Data = any>(
raw: Response,
body: Body,
data?: Data
data?: Data,
): ResponseObject<Body, Data> {
let actualData: any = data ?? body;
const _props = ["raw", "body", "ok", "status", "res", "data", "toJSON"];
@@ -205,11 +205,11 @@ export function createResponseProxy<Body = any, Data = any>(
return {
configurable: true,
enumerable: true,
value: Reflect.get({ raw, body, ok: raw.ok, status: raw.status }, prop)
value: Reflect.get({ raw, body, ok: raw.ok, status: raw.status }, prop),
};
}
return Reflect.getOwnPropertyDescriptor(target, prop);
}
},
}) as ResponseObject<Body, Data>;
}
@@ -222,7 +222,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
protected options?: {
fetcher?: typeof fetch;
verbose?: boolean;
}
},
) {}
get verbose() {
@@ -237,7 +237,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
if (this.verbose) {
console.log("[FetchPromise] Request", {
method: this.request.method,
url: this.request.url
url: this.request.url,
});
}
@@ -246,7 +246,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
console.log("[FetchPromise] Response", {
res: res,
ok: res.ok,
status: res.status
status: res.status,
});
}
@@ -272,13 +272,13 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
// biome-ignore lint/suspicious/noThenProperty: it's a promise :)
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined,
): Promise<TResult1 | TResult2> {
return this.execute().then(onfulfilled as any, onrejected);
}
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined,
): Promise<T | TResult> {
return this.then(undefined, onrejected);
}
@@ -292,7 +292,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
(reason) => {
onfinally?.();
throw reason;
}
},
);
}
@@ -310,7 +310,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
const url = new URL(this.request.url);
const path = this.path().split("/");
return (options?.search !== false ? [...path, url.searchParams.toString()] : path).filter(
Boolean
Boolean,
);
}
}

View File

@@ -10,7 +10,7 @@ import {
mark,
objectEach,
stripMark,
transformObject
transformObject,
} from "core/utils";
import {
type Connection,
@@ -20,7 +20,7 @@ import {
entity,
enumm,
jsonSchema,
number
number,
} from "data";
import { TransformPersistFailedException } from "data/errors";
import { Hono } from "hono";
@@ -42,7 +42,7 @@ export const MODULES = {
data: AppData,
auth: AppAuth,
media: AppMedia,
flows: AppFlows
flows: AppFlows,
} as const;
// get names of MODULES as an array
@@ -71,7 +71,7 @@ export type InitialModuleConfigs =
enum Verbosity {
silent = 0,
error = 1,
log = 2
log = 2,
}
export type ModuleManagerOptions = {
@@ -79,7 +79,7 @@ export type ModuleManagerOptions = {
eventManager?: EventManager<any>;
onUpdated?: <Module extends keyof Modules>(
module: Module,
config: ModuleConfigs[Module]
config: ModuleConfigs[Module],
) => Promise<void>;
// triggered when no config table existed
onFirstBoot?: () => Promise<void>;
@@ -111,16 +111,16 @@ const configJsonSchema = Type.Union([
t: StringEnum(["a", "r", "e"]),
p: Type.Array(Type.Union([Type.String(), Type.Number()])),
o: Type.Optional(Type.Any()),
n: Type.Optional(Type.Any())
})
)
n: Type.Optional(Type.Any()),
}),
),
]);
const __bknd = entity(TABLE_NAME, {
version: number().required(),
type: enumm({ enum: ["config", "diff", "backup"] }).required(),
json: jsonSchema({ schema: configJsonSchema }).required(),
created_at: datetime(),
updated_at: datetime()
updated_at: datetime(),
});
type ConfigTable2 = Schema<typeof __bknd>;
interface T_INTERNAL_EM {
@@ -147,7 +147,7 @@ export class ModuleManager {
constructor(
private readonly connection: Connection,
private options?: Partial<ModuleManagerOptions>
private options?: Partial<ModuleManagerOptions>,
) {
this.__em = new EntityManager([__bknd], this.connection);
this.modules = {} as Modules;
@@ -249,7 +249,7 @@ export class ModuleManager {
emgr: this.emgr,
guard: this.guard,
flags: Module.ctx_flags,
logger: this.logger
logger: this.logger,
};
}
@@ -263,8 +263,8 @@ export class ModuleManager {
const { data: result } = await this.repo().findOne(
{ type: "config" },
{
sort: { by: "version", dir: "desc" }
}
sort: { by: "version", dir: "desc" },
},
);
if (!result) {
@@ -273,13 +273,13 @@ export class ModuleManager {
return result as unknown as ConfigTable;
},
this.verbosity > Verbosity.silent ? [] : ["log", "error", "warn"]
this.verbosity > Verbosity.silent ? [] : ["log", "error", "warn"],
);
this.logger
.log("took", performance.now() - startTime, "ms", {
version: result.version,
id: result.id
id: result.id,
})
.clear();
return result;
@@ -300,12 +300,12 @@ export class ModuleManager {
await this.mutator().insertOne({
version: state.version,
type: "backup",
json: configs
json: configs,
});
await this.mutator().insertOne({
version: version,
type: "config",
json: configs
json: configs,
});
} else {
this.logger.log("version matches");
@@ -319,7 +319,7 @@ export class ModuleManager {
await this.mutator().insertOne({
version,
type: "diff",
json: clone(diffs)
json: clone(diffs),
});
// store new version
@@ -327,12 +327,12 @@ export class ModuleManager {
{
version,
json: configs,
updated_at: new Date()
updated_at: new Date(),
} as any,
{
type: "config",
version
}
version,
},
);
} else {
this.logger.log("no diff, not saving");
@@ -347,7 +347,7 @@ export class ModuleManager {
version,
json: configs,
created_at: new Date(),
updated_at: new Date()
updated_at: new Date(),
});
} else if (e instanceof TransformPersistFailedException) {
console.error("Cannot save invalid config");
@@ -383,7 +383,7 @@ export class ModuleManager {
if (state.version !== this.version()) {
// @todo: potentially drop provided config and use database version
throw new Error(
`Given version (${this.version()}) and fetched version (${state.version}) do not match.`
`Given version (${this.version()}) and fetched version (${state.version}) do not match.`,
);
}
} catch (e: any) {
@@ -400,7 +400,7 @@ export class ModuleManager {
}
const [_version, _configs] = await migrate(version, configs, {
db: this.db
db: this.db,
});
version = _version;
configs = _configs;
@@ -427,7 +427,7 @@ export class ModuleManager {
} catch (e) {
console.error(e);
throw new Error(
`Failed to set config for module ${key}: ${JSON.stringify(config, null, 2)}`
`Failed to set config for module ${key}: ${JSON.stringify(config, null, 2)}`,
);
}
});
@@ -493,7 +493,7 @@ export class ModuleManager {
modules: [] as ModuleKey[],
synced: false,
saved: false,
reloaded: false
reloaded: false,
};
this.logger.log("buildModules() triggered", options, this._built);
@@ -545,7 +545,7 @@ export class ModuleManager {
const ctx = {
...this.ctx(),
// disable events for initial setup
em: this.ctx().em.fork()
em: this.ctx().em.fork(),
};
// perform a sync
@@ -557,7 +557,7 @@ export class ModuleManager {
}
mutateConfigSafe<Module extends keyof Modules>(
name: Module
name: Module,
): Pick<ReturnType<Modules[Module]["schema"]>, "set" | "patch" | "overwrite" | "remove"> {
const module = this.modules[name];
const copy = structuredClone(this.configs());
@@ -602,7 +602,7 @@ export class ModuleManager {
throw e;
}
};
}
},
});
}
@@ -630,7 +630,7 @@ export class ModuleManager {
return {
version: this.version(),
...schemas
...schemas,
};
}
@@ -646,7 +646,7 @@ export class ModuleManager {
return {
version: this.version(),
...modules
...modules,
} as any;
}
}
@@ -654,7 +654,7 @@ export class ModuleManager {
export function getDefaultSchema() {
const schema = {
type: "object",
...transformObject(MODULES, (module) => module.prototype.getSchema())
...transformObject(MODULES, (module) => module.prototype.getSchema()),
};
return schema as any;

View File

@@ -12,7 +12,7 @@ export type ApiSchemaResponse = {
export class SystemApi extends ModuleApi<any> {
protected override getDefaultOptions(): Partial<any> {
return {
basepath: "/api/system"
basepath: "/api/system",
};
}
@@ -23,18 +23,18 @@ export class SystemApi extends ModuleApi<any> {
readSchema(options?: { config?: boolean; secrets?: boolean }) {
return this.get<ApiSchemaResponse>("schema", {
config: options?.config ? 1 : 0,
secrets: options?.secrets ? 1 : 0
secrets: options?.secrets ? 1 : 0,
});
}
setConfig<Module extends ModuleKey>(
module: Module,
value: ModuleConfigs[Module],
force?: boolean
force?: boolean,
) {
return this.post<ConfigUpdateResponse>(
["config", "set", module].join("/") + `?force=${force ? 1 : 0}`,
value
value,
);
}

View File

@@ -9,7 +9,7 @@ export {
type ModuleConfigs,
type ModuleSchemas,
MODULE_NAMES,
type ModuleKey
type ModuleKey,
} from "./ModuleManager";
export type { ModuleBuildContext } from "./Module";
@@ -17,5 +17,5 @@ export {
type PrimaryFieldType,
type BaseModuleApiOptions,
type ApiResponse,
ModuleApi
ModuleApi,
} from "./ModuleApi";

View File

@@ -17,18 +17,18 @@ export const migrations: Migration[] = [
{
version: 1,
//schema: true,
up: async (config) => config
up: async (config) => config,
},
{
version: 2,
up: async (config, { db }) => {
return config;
}
},
},
{
version: 3,
//schema: true,
up: async (config) => config
up: async (config) => config,
},
{
version: 4,
@@ -37,10 +37,10 @@ export const migrations: Migration[] = [
...config,
auth: {
...config.auth,
basepath: "/api/auth2"
}
basepath: "/api/auth2",
},
};
}
},
},
{
version: 5,
@@ -49,13 +49,13 @@ export const migrations: Migration[] = [
const cors = config.server.cors?.allow_methods ?? [];
set(config.server, "cors.allow_methods", [...new Set([...cors, "PATCH"])]);
return config;
}
},
},
{
version: 6,
up: async (config, { db }) => {
return config;
}
},
},
{
version: 7,
@@ -67,11 +67,11 @@ export const migrations: Migration[] = [
...config,
auth: {
...config.auth,
jwt
}
jwt,
},
};
}
}
},
},
/*{
version: 8,
up: async (config, { db }) => {
@@ -88,7 +88,7 @@ export async function migrateTo(
current: number,
to: number,
config: GenericConfigObject,
ctx: MigrationContext
ctx: MigrationContext,
): Promise<[number, GenericConfigObject]> {
//console.log("migrating from", current, "to", CURRENT_VERSION, config);
const todo = migrations.filter((m) => m.version > current && m.version <= to);
@@ -115,7 +115,7 @@ export async function migrateTo(
export async function migrate(
current: number,
config: GenericConfigObject,
ctx: MigrationContext
ctx: MigrationContext,
): Promise<[number, GenericConfigObject]> {
return migrateTo(current, CURRENT_VERSION, config, ctx);
}

View File

@@ -1,7 +1,7 @@
import { MediaAdapterRegistry } from "media";
const registries = {
media: MediaAdapterRegistry
media: MediaAdapterRegistry,
} as const;
export { registries };

View File

@@ -23,7 +23,7 @@ export type AdminControllerOptions = {
export class AdminController extends Controller {
constructor(
private readonly app: App,
private _options: AdminControllerOptions = {}
private _options: AdminControllerOptions = {},
) {
super();
}
@@ -36,7 +36,7 @@ export class AdminController extends Controller {
return {
...this._options,
basepath: this._options.basepath ?? "/",
assets_path: this._options.assets_path ?? config.server.assets_path
assets_path: this._options.assets_path ?? config.server.assets_path,
};
}
@@ -53,7 +53,7 @@ export class AdminController extends Controller {
const hono = this.create().use(
authMiddleware({
//skip: [/favicon\.ico$/]
})
}),
);
const auth = this.app.module.auth;
@@ -66,14 +66,14 @@ export class AdminController extends Controller {
success: configs.auth.cookie.pathSuccess ?? "/",
loggedOut: configs.auth.cookie.pathLoggedOut ?? "/",
login: "/auth/login",
logout: "/auth/logout"
logout: "/auth/logout",
};
hono.use("*", async (c, next) => {
const obj = {
user: c.get("auth")?.user,
logout_route: this.withBasePath(authRoutes.logout),
color_scheme: configs.server.admin.color_scheme
color_scheme: configs.server.admin.color_scheme,
};
const html = await this.getHtml(obj);
if (!html) {
@@ -97,11 +97,11 @@ export class AdminController extends Controller {
console.log("redirecting to success");
return c.redirect(authRoutes.success);
}
}
},
}),
async (c) => {
return c.html(c.get("html")!);
}
},
);
hono.get(authRoutes.logout, async (c) => {
@@ -119,16 +119,16 @@ export class AdminController extends Controller {
console.log("redirecting");
return c.redirect(authRoutes.login);
}
},
}),
permission(SystemPermissions.schemaRead, {
onDenied: async (c) => {
addFlashMessage(c, "You not allowed to read the schema", "warning");
}
},
}),
async (c) => {
return c.html(c.get("html")!);
}
},
);
return hono;
@@ -141,12 +141,12 @@ export class AdminController extends Controller {
if (this.options.html.includes(htmlBkndContextReplace)) {
return this.options.html.replace(
htmlBkndContextReplace,
"<script>" + bknd_context + "</script>"
"<script>" + bknd_context + "</script>",
);
}
console.warn(
`Custom HTML needs to include '${htmlBkndContextReplace}' to inject BKND context`
`Custom HTML needs to include '${htmlBkndContextReplace}' to inject BKND context`,
);
return this.options.html as string;
}
@@ -160,13 +160,13 @@ export class AdminController extends Controller {
const assets = {
js: "main.js",
css: "styles.css"
css: "styles.css",
};
if (isProd) {
// @ts-ignore
const manifest = await import("bknd/dist/manifest.json", {
assert: { type: "json" }
assert: { type: "json" },
});
// @todo: load all marked as entry (incl. css)
assets.js = manifest.default["src/ui/main.tsx"].file;
@@ -217,7 +217,7 @@ export class AdminController extends Controller {
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true`
window.__vite_plugin_react_preamble_installed__ = true`,
}}
/>
<script type="module" src={"/@vite/client"} />
@@ -235,7 +235,7 @@ export class AdminController extends Controller {
</div>
<script
dangerouslySetInnerHTML={{
__html: bknd_context
__html: bknd_context,
}}
/>
{!isProd && <script type="module" src={mainPath} />}
@@ -256,21 +256,21 @@ const style = (theme: AppTheme) => {
justifyContent: "center",
alignItems: "center",
"-webkit-font-smoothing": "antialiased",
"-moz-osx-font-smoothing": "grayscale"
"-moz-osx-font-smoothing": "grayscale",
};
const styles = {
light: {
color: "rgb(9,9,11)",
backgroundColor: "rgb(250,250,250)"
backgroundColor: "rgb(250,250,250)",
},
dark: {
color: "rgb(250,250,250)",
backgroundColor: "rgb(30,31,34)"
}
backgroundColor: "rgb(30,31,34)",
},
};
return {
...base,
...styles[theme === "light" ? "light" : "dark"]
...styles[theme === "light" ? "light" : "dark"],
};
};

View File

@@ -16,29 +16,29 @@ export const serverConfigSchema = Type.Object(
logo_return_path: Type.Optional(
Type.String({
default: "/",
description: "Path to return to after *clicking* the logo"
})
)
description: "Path to return to after *clicking* the logo",
}),
),
},
{ default: {}, additionalProperties: false }
{ default: {}, additionalProperties: false },
),
cors: Type.Object(
{
origin: Type.String({ default: "*" }),
allow_methods: Type.Array(StringEnum(serverMethods), {
default: serverMethods,
uniqueItems: true
uniqueItems: true,
}),
allow_headers: Type.Array(Type.String(), {
default: ["Content-Type", "Content-Length", "Authorization", "Accept"]
})
default: ["Content-Type", "Content-Length", "Authorization", "Accept"],
}),
},
{ default: {}, additionalProperties: false }
)
{ default: {}, additionalProperties: false },
),
},
{
additionalProperties: false
}
additionalProperties: false,
},
);
export type AppServerConfig = Static<typeof serverConfigSchema>;
@@ -70,8 +70,8 @@ export class AppServer extends Module<typeof serverConfigSchema> {
cors({
origin: this.config.cors.origin,
allowMethods: this.config.cors.allow_methods,
allowHeaders: this.config.cors.allow_headers
})
allowHeaders: this.config.cors.allow_headers,
}),
);
// add an initial fallback route
@@ -83,7 +83,7 @@ export class AppServer extends Module<typeof serverConfigSchema> {
if (new URL(c.req.url).pathname === "/") {
c.res = undefined;
c.res = Response.json({
bknd: "hello world!"
bknd: "hello world!",
});
}
}

View File

@@ -9,7 +9,7 @@ import {
datetimeStringLocal,
datetimeStringUTC,
getTimezone,
getTimezoneOffset
getTimezoneOffset,
} from "core/utils";
import { getRuntimeKey } from "core/utils";
import type { Context, Hono } from "hono";
@@ -19,7 +19,7 @@ import {
MODULE_NAMES,
type ModuleConfigs,
type ModuleKey,
getDefaultConfig
getDefaultConfig,
} from "modules/ModuleManager";
import * as SystemPermissions from "modules/permissions";
import { generateOpenAPI } from "modules/server/openapi";
@@ -64,8 +64,8 @@ export class SystemController extends Controller {
tb(
"query",
Type.Object({
secrets: Type.Optional(booleanLike)
})
secrets: Type.Optional(booleanLike),
}),
),
async (c) => {
// @todo: allow secrets if authenticated user is admin
@@ -81,11 +81,11 @@ export class SystemController extends Controller {
? {
version: this.app.version(),
module,
config: config[module]
config: config[module],
}
: config
: config,
);
}
},
);
async function handleConfigUpdateResponse(c: Context<any>, cb: () => Promise<ConfigUpdate>) {
@@ -97,7 +97,7 @@ export class SystemController extends Controller {
if (e instanceof TypeInvalidError) {
return c.json(
{ success: false, type: "type-invalid", errors: e.errors },
{ status: 400 }
{ status: 400 },
);
}
if (e instanceof Error) {
@@ -114,8 +114,8 @@ export class SystemController extends Controller {
tb(
"query",
Type.Object({
force: Type.Optional(booleanLike)
})
force: Type.Optional(booleanLike),
}),
),
async (c) => {
const module = c.req.param("module") as any;
@@ -129,7 +129,7 @@ export class SystemController extends Controller {
// force overwrite defined keys
const newConfig = {
...this.app.module[module].config,
...value
...value,
};
await this.app.mutateConfig(module).set(newConfig);
} else {
@@ -138,10 +138,10 @@ export class SystemController extends Controller {
return {
success: true,
module,
config: this.app.module[module].config
config: this.app.module[module].config,
};
});
}
},
);
hono.post("/add/:module/:path", permission(SystemPermissions.configWrite), async (c) => {
@@ -160,7 +160,7 @@ export class SystemController extends Controller {
return {
success: true,
module,
config: this.app.module[module].config
config: this.app.module[module].config,
};
});
});
@@ -176,7 +176,7 @@ export class SystemController extends Controller {
return {
success: true,
module,
config: this.app.module[module].config
config: this.app.module[module].config,
};
});
});
@@ -192,7 +192,7 @@ export class SystemController extends Controller {
return {
success: true,
module,
config: this.app.module[module].config
config: this.app.module[module].config,
};
});
});
@@ -207,7 +207,7 @@ export class SystemController extends Controller {
return {
success: true,
module,
config: this.app.module[module].config
config: this.app.module[module].config,
};
});
});
@@ -228,8 +228,8 @@ export class SystemController extends Controller {
"query",
Type.Object({
config: Type.Optional(booleanLike),
secrets: Type.Optional(booleanLike)
})
secrets: Type.Optional(booleanLike),
}),
),
async (c) => {
const module = c.req.param("module") as ModuleKey | undefined;
@@ -245,7 +245,7 @@ export class SystemController extends Controller {
module,
version,
schema: schema[module],
config: config ? this.app.module[module].toJSON(secrets) : undefined
config: config ? this.app.module[module].toJSON(secrets) : undefined,
});
}
@@ -254,9 +254,9 @@ export class SystemController extends Controller {
version,
schema,
config: config ? this.app.toJSON(secrets) : undefined,
permissions: this.app.modules.ctx().guard.getPermissionNames()
permissions: this.app.modules.ctx().guard.getPermissionNames(),
});
}
},
);
hono.post(
@@ -264,8 +264,8 @@ export class SystemController extends Controller {
tb(
"query",
Type.Object({
sync: Type.Optional(booleanLike)
})
sync: Type.Optional(booleanLike),
}),
),
async (c) => {
const { sync } = c.req.valid("query") as Record<string, boolean>;
@@ -273,7 +273,7 @@ export class SystemController extends Controller {
await this.app.build({ sync });
return c.json({ success: true, options: { sync } });
}
},
);
hono.get("/ping", (c) => c.json({ pong: true }));
@@ -286,9 +286,9 @@ export class SystemController extends Controller {
name: getTimezone(),
offset: getTimezoneOffset(),
local: datetimeStringLocal(),
utc: datetimeStringUTC()
}
})
utc: datetimeStringUTC(),
},
}),
);
hono.get("/openapi.json", async (c) => {

View File

@@ -22,14 +22,14 @@ function systemRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
content: {
"application/json": {
schema: Type.Object({
pong: Type.Boolean({ default: true })
})
}
}
}
pong: Type.Boolean({ default: true }),
}),
},
},
},
},
tags
}
tags,
},
},
"/config": {
get: {
@@ -45,14 +45,14 @@ function systemRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
data: Type.Object({}),
auth: Type.Object({}),
flows: Type.Object({}),
media: Type.Object({})
})
}
}
}
media: Type.Object({}),
}),
},
},
},
},
tags
}
tags,
},
},
"/schema": {
get: {
@@ -69,16 +69,16 @@ function systemRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
data: Type.Object({}),
auth: Type.Object({}),
flows: Type.Object({}),
media: Type.Object({})
})
})
}
}
}
media: Type.Object({}),
}),
}),
},
},
},
},
tags
}
}
tags,
},
},
};
return { paths: prefixPaths(paths, "/api/system") };
@@ -87,42 +87,42 @@ function systemRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
function dataRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
const schemas = {
entityData: Type.Object({
id: Type.Number() as any
})
id: Type.Number() as any,
}),
};
const repoManyResponses: OAS.ResponsesObject = {
"200": {
description: "List of entities",
content: {
"application/json": {
schema: Type.Array(schemas.entityData)
}
}
}
schema: Type.Array(schemas.entityData),
},
},
},
};
const repoSingleResponses: OAS.ResponsesObject = {
"200": {
description: "Entity",
content: {
"application/json": {
schema: schemas.entityData
}
}
}
schema: schemas.entityData,
},
},
},
};
const params = {
entity: {
name: "entity",
in: "path",
required: true,
schema: Type.String()
schema: Type.String(),
},
entityId: {
name: "id",
in: "path",
required: true,
schema: Type.Number() as any
}
schema: Type.Number() as any,
},
};
const tags = ["data"];
@@ -132,7 +132,7 @@ function dataRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
summary: "List entities",
parameters: [params.entity],
responses: repoManyResponses,
tags
tags,
},
post: {
summary: "Create entity",
@@ -140,20 +140,20 @@ function dataRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
requestBody: {
content: {
"application/json": {
schema: Type.Object({})
}
}
schema: Type.Object({}),
},
},
},
responses: repoSingleResponses,
tags
}
tags,
},
},
"/entity/{entity}/{id}": {
get: {
summary: "Get entity",
parameters: [params.entity, params.entityId],
responses: repoSingleResponses,
tags
tags,
},
patch: {
summary: "Update entity",
@@ -161,24 +161,24 @@ function dataRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
requestBody: {
content: {
"application/json": {
schema: Type.Object({})
}
}
schema: Type.Object({}),
},
},
},
responses: repoSingleResponses,
tags
tags,
},
delete: {
summary: "Delete entity",
parameters: [params.entity, params.entityId],
responses: {
"200": {
description: "Entity deleted"
}
description: "Entity deleted",
},
},
tags
}
}
tags,
},
},
};
return { paths: prefixPaths(paths, config.data.basepath!) };
@@ -189,8 +189,8 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
user: Type.Object({
id: Type.String(),
email: Type.String(),
name: Type.String()
})
name: Type.String(),
}),
};
const tags = ["auth"];
@@ -203,10 +203,10 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
"application/json": {
schema: Type.Object({
email: Type.String(),
password: Type.String()
})
}
}
password: Type.String(),
}),
},
},
},
responses: {
"200": {
@@ -214,14 +214,14 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
content: {
"application/json": {
schema: Type.Object({
user: schemas.user
})
}
}
}
user: schemas.user,
}),
},
},
},
},
tags
}
tags,
},
},
"/password/register": {
post: {
@@ -231,10 +231,10 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
"application/json": {
schema: Type.Object({
email: Type.String(),
password: Type.String()
})
}
}
password: Type.String(),
}),
},
},
},
responses: {
"200": {
@@ -242,14 +242,14 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
content: {
"application/json": {
schema: Type.Object({
user: schemas.user
})
}
}
}
user: schemas.user,
}),
},
},
},
},
tags
}
tags,
},
},
"/me": {
get: {
@@ -260,14 +260,14 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
content: {
"application/json": {
schema: Type.Object({
user: schemas.user
})
}
}
}
user: schemas.user,
}),
},
},
},
},
tags
}
tags,
},
},
"/strategies": {
get: {
@@ -278,15 +278,15 @@ function authRoutes(config: ModuleConfigs): { paths: OAS.Document["paths"] } {
content: {
"application/json": {
schema: Type.Object({
strategies: Type.Object({})
})
}
}
}
strategies: Type.Object({}),
}),
},
},
},
},
tags
}
}
tags,
},
},
};
return { paths: prefixPaths(paths, config.auth.basepath!) };
@@ -301,12 +301,12 @@ export function generateOpenAPI(config: ModuleConfigs): OAS.Document {
openapi: "3.1.0",
info: {
title: "bknd API",
version: "0.0.0"
version: "0.0.0",
},
paths: {
...system.paths,
...data.paths,
...auth.paths
}
...auth.paths,
},
};
}