UNPKG

@sigiljs/sigil

Version:

TypeScript-first Node.js HTTP framework offering schema-driven routing, modifier-based middleware, plugin extensibility, and flexible response templating

2 lines (1 loc) 1.78 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("../route/route.js"),l=require("./misc/attach-plugin-context.js"),u=require("../utils/safe-url.js"),d=require("./sigil-request-processor.js");class i extends d.default{defineSchema=i.defineSchema;defineHandler=i.defineHandler;constructor(e){super(e)}static defineHandler(e,t){return t}static defineSchema(e,t){return[e,t]}addPlugin(e,t){if(this.$plugins.has(e.name))throw new Error(`Plugin with name "${e.name}" already registered.`);try{l.default(e,{sigilApi:this,responseTemplate:this.$responseTemplate,routes:this.$routes,debugOpts:this.$options.debug||{},pluginConfig:t});const s=new e;this.$plugins.set(e.name,s)}catch(s){this.logger({message:`Failed to initialize plugin "${e?.name}" due to ${s?.name}: ${s?.message}`,level:"error",module:"registry",json:{milestone:"plugin",ok:!1,plugins:e?.name}})}}mount(e,t){return this.$root.mount(e,t),this.$routes.add([e,t]),t.__$connectToSigil(this,()=>this.$updateCallback(),{debug:this.$options.debug}),t}route(e,t){const s=new o.default({...t,debug:t?.debug??this.$options.debug});return this.$root.mount(e,s),this.$routes.add([e,s]),s.__$connectToSigil(this,()=>this.$updateCallback()),s}async listen(e,t="localhost"){if(!this.$server)throw new Error("Cannot use internal server in the serverless mode");const s=this.$options.server?.https?.cert?"https":"http",n=u.default(`${s}://${t}:${e}`);if(!n)throw new Error(`Invalid URL: ${s}://${t}:${e}`);return this.$initialized=!0,await this.$updateCallback(),await new Promise(r=>{const a=setInterval(()=>{this.$pluginsInitialized&&(r(),clearInterval(a))},100)}),new Promise(r=>{this.$server.listen(e,t,()=>r({host:t,port:e,url:n}))})}}exports.default=i;