Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@busy-hour/blaze

Package Overview
Dependencies
Maintainers
1
Versions
54
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@busy-hour/blaze - npm Package Compare versions

Comparing version 2.0.3 to 3.0.0-0

dist/cjs/config/BlazeDependency.js

25

CHANGELOG.md

@@ -5,2 +5,27 @@ # Changelog

## [3.0.0-0](https://github.com/Busy-Hour-Studio/blaze/compare/v2.0.3...v3.0.0-0) (2024-04-21)
### ⚠ BREAKING CHANGES
* blaze router flow
* blaze router flow ([a50dd13](https://github.com/Busy-Hour-Studio/blaze/commit/a50dd13e296cc5e270b45c0e1784a95118652dbd))
### Features
* custom definitions supports ([22d8f70](https://github.com/Busy-Hour-Studio/blaze/commit/22d8f704ed70e2a04778a64ce5e68719f8c6b43c))
* exposed fetch method ([fccf321](https://github.com/Busy-Hour-Studio/blaze/commit/fccf3211bf9a8dce89f0db19031b13287f535445))
* typescript plugin type helper ([fff4ac8](https://github.com/Busy-Hour-Studio/blaze/commit/fff4ac866021970b0c5e0cec272df03d0a4770ef))
### Bug Fixes
* esm service loader ([8a21bee](https://github.com/Busy-Hour-Studio/blaze/commit/8a21bee5f7163a4eac7652f6babca13936da8764))
* exports validator/handler type extractor ([343db2b](https://github.com/Busy-Hour-Studio/blaze/commit/343db2b18417af55bfd34de271fd0b98de518c91))
* type definitions reference errors ([7152158](https://github.com/Busy-Hour-Studio/blaze/commit/71521580a26134337c9b271751e52aa013afd19b))
* typos on type names ([88b775c](https://github.com/Busy-Hour-Studio/blaze/commit/88b775c4d8b62fa02f4b48ab6df31c53f0162419))
* wrong imported module ([4c251b3](https://github.com/Busy-Hour-Studio/blaze/commit/4c251b3c142ce643a687a6de5d1a4f3588c41c3d))
## [2.0.3](https://github.com/Busy-Hour-Studio/blaze/compare/v2.0.2...v2.0.3) (2024-04-19)

@@ -7,0 +32,0 @@

10

dist/cjs/event/BlazeBroker.js

@@ -42,11 +42,7 @@ "use strict";

}
// eslint-disable-next-line no-use-before-define, @typescript-eslint/no-shadow
async call(eventName, ...values) {
this.validateEventName(eventName);
return import__.BlazeEvent.emitAsync(eventName, ...values);
const results = await import__.BlazeEvent.emitAsync(eventName, ...values);
return results[0];
}
// eslint-disable-next-line no-use-before-define, @typescript-eslint/no-shadow
async mcall(...args) {
return Promise.all(args.map((values) => this.call(...values)));
}
emit(eventName, ...values) {

@@ -57,3 +53,3 @@ return import__.BlazeEvent.emit(eventName, ...values);

const evtName = [import_constant.RESERVED_KEYWORD.PREFIX.EVENT, eventName].join(".");
return this.emit(evtName, ...values);
return import__.BlazeEvent.emit(evtName, ...values);
}

@@ -60,0 +56,0 @@ }

@@ -51,8 +51,7 @@ "use strict";

isRest;
broker = import__.BlazeBroker;
broker;
// Aliases for broker
call = import__.BlazeBroker.call.bind(import__.BlazeBroker);
mcall = import__.BlazeBroker.mcall.bind(import__.BlazeBroker);
emit = import__.BlazeBroker.emit.bind(import__.BlazeBroker);
event = import__.BlazeBroker.event.bind(import__.BlazeBroker);
call;
emit;
event;
constructor(options) {

@@ -72,2 +71,6 @@ const { honoCtx, body, params, headers, validations } = options;

this.validations = validations;
this.broker = import__.BlazeBroker;
this.call = import__.BlazeBroker.call.bind(import__.BlazeBroker);
this.emit = import__.BlazeBroker.emit.bind(import__.BlazeBroker);
this.event = import__.BlazeBroker.event.bind(import__.BlazeBroker);
}

@@ -74,0 +77,0 @@ get query() {

@@ -18,9 +18,10 @@ "use strict";

};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var src_exports = {};
__export(src_exports, {
Blaze: () => import_router.Blaze,
BlazeCreator: () => import_creator.BlazeCreator,
BlazeError: () => import_BlazeError.BlazeError,
initializeServices: () => import_setup.initializeServices
initializeServices: () => import_setup.initializeServices,
z: () => import_router.z
});

@@ -30,10 +31,11 @@ module.exports = __toCommonJS(src_exports);

var import_BlazeError = require("./errors/BlazeError");
__reExport(src_exports, require("./router"), module.exports);
var import_router = require("./router");
var import_setup = require("./utils/setup");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Blaze,
BlazeCreator,
BlazeError,
initializeServices,
...require("./router")
z
});
"use strict";
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;

@@ -18,2 +20,10 @@ var __export = (target, all) => {

};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

@@ -25,69 +35,98 @@ var Blaze_exports = {};

module.exports = __toCommonJS(Blaze_exports);
var import_zod_to_openapi = require("@asteasolutions/zod-to-openapi");
var import_hono = require("hono");
var import_router = require("../utils/helper/router");
class Blaze extends import_hono.Hono {
openAPIRegistry;
var import_node_fs = __toESM(require("node:fs"), 1);
var import_config = require("../config");
var import_BlazeError = require("../errors/BlazeError");
var import_event = require("../event");
var import_common = require("../utils/common");
var import_service2 = require("../utils/setup/service");
var import_BlazeRouter = require("./BlazeRouter");
class Blaze {
services;
router;
doc;
doc31;
blazeCtx;
fetch;
constructor(options) {
super({ strict: false, router: options.router });
this.openAPIRegistry = new import_zod_to_openapi.OpenAPIRegistry();
this.services = [];
this.router = new import_BlazeRouter.BlazeRouter(options);
this.doc = this.router.doc.bind(this.router);
this.doc31 = this.router.doc31.bind(this.router);
this.blazeCtx = new import_event.BlazeContext({
body: null,
params: null,
headers: null,
honoCtx: null,
validations: null
});
this.fetch = this.router.fetch.bind(this.router);
if (options.path) {
this.load({
path: options.path,
autoStart: options.autoStart
});
}
}
openapi(route) {
let method = route.method ? route.method.toLowerCase() : "post";
method = method === "all" ? "post" : method;
const newRoute = {
...route,
method
};
this.openAPIRegistry.registerPath(newRoute);
this.on(route.method, route.path, route.handler);
/**
* Start all the loaded services
* @example
* ```ts
* app.start()
* ```
* passing `autoStart: true` on app creation (`new Blaze({ autoStart: true })`) will also start all the services
*/
start() {
this.services.forEach((service) => service.onStarted());
}
getOpenAPIDocument(config) {
const generator = new import_zod_to_openapi.OpenApiGeneratorV3(this.openAPIRegistry.definitions);
const document = generator.generateDocument(config);
return document;
}
getOpenAPI31Document(config) {
const generator = new import_zod_to_openapi.OpenApiGeneratorV31(this.openAPIRegistry.definitions);
const document = generator.generateDocument(config);
return document;
}
off(method, path) {
const index = this.router.routes.findIndex(
(route) => route[0] === method && route[1] === path
/**
* `load` load all the services from the given path
* @example
* ```ts
* app.load({
* path: path.resolve(__dirname, 'services'),
* autoStart: true
* })
* ```
* `autoStart` options will start all the services when all the services are loaded
*/
async load(options) {
if (!import_node_fs.default.existsSync(options.path)) {
throw new import_BlazeError.BlazeError("Service path doesn't exist");
}
const serviceFiles = import_node_fs.default.readdirSync(options.path);
const services = await Promise.all(
serviceFiles.map((servicePath) => {
const service = import_service2.BlazeService.create({
app: this.router,
servicePath,
blazeCtx: this.blazeCtx,
sourcePath: options.path
});
return service;
})
);
if (index === -1)
this.services.push(...services);
if (!options.autoStart)
return;
this.router.routes.splice(index, 1);
this.start();
}
doc(path, config) {
this.get(path, (ctx) => {
try {
const document = this.getOpenAPIDocument(config);
return ctx.json(document);
} catch (e) {
return ctx.json(e, 500);
}
});
getServeConfig(port, listener) {
const config = {
fetch: this.router.fetch,
port
};
return [config, listener];
}
doc31(path, config) {
this.get(path, (ctx) => {
try {
const document = this.getOpenAPI31Document(config);
return ctx.json(document);
} catch (e) {
return ctx.json(e, 500);
serve(port, listener) {
if (!(0, import_common.isNil)(port)) {
const args = this.getServeConfig(port, listener);
if (import_config.BlazeDependency.runTime === "node" && import_config.BlazeDependency.moduleExist["node-adapter"]) {
import_config.BlazeDependency.nodeAdapter.serve(...args);
}
});
}
route(path, app) {
super.route(path, app);
if (!(app instanceof Blaze)) {
return this;
if ((0, import_common.isNil)(listener)) {
return args[0];
}
return args;
}
const docPath = path.replaceAll(/:([^/]+)/g, "{$1}");
app.openAPIRegistry.definitions.forEach((def) => {
(0, import_router.assignOpenAPIRegistry)(this, docPath, def);
});
return this;
return this.router.fetch;
}

@@ -94,0 +133,0 @@ }

@@ -22,2 +22,3 @@ "use strict";

Blaze: () => import_Blaze.Blaze,
BlazeRouter: () => import_BlazeRouter.BlazeRouter,
z: () => import_validator.z

@@ -27,2 +28,3 @@ });

var import_Blaze = require("./Blaze");
var import_BlazeRouter = require("./BlazeRouter");
var import_validator = require("./validator");

@@ -32,3 +34,4 @@ // Annotate the CommonJS export names for ESM import in node:

Blaze,
BlazeRouter,
z
});

@@ -25,6 +25,6 @@ "use strict";

var import_url = require("hono/utils/url");
function assignOpenAPIRegistry(blaze, docPath, def) {
function assignOpenAPIRegistry(router, docPath, def) {
switch (def.type) {
case "component":
return blaze.openAPIRegistry.registerComponent(
return router.openAPIRegistry.registerComponent(
def.componentType,

@@ -35,3 +35,3 @@ def.name,

case "route":
return blaze.openAPIRegistry.registerPath({
return router.openAPIRegistry.registerPath({
...def.route,

@@ -41,3 +41,3 @@ path: (0, import_url.mergePath)(docPath, def.route.path)

case "webhook":
return blaze.openAPIRegistry.registerWebhook({
return router.openAPIRegistry.registerWebhook({
...def.webhook,

@@ -47,3 +47,3 @@ path: (0, import_url.mergePath)(docPath, def.webhook.path)

case "schema":
return blaze.openAPIRegistry.register(
return router.openAPIRegistry.register(
def.schema._def.openapi._internal.refId,

@@ -53,3 +53,3 @@ def.schema

case "parameter":
return blaze.openAPIRegistry.registerParameter(
return router.openAPIRegistry.registerParameter(
def.schema._def.openapi._internal.refId,

@@ -56,0 +56,0 @@ def.schema

@@ -25,4 +25,4 @@ "use strict";

var import_common = require("../common");
function loadService(filePath) {
const file = (0, import_common.require)(filePath);
async function loadService(filePath) {
const file = await import(filePath);
let service;

@@ -29,0 +29,0 @@ if (

@@ -38,3 +38,3 @@ "use strict";

var import_service = require("./setup/service");
function initializeServices(options) {
async function initializeServices(options) {
const { app, path: sourcePath } = options;

@@ -52,11 +52,13 @@ if (!import_node_fs.default.existsSync(sourcePath)) {

const serviceFiles = import_node_fs.default.readdirSync(sourcePath);
const pendingServices = serviceFiles.map((servicePath) => {
const service = import_service.BlazeService.create({
app,
servicePath,
blazeCtx,
sourcePath
});
return service;
});
const pendingServices = await Promise.all(
serviceFiles.map(async (servicePath) => {
const service = import_service.BlazeService.create({
app,
servicePath,
blazeCtx,
sourcePath
});
return service;
})
);
pendingServices.forEach((service) => service.onStarted());

@@ -63,0 +65,0 @@ }

@@ -110,3 +110,3 @@ "use strict";

if (validator?.header) {
request.headers = validator.header;
request.header = validator.header;
}

@@ -113,0 +113,0 @@ return {

@@ -36,3 +36,3 @@ "use strict";

var import_event = require("../../event");
var import_router = require("../../router");
var import_BlazeRouter = require("../../router/BlazeRouter");
var import_common = require("../common");

@@ -55,2 +55,3 @@ var import_service = require("../helper/service");

service;
isStarted;
constructor(options) {

@@ -64,2 +65,3 @@ const { service, blazeCtx, servicePath, app } = options;

this.mainRouter = app;
this.isStarted = false;
this.actions = [];

@@ -75,3 +77,3 @@ this.events = [];

if (!this.router) {
this.router = new import_router.Blaze({
this.router = new import_BlazeRouter.BlazeRouter({
router: this.service.router

@@ -141,8 +143,11 @@ });

onStarted() {
if (this.isStarted)
return;
this.assignRestRoute();
this.service.onStarted?.(this.blazeCtx);
this.isStarted = true;
}
static create(options) {
static async create(options) {
const servicePath = import_node_path.default.resolve(options.sourcePath, options.servicePath);
const serviceFile = (0, import_service.loadService)(servicePath);
const serviceFile = await (0, import_service.loadService)(servicePath);
const service = new BlazeService({

@@ -149,0 +154,0 @@ app: options.app,

@@ -20,11 +20,7 @@ // src/event/BlazeBroker.ts

}
// eslint-disable-next-line no-use-before-define, @typescript-eslint/no-shadow
async call(eventName, ...values) {
this.validateEventName(eventName);
return BlazeEvent.emitAsync(eventName, ...values);
const results = await BlazeEvent.emitAsync(eventName, ...values);
return results[0];
}
// eslint-disable-next-line no-use-before-define, @typescript-eslint/no-shadow
async mcall(...args) {
return Promise.all(args.map((values) => this.call(...values)));
}
emit(eventName, ...values) {

@@ -35,3 +31,3 @@ return BlazeEvent.emit(eventName, ...values);

const evtName = [RESERVED_KEYWORD.PREFIX.EVENT, eventName].join(".");
return this.emit(evtName, ...values);
return BlazeEvent.emit(evtName, ...values);
}

@@ -38,0 +34,0 @@ };

@@ -23,8 +23,7 @@ // src/event/BlazeContext.ts

isRest;
broker = BlazeBroker;
broker;
// Aliases for broker
call = BlazeBroker.call.bind(BlazeBroker);
mcall = BlazeBroker.mcall.bind(BlazeBroker);
emit = BlazeBroker.emit.bind(BlazeBroker);
event = BlazeBroker.event.bind(BlazeBroker);
call;
emit;
event;
constructor(options) {

@@ -44,2 +43,6 @@ const { honoCtx, body, params, headers, validations } = options;

this.validations = validations;
this.broker = BlazeBroker;
this.call = BlazeBroker.call.bind(BlazeBroker);
this.emit = BlazeBroker.emit.bind(BlazeBroker);
this.event = BlazeBroker.event.bind(BlazeBroker);
}

@@ -46,0 +49,0 @@ get query() {

// src/index.ts
import { BlazeCreator } from "./creator/index.js";
import { BlazeError } from "./errors/BlazeError.js";
export * from "./router/index.js";
import { Blaze, z } from "./router/index.js";
import { initializeServices } from "./utils/setup.js";
export {
Blaze,
BlazeCreator,
BlazeError,
initializeServices
initializeServices,
z
};
// src/router/Blaze.ts
import {
OpenAPIRegistry,
OpenApiGeneratorV3,
OpenApiGeneratorV31
} from "@asteasolutions/zod-to-openapi";
import { Hono } from "hono";
import { assignOpenAPIRegistry } from "../utils/helper/router.js";
var Blaze = class _Blaze extends Hono {
openAPIRegistry;
import fs from "node:fs";
import { BlazeDependency } from "../config/index.js";
import { BlazeError } from "../errors/BlazeError.js";
import { BlazeContext } from "../event/index.js";
import { isNil } from "../utils/common.js";
import { BlazeService } from "../utils/setup/service.js";
import { BlazeRouter } from "./BlazeRouter.js";
var Blaze = class {
services;
router;
doc;
doc31;
blazeCtx;
fetch;
constructor(options) {
super({ strict: false, router: options.router });
this.openAPIRegistry = new OpenAPIRegistry();
this.services = [];
this.router = new BlazeRouter(options);
this.doc = this.router.doc.bind(this.router);
this.doc31 = this.router.doc31.bind(this.router);
this.blazeCtx = new BlazeContext({
body: null,
params: null,
headers: null,
honoCtx: null,
validations: null
});
this.fetch = this.router.fetch.bind(this.router);
if (options.path) {
this.load({
path: options.path,
autoStart: options.autoStart
});
}
}
openapi(route) {
let method = route.method ? route.method.toLowerCase() : "post";
method = method === "all" ? "post" : method;
const newRoute = {
...route,
method
};
this.openAPIRegistry.registerPath(newRoute);
this.on(route.method, route.path, route.handler);
/**
* Start all the loaded services
* @example
* ```ts
* app.start()
* ```
* passing `autoStart: true` on app creation (`new Blaze({ autoStart: true })`) will also start all the services
*/
start() {
this.services.forEach((service) => service.onStarted());
}
getOpenAPIDocument(config) {
const generator = new OpenApiGeneratorV3(this.openAPIRegistry.definitions);
const document = generator.generateDocument(config);
return document;
}
getOpenAPI31Document(config) {
const generator = new OpenApiGeneratorV31(this.openAPIRegistry.definitions);
const document = generator.generateDocument(config);
return document;
}
off(method, path) {
const index = this.router.routes.findIndex(
(route) => route[0] === method && route[1] === path
/**
* `load` load all the services from the given path
* @example
* ```ts
* app.load({
* path: path.resolve(__dirname, 'services'),
* autoStart: true
* })
* ```
* `autoStart` options will start all the services when all the services are loaded
*/
async load(options) {
if (!fs.existsSync(options.path)) {
throw new BlazeError("Service path doesn't exist");
}
const serviceFiles = fs.readdirSync(options.path);
const services = await Promise.all(
serviceFiles.map((servicePath) => {
const service = BlazeService.create({
app: this.router,
servicePath,
blazeCtx: this.blazeCtx,
sourcePath: options.path
});
return service;
})
);
if (index === -1)
this.services.push(...services);
if (!options.autoStart)
return;
this.router.routes.splice(index, 1);
this.start();
}
doc(path, config) {
this.get(path, (ctx) => {
try {
const document = this.getOpenAPIDocument(config);
return ctx.json(document);
} catch (e) {
return ctx.json(e, 500);
}
});
getServeConfig(port, listener) {
const config = {
fetch: this.router.fetch,
port
};
return [config, listener];
}
doc31(path, config) {
this.get(path, (ctx) => {
try {
const document = this.getOpenAPI31Document(config);
return ctx.json(document);
} catch (e) {
return ctx.json(e, 500);
serve(port, listener) {
if (!isNil(port)) {
const args = this.getServeConfig(port, listener);
if (BlazeDependency.runTime === "node" && BlazeDependency.moduleExist["node-adapter"]) {
BlazeDependency.nodeAdapter.serve(...args);
}
});
}
route(path, app) {
super.route(path, app);
if (!(app instanceof _Blaze)) {
return this;
if (isNil(listener)) {
return args[0];
}
return args;
}
const docPath = path.replaceAll(/:([^/]+)/g, "{$1}");
app.openAPIRegistry.definitions.forEach((def) => {
assignOpenAPIRegistry(this, docPath, def);
});
return this;
return this.router.fetch;
}

@@ -74,0 +99,0 @@ };

// src/router/index.ts
import { Blaze } from "./Blaze.js";
import { BlazeRouter } from "./BlazeRouter.js";
import { z } from "./validator.js";
export {
Blaze,
BlazeRouter,
z
};
// src/utils/helper/router.ts
import { mergePath } from "hono/utils/url";
function assignOpenAPIRegistry(blaze, docPath, def) {
function assignOpenAPIRegistry(router, docPath, def) {
switch (def.type) {
case "component":
return blaze.openAPIRegistry.registerComponent(
return router.openAPIRegistry.registerComponent(
def.componentType,

@@ -12,3 +12,3 @@ def.name,

case "route":
return blaze.openAPIRegistry.registerPath({
return router.openAPIRegistry.registerPath({
...def.route,

@@ -18,3 +18,3 @@ path: mergePath(docPath, def.route.path)

case "webhook":
return blaze.openAPIRegistry.registerWebhook({
return router.openAPIRegistry.registerWebhook({
...def.webhook,

@@ -24,3 +24,3 @@ path: mergePath(docPath, def.webhook.path)

case "schema":
return blaze.openAPIRegistry.register(
return router.openAPIRegistry.register(
def.schema._def.openapi._internal.refId,

@@ -30,3 +30,3 @@ def.schema

case "parameter":
return blaze.openAPIRegistry.registerParameter(
return router.openAPIRegistry.registerParameter(
def.schema._def.openapi._internal.refId,

@@ -33,0 +33,0 @@ def.schema

// src/utils/helper/service.ts
import { hasOwnProperty, require as require2 } from "../common.js";
function loadService(filePath) {
const file = require2(filePath);
import { hasOwnProperty } from "../common.js";
async function loadService(filePath) {
const file = await import(filePath);
let service;

@@ -6,0 +6,0 @@ if (

@@ -6,3 +6,3 @@ // src/utils/setup.ts

import { BlazeService } from "./setup/service.js";
function initializeServices(options) {
async function initializeServices(options) {
const { app, path: sourcePath } = options;

@@ -20,11 +20,13 @@ if (!fs.existsSync(sourcePath)) {

const serviceFiles = fs.readdirSync(sourcePath);
const pendingServices = serviceFiles.map((servicePath) => {
const service = BlazeService.create({
app,
servicePath,
blazeCtx,
sourcePath
});
return service;
});
const pendingServices = await Promise.all(
serviceFiles.map(async (servicePath) => {
const service = BlazeService.create({
app,
servicePath,
blazeCtx,
sourcePath
});
return service;
})
);
pendingServices.forEach((service) => service.onStarted());

@@ -31,0 +33,0 @@ }

@@ -92,3 +92,3 @@ // src/utils/setup/rest.ts

if (validator?.header) {
request.headers = validator.header;
request.header = validator.header;
}

@@ -95,0 +95,0 @@ return {

// src/utils/setup/service.ts
import path from "node:path";
import { BlazeEvent } from "../../event/index.js";
import { Blaze } from "../../router/index.js";
import { BlazeRouter } from "../../router/BlazeRouter.js";
import { getRestPath, getServiceName } from "../common.js";

@@ -22,2 +22,3 @@ import { loadService } from "../helper/service.js";

service;
isStarted;
constructor(options) {

@@ -31,2 +32,3 @@ const { service, blazeCtx, servicePath, app } = options;

this.mainRouter = app;
this.isStarted = false;
this.actions = [];

@@ -42,3 +44,3 @@ this.events = [];

if (!this.router) {
this.router = new Blaze({
this.router = new BlazeRouter({
router: this.service.router

@@ -108,8 +110,11 @@ });

onStarted() {
if (this.isStarted)
return;
this.assignRestRoute();
this.service.onStarted?.(this.blazeCtx);
this.isStarted = true;
}
static create(options) {
static async create(options) {
const servicePath = path.resolve(options.sourcePath, options.servicePath);
const serviceFile = loadService(servicePath);
const serviceFile = await loadService(servicePath);
const service = new _BlazeService({

@@ -116,0 +121,0 @@ app: options.app,

import type { BlazeActionCreator, BlazeEventCreator, BlazeServiceCreator } from '../types/creator';
/**
* Create Blaze service, action, event, etc.
* @deprecated use "satifies Service, Action, Event, etc." instead to support type safe code with "@busy-hour/blaze-type"
*/
export declare const BlazeCreator: {

@@ -3,0 +7,0 @@ service: BlazeServiceCreator;

import type { ActionCallResult as Result } from '../types/action';
import type { ActionCallRecord, ActionEventCallRequest, EventCallRecord } from '../types/common';
import type { EventName } from '../types/event';

@@ -6,6 +7,11 @@ export declare class BlazeBroker {

private validateEventName;
call<T, U = T extends Array<infer T> ? Result<T> : Result<T>>(eventName: EventName, ...values: unknown[]): Promise<U[]>;
mcall<T, U = T extends Array<infer T> ? Result<T> : Result<T>>(...args: [eventName: EventName, ...values: unknown[]][]): Promise<U[][]>;
emit(eventName: EventName, ...values: unknown[]): boolean;
event(eventName: EventName, ...values: unknown[]): boolean;
call<T extends keyof ActionCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = ActionCallRecord[T], V = Result<U['result']>>(eventName: T, body: U['body']): Promise<V>;
call<T extends keyof ActionCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = ActionCallRecord[T], V = Result<U['result']>>(eventName: T, body: U['body'], params: U['params']): Promise<V>;
call<T extends keyof ActionCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = ActionCallRecord[T], V = Result<U['result']>>(eventName: T, body: U['body'], params: U['params'], headers: U['headers']): Promise<V>;
emit<T extends keyof ActionCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = ActionCallRecord[T]>(eventName: T, body: U['body']): boolean;
emit<T extends keyof ActionCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = ActionCallRecord[T]>(eventName: T, body: U['body'], params: U['params']): boolean;
emit<T extends keyof ActionCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = ActionCallRecord[T]>(eventName: T, body: U['body'], params: U['params'], headers: U['headers']): boolean;
event<T extends keyof EventCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = EventCallRecord[T]>(eventName: T, body: U['body']): boolean;
event<T extends keyof EventCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = EventCallRecord[T]>(eventName: T, body: U['body'], params: U['params']): boolean;
event<T extends keyof EventCallRecord | (string & NonNullable<unknown>), U extends ActionEventCallRequest = EventCallRecord[T]>(eventName: T, body: U['body'], params: U['params'], headers: U['headers']): boolean;
}

@@ -8,2 +8,3 @@ /// <reference types="node" />

import type { ResponseType } from '../types/rest';
import { BlazeBroker as Broker } from './BlazeBroker';
export declare class BlazeContext<Meta extends RecordUnknown = RecordUnknown, Body extends RecordUnknown = RecordUnknown, Params extends RecordUnknown = RecordUnknown, Headers extends RecordString = RecordString> {

@@ -22,7 +23,6 @@ private readonly $honoCtx;

readonly isRest: boolean;
readonly broker: import("./BlazeBroker").BlazeBroker;
readonly call: <T, U = T extends (infer T_1)[] ? import("../types/action").ActionCallResult<T_1> : import("../types/action").ActionCallResult<T>>(eventName: string, ...values: unknown[]) => Promise<U[]>;
readonly mcall: <T, U = T extends (infer T_1)[] ? import("../types/action").ActionCallResult<T_1> : import("../types/action").ActionCallResult<T>>(...args: [eventName: string, ...values: unknown[]][]) => Promise<U[][]>;
readonly emit: (eventName: string, ...values: unknown[]) => boolean;
readonly event: (eventName: string, ...values: unknown[]) => boolean;
readonly broker: Broker;
readonly call: Broker['call'];
readonly emit: Broker['emit'];
readonly event: Broker['event'];
constructor(options: ContextConstructorOption<Body, Params, Headers>);

@@ -29,0 +29,0 @@ get query(): qs.ParsedUrlQuery;

export type { Action, ActionHandler, ActionOpenAPI, ActionValidator, Actions, OpenAPIBody, } from './types/action';
export type { ActionCallRecord, ActionEventCallRequest, EventCallRecord, ExtractActionHandler, ExtractActionValidator, ExtractEventValidator, } from './types/common';
export type { Event, Events } from './types/event';

@@ -8,3 +9,3 @@ export type { AcceptedAfterHook, AcceptedBeforeHook, ActionHook, } from './types/hooks';

export { BlazeError } from './errors/BlazeError';
export * from './router';
export { Blaze, z } from './router';
export { initializeServices } from './utils/setup';

@@ -1,17 +0,60 @@

import { OpenAPIRegistry, OpenApiGeneratorV3, OpenApiGeneratorV31 } from '@asteasolutions/zod-to-openapi';
import type { OpenAPIObjectConfig } from '@asteasolutions/zod-to-openapi/dist/v3.0/openapi-generator';
import type { Env, Schema } from 'hono';
import { Hono } from 'hono';
import type { MergePath, MergeSchemaPath } from 'hono/types';
import type { BlazeOpenAPIOption, CreateBlazeOption } from '../types/router';
export declare class Blaze<E extends Env = Env, S extends Schema = NonNullable<unknown>, BasePath extends string = '/'> extends Hono<E, S, BasePath> {
readonly openAPIRegistry: OpenAPIRegistry;
/// <reference types="node" />
import { AddressInfo } from 'node:net';
import type { BlazeFetch, CreateBlazeOption } from '../types/router';
import { LoadServicesOption } from '../types/service';
import { BlazeService } from '../utils/setup/service';
import { BlazeRouter } from './BlazeRouter';
export declare class Blaze {
readonly services: BlazeService[];
readonly router: BlazeRouter;
readonly doc: BlazeRouter['doc'];
readonly doc31: BlazeRouter['doc31'];
private readonly blazeCtx;
readonly fetch: BlazeFetch;
constructor(options: CreateBlazeOption);
openapi(route: BlazeOpenAPIOption): void;
getOpenAPIDocument(config: OpenAPIObjectConfig): ReturnType<OpenApiGeneratorV3['generateDocument']>;
getOpenAPI31Document(config: OpenAPIObjectConfig): ReturnType<OpenApiGeneratorV31['generateDocument']>;
off(method: string, path: string): void;
doc(path: string, config: OpenAPIObjectConfig): void;
doc31(path: string, config: OpenAPIObjectConfig): void;
route<SubPath extends string, SubEnv extends Env, SubSchema extends Schema, SubBasePath extends string>(path: SubPath, app?: Blaze<SubEnv, SubSchema, SubBasePath> | undefined): Blaze<E, MergeSchemaPath<SubSchema, MergePath<BasePath, SubPath>> & S, BasePath>;
/**
* Start all the loaded services
* @example
* ```ts
* app.start()
* ```
* passing `autoStart: true` on app creation (`new Blaze({ autoStart: true })`) will also start all the services
*/
start(): void;
/**
* `load` load all the services from the given path
* @example
* ```ts
* app.load({
* path: path.resolve(__dirname, 'services'),
* autoStart: true
* })
* ```
* `autoStart` options will start all the services when all the services are loaded
*/
load(options: LoadServicesOption): Promise<void>;
private getServeConfig;
/**
* Start the server at the given port
* @param listener - [Only for Node] a listener that will be called when the server is started.
* @example
* ```ts
* // Start server at port 3000
* app.serve(3000)
*
* // Pass a listener after server started
* app.serve(3000, (addressInfo) => {
* console.log(`Server started at ${addressInfo.address}:${addressInfo.port}`)
* })
* ```
*/
serve(): BlazeFetch;
serve(port: number): {
fetch: BlazeFetch;
port: number;
};
serve<Listener extends (addressInfo: AddressInfo) => void>(port: number, listener: Listener): [{
fetch: BlazeFetch;
port: number;
}, Listener];
}
export { Blaze } from './Blaze';
export { BlazeRouter } from './BlazeRouter';
export { z } from './validator';

@@ -8,7 +8,73 @@ import type { ZodObject, ZodRawShape } from 'zod';

export interface BlazeActionCreator {
/**
* Create a reuseable action for services.
* @example
* ```ts
* const action = BlazeCreator.action({
* rest: 'POST /',
* async handler(ctx) {
* const body = await ctx.request.body()
* }
* })
* ```
*/
<Meta extends RecordUnknown = RecordUnknown, Header extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, Body extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, Params extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>>(action: Action<Meta, Header, Body, Params>): Action<Meta, Header, Body, Params>;
/**
* Create a reuseable validator for actions body, params and headers.
* @example
* ```ts
* const validator = BlazeCreator.action.validator({
* header: z.object({
* token: z.string(),
* })
* })
* ```
*/
validator<Header extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, Body extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, Params extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>>(validator: ActionValidator<Header, Body, Params>): ActionValidator<Header, Body, Params>;
/**
* Create an openai spec for action.
* @example
* ```ts
* const openapi = BlazeCreator.action.openapi({
* responses: {
* 200: {
* description: 'Get user with email N',
* },
* 400: {
* description: 'Bad Request',
* },
* },
* })
* ```
*/
openapi(openapi: ActionOpenAPI): ActionOpenAPI;
hook: {
/**
* Create a reuseable after hook for the service.
* The hook will be called after the action handler called.
* @example
* ```ts
* const after = BlazeCreator.event.hook.after((ctx, res) => {
* const user = {
* name: res.name
* age: res.age
* }
*
* return user
* })
* ```
*/
after<Meta extends RecordUnknown = RecordUnknown, Body extends RecordUnknown = RecordUnknown, Params extends RecordUnknown = RecordUnknown, Header extends RecordString = RecordString, Result = never>(hook: AfterHookHandler<Meta, Body, Params, Header, Result>): AfterHookHandler<Meta, Body, Params, Header, never>;
/**
* Create a reuseable before hook for the service.
* The hook will be called before the action handler called.
* @example
* ```ts
* const before = BlazeCreator.event.hook.before((ctx) => {
* const user = await ctx.request.body()
*
* // Validate no duplicated email
* })
* ```
*/
before<Meta extends RecordUnknown = RecordUnknown, Body extends RecordUnknown = RecordUnknown, Params extends RecordUnknown = RecordUnknown, Header extends RecordString = RecordString>(hook: BeforeHookHandler<Meta, Body, Params, Header>): BeforeHookHandler<Meta, Body, Params, Header>;

@@ -18,6 +84,42 @@ };

export interface BlazeEventCreator {
/**
* Create a reusable event for services.
* @example
* ```ts
* const event = BlazeCreator.event({
* async handler(ctx) {
* const user = await ctx.request.body()
*
* Logger.info('User Created:', user)
* }
* })
* ```
*/
<Meta extends RecordUnknown = RecordUnknown, Params extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>>(event: Event<Meta, Params>): Event<Meta, Params>;
/**
* Create a reuseable validator for events parameters.
* @example
* ```ts
* const validator = BlazeCreator.event.validator({
* name: z.string(),
* age: z.number(),
* })
* ```
*/
validator<Params extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>>(validator: Params): Params;
}
export interface BlazeServiceCreator {
/**
* Create a new service with the given name, actions, events, and etc.
* @example
* ```ts
* const service = BlazeCreator.service({
* name: 'user',
* actions: {
* find,
* create,
* },
* })
* ```
*/
(service: Service): Service;

@@ -24,0 +126,0 @@ action: BlazeActionCreator;

import type { ZodObject, ZodRawShape } from 'zod';
import type { BlazeContext } from '../event';
import type { ActionHandler } from './action';
import type { Random, RecordString, RecordUnknown } from './helper';
import type { Random, RecordUnknown } from './helper';
export interface EventActionHandler {

@@ -13,4 +13,4 @@ name: string;

export type EventName = string;
export interface EventHandler<Meta extends RecordUnknown = RecordUnknown, Params extends RecordUnknown = RecordUnknown, Header extends RecordString = RecordString> {
(ctx: BlazeContext<Meta, Params, RecordUnknown, Header>): Promise<void> | void;
export interface EventHandler<Meta extends RecordUnknown = RecordUnknown, Params extends RecordUnknown = RecordUnknown> {
(ctx: BlazeContext<Meta, Params>): Promise<void> | void;
}

@@ -17,0 +17,0 @@ export interface Event<Meta extends RecordUnknown = RecordUnknown, Params extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, FinalParams extends RecordUnknown = Params['_output'] & RecordUnknown> {

import type { Context as HonoCtx } from 'hono';
import type { BlazeContext } from '../event';
import type { Blaze } from '../router';
import type { BlazeRouter } from '../router';
import type { Action } from './action';

@@ -15,3 +15,3 @@ export type Method = 'ALL' | 'POST' | 'GET' | 'PUT' | 'PATCH' | 'OPTIONS' | 'DELETE' | 'USE';

action: Omit<Action, 'name'>;
router: Blaze;
router: BlazeRouter;
}

@@ -18,0 +18,0 @@ export interface RestErrorHandlerOption {

@@ -0,8 +1,12 @@

/// <reference types="node" />
import type { RouteConfig, ZodRequestBody } from '@asteasolutions/zod-to-openapi';
import type { Router } from 'hono/router';
import type { MiddlewareHandler, RouterRoute } from 'hono/types';
import type { Env, MiddlewareHandler, RouterRoute } from 'hono/types';
import type { AnyZodObject } from 'zod';
import type { RecordUnknown } from './helper';
import type { Method } from './rest';
export interface CreateBlazeOption {
router?: Router<[never, RouterRoute]>;
path?: string | null;
autoStart?: boolean | null;
}

@@ -12,3 +16,3 @@ export interface OpenAPIRequest {

params?: AnyZodObject;
headers?: AnyZodObject;
header?: AnyZodObject;
}

@@ -20,1 +24,4 @@ export interface BlazeOpenAPIOption extends Omit<RouteConfig, 'request' | 'method'> {

}
export interface BlazeFetch<E extends Env = Env> {
(request: Request, Env?: E['Bindings'] | RecordUnknown, executionCtx?: RecordUnknown): Response | Promise<Response>;
}
import type { Router } from 'hono/router';
import type { RouterRoute } from 'hono/types';
import type { BlazeContext } from '../event';
import type { Blaze } from '../router';
import type { BlazeRouter } from '../router';
import type { Action, ActionHandler, Actions } from './action';

@@ -18,5 +18,9 @@ import type { Event, EventActionHandler, Events } from './event';

export interface LoadServiceOption {
app: Blaze;
app: BlazeRouter;
path: string;
}
export interface LoadServicesOption {
path: string;
autoStart?: boolean | null;
}
export interface CreateServiceOption {

@@ -26,3 +30,3 @@ sourcePath: string;

blazeCtx: BlazeContext;
app: Blaze;
app: BlazeRouter;
}

@@ -29,0 +33,0 @@ export interface ServiceConstructorOption extends Omit<CreateServiceOption, 'sourcePath'> {

/// <reference types="node" />
import type { StatusCode } from 'hono/utils/http-status';
import type { Blaze } from '../../router/Blaze';
import type { BlazeRouter } from '../../router';
import type { Method, RestErrorHandlerOption, RestParam, RestResponseHandlerOption, RestRoute } from '../../types/rest';
export declare function extractRestPath(restRoute: RestRoute): readonly [null, string] | readonly [Method, string];
export declare function extractRestParams(params: RestParam): readonly [Method | null, string];
export declare function getRouteHandler(router: Blaze, method: Method | null): import("hono/types").MiddlewareHandlerInterface<import("hono").Env, {}, "/">;
export declare function getRouteHandler(router: BlazeRouter, method: Method | null): import("hono/types").MiddlewareHandlerInterface<import("hono").Env, {}, "/">;
export declare function getRestResponse(options: Omit<RestResponseHandlerOption, 'honoCtx'>): readonly [

@@ -9,0 +9,0 @@ never,

import type { OpenAPIDefinitions } from '@asteasolutions/zod-to-openapi/dist/openapi-registry';
import type { Env, Schema } from 'hono';
import type { Blaze } from '../../router';
export declare function assignOpenAPIRegistry<E extends Env = Env, S extends Schema = NonNullable<unknown>, BasePath extends string = '/'>(blaze: Blaze<E, S, BasePath>, docPath: string, def: OpenAPIDefinitions): void | import("zod").ZodTypeAny | {
import type { BlazeRouter } from '../../router';
export declare function assignOpenAPIRegistry<E extends Env = Env, S extends Schema = NonNullable<unknown>, BasePath extends string = '/'>(router: BlazeRouter<E, S, BasePath>, docPath: string, def: OpenAPIDefinitions): void | import("zod").ZodTypeAny | {
name: string;

@@ -6,0 +6,0 @@ ref: {

import { Service } from '../../types/service';
export declare function loadService(filePath: string): Service;
export declare function loadService(filePath: string): Promise<Service>;
import type { LoadServiceOption } from '../types/service';
export declare function initializeServices(options: LoadServiceOption): void;
export declare function initializeServices(options: LoadServiceOption): Promise<void>;

@@ -1,2 +0,2 @@

import { Blaze } from '../../router';
import { BlazeRouter } from '../../router/BlazeRouter';
import type { EventActionHandler } from '../../types/event';

@@ -11,3 +11,3 @@ import type { CreateServiceOption, ServiceConstructorOption } from '../../types/service';

readonly restPath: string;
readonly mainRouter: Blaze;
readonly mainRouter: BlazeRouter;
readonly actions: BlazeServiceAction[];

@@ -17,5 +17,6 @@ readonly events: BlazeServiceEvent[];

readonly handlers: EventActionHandler[];
router: Blaze | null;
router: BlazeRouter | null;
private readonly blazeCtx;
private readonly service;
private isStarted;
constructor(options: ServiceConstructorOption);

@@ -29,3 +30,3 @@ private loadRest;

onStarted(): void;
static create(options: CreateServiceOption): BlazeService;
static create(options: CreateServiceOption): Promise<BlazeService>;
}

@@ -7,3 +7,3 @@ {

"type": "module",
"version": "2.0.3",
"version": "3.0.0-0",
"license": "MIT",

@@ -71,2 +71,82 @@ "devDependencies": {

"require": "./dist/cjs/index.js"
},
"./event": {
"types": "./dist/types/event/index.d.ts",
"import": "./dist/esm/event/index.js",
"require": "./dist/cjs/event/index.js"
},
"./event/BlazeBroker": {
"types": "./dist/types/event/BlazeBroker.d.ts",
"import": "./dist/esm/event/BlazeBroker.js",
"require": "./dist/cjs/event/BlazeBroker.js"
},
"./event/BlazeContext": {
"types": "./dist/types/event/BlazeContext.d.ts",
"import": "./dist/esm/event/BlazeContext.js",
"require": "./dist/cjs/event/BlazeContext.js"
},
"./event/BlazeEventEmitter": {
"types": "./dist/types/event/BlazeEventEmitter.d.ts",
"import": "./dist/esm/event/BlazeEventEmitter.js",
"require": "./dist/cjs/event/BlazeEventEmitter.js"
},
"./types": {
"types": "./dist/types/types/index.d.ts",
"import": "./dist/esm/types/index.js",
"require": "./dist/cjs/types/index.js"
},
"./types/action": {
"types": "./dist/types/types/action.d.ts",
"import": "./dist/esm/types/action.js",
"require": "./dist/cjs/types/action.js"
},
"./types/common": {
"types": "./dist/types/types/common.d.ts",
"import": "./dist/esm/types/common.js",
"require": "./dist/cjs/types/common.js"
},
"./types/context": {
"types": "./dist/types/types/context.d.ts",
"import": "./dist/esm/types/context.js",
"require": "./dist/cjs/types/context.js"
},
"./types/creator": {
"types": "./dist/types/types/creator.d.ts",
"import": "./dist/esm/types/creator.js",
"require": "./dist/cjs/types/creator.js"
},
"./types/error": {
"types": "./dist/types/types/error.d.ts",
"import": "./dist/esm/types/error.js",
"require": "./dist/cjs/types/error.js"
},
"./types/event": {
"types": "./dist/types/types/event.d.ts",
"import": "./dist/esm/types/event.js",
"require": "./dist/cjs/types/event.js"
},
"./types/helper": {
"types": "./dist/types/types/helper.d.ts",
"import": "./dist/esm/types/helper.js",
"require": "./dist/cjs/types/helper.js"
},
"./types/hooks": {
"types": "./dist/types/types/hooks.d.ts",
"import": "./dist/esm/types/hooks.js",
"require": "./dist/cjs/types/hooks.js"
},
"./types/rest": {
"types": "./dist/types/types/rest.d.ts",
"import": "./dist/esm/types/rest.js",
"require": "./dist/cjs/types/rest.js"
},
"./types/router": {
"types": "./dist/types/types/router.d.ts",
"import": "./dist/esm/types/router.js",
"require": "./dist/cjs/types/router.js"
},
"./types/service": {
"types": "./dist/types/types/service.d.ts",
"import": "./dist/esm/types/service.js",
"require": "./dist/cjs/types/service.js"
}

@@ -73,0 +153,0 @@ },

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc