Socket
Socket
Sign inDemoInstall

@bit-js/blitz

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bit-js/blitz - npm Package Compare versions

Comparing version 1.0.18 to 1.0.19

2

lib/index.js
// @bun
var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:(newValue)=>all[name]=()=>newValue})};var exports_internal={};__export(exports_internal,{Tree:()=>{{return Tree}},Radix:()=>{{return Radix}},Edge:()=>{{return Edge}},Context:()=>{{return Context}},BaseRouter:()=>{{return BaseRouter}}});class PathParts{inertParts=[];paramParts=[]}function splitPath(path){const parts=new PathParts;const{inertParts,paramParts}=parts;let paramIdx=path.indexOf(":"),start=0;while(paramIdx!==-1){if(paramIdx!==start)inertParts.push(path.substring(start,paramIdx));start=path.indexOf("/",paramIdx+1);if(start===-1){paramParts.push(path.substring(paramIdx+1));return parts}paramParts.push(path.substring(paramIdx+1,start));paramIdx=path.indexOf(":",start+1)}inertParts.push(path.substring(start));return parts}function plus(num,val){if(val===0)return num;const plusIdx=num.indexOf("+");return plusIdx===-1?Number.isNaN(+num)?`${num}+${val.toString()}`:(+num+val).toString():`${num.substring(0,plusIdx)}+${+num.substring(plusIdx+1)+val}`}function mergeRegExpParts(parts){return parts.length===1?parts[0]:`(?:${parts.join("|")})`}class ParamNode{paramName;store=null;inert=null;constructor(name){if(name==="$")throw new Error('Parameter name should not be "$" to avoid collision with wildcard parameter');this.paramName=name}}class InertStore{store={};size=0;lastChild;put(item){this.lastChild=item;this.store[item.key]=item;++this.size}}class Node{part;key;store=null;inert=null;params=null;wildcardStore=null;setPart(part){this.part=part;this.key=part.charCodeAt(0).toString()}constructor(part){this.setPart(part)}reset(part,firstChild){this.setPart(part);this.inert=new InertStore;this.inert.put(firstChild);this.store=this.params=this.wildcardStore=null}clone(part){const node=new Node(part);node.store=this.store;node.inert=this.inert;node.params=this.params;node.wildcardStore=this.wildcardStore;return node}param(paramName){if(this.params===null)this.params=new ParamNode(paramName);else if(this.params.paramName!==paramName)throw new Error(`Cannot create route with parameter "${paramName}" because a route already exists with a different parameter name ("${this.params.paramName}") in the same location`);return this.params}compileRegex(resultStore){const parts=[];if(this.store!==null){parts.push("$()");resultStore.push(this.store)}if(this.inert!==null){const{inert:{store}}=this;for(const key in store)parts.push(store[key].compileRegex(resultStore))}if(this.params!==null){const{params}=this;const paramParts=[];resultStore.push(null);if(params.store!==null){paramParts.push("$()");resultStore.push(params.store)}if(params.inert!==null)paramParts.push(params.inert.compileRegex(resultStore));parts.push(`(?<${params.paramName}>[^/]+)${mergeRegExpParts(paramParts)}`)}if(this.wildcardStore!==null){resultStore.push(null);resultStore.push(this.wildcardStore);parts.push("(?<$>.+)$()")}return this.part.replace(/\//g,"\\/")+mergeRegExpParts(parts)}compile(ctx,prevPathLen,isChildParam,isNestedChildParam){const{builder}=ctx;const{part}=this;const pathLen=plus(prevPathLen,part.length-1);const isNotRoot=part.length!==1;if(isNotRoot){builder.push(ctx.createTopLevelCheck(part,prevPathLen,pathLen));builder.push("{")}if(this.store!==null)builder.push(`if(path.length===${pathLen})${ctx.yield(this.store)};`);if(this.inert!==null){const nextPathLen=plus(pathLen,1);if(this.inert.size===1){const{lastChild}=this.inert;builder.push(`if(path.charCodeAt(${pathLen})===${lastChild.key}){`);lastChild.compile(ctx,nextPathLen,isChildParam,isNestedChildParam);builder.push("}")}else{const{store}=this.inert;builder.push(`switch(path.charCodeAt(${pathLen})){`);for(const key in store){builder.push(`case ${key}:`);store[key].compile(ctx,nextPathLen,isChildParam,isNestedChildParam);builder.push("break;")}builder.push("}")}}if(this.params!==null){const{params}=this;const prevIndex=isChildParam?"p":pathLen;if(isChildParam){if(!isNestedChildParam)builder.push("let ");builder.push(`p=${pathLen};`)}const nextSlashIndex=ctx.searchPath("/",prevIndex),hasInert=params.inert!==null,hasStore=params.store!==null,{paramName}=params;if(hasInert){if(!isChildParam)builder.push("let ");builder.push(`i=${nextSlashIndex};`)}if(hasStore){builder.push(`if(${hasInert?"i":nextSlashIndex}===-1){`);const value=ctx.slicePath(prevIndex);builder.push("c.params");builder.push(isChildParam?`.${paramName}=${value};`:`={${paramName}:${value}};`);builder.push(ctx.yield(params.store));builder.push("}")}if(hasInert){const value=ctx.substringPath(prevIndex,"i");if(!hasStore)builder.push(`if(i!==-1){`);builder.push("c.params");builder.push(isChildParam?`.${paramName}=${value};`:`={${paramName}:${value}};`);params.inert.compile(ctx,"i+1",true,isChildParam);if(!hasStore)builder.push("}")}}if(this.wildcardStore!==null){const value=ctx.slicePath(pathLen);builder.push("c.params");builder.push(isChildParam?`.\$=${value};`:`={\$:${value}};`);builder.push(ctx.yield(this.wildcardStore));builder.push(";")}if(isNotRoot)builder.push("}")}}function getArgs(value){return value.length===0?"()":"(c)"}class BuildContext{builder;paramsKeys=[];paramsValues=[];options;currentID=0;constructor(options,builder=[]){this.builder=builder;options.invokeResultFunction??=false;this.options=options}insert(value){const key="f"+this.currentID.toString();++this.currentID;this.paramsKeys.push(key);this.paramsValues.push(value);return key}yield(value){if(typeof value==="undefined")return"return";if(typeof value!=="function"){if(typeof value!=="symbol"&&typeof value!=="object")return`return ${JSON.stringify(value)}`}const key=this.insert(value);return this.options.invokeResultFunction?`return ${key}${getArgs(value)}`:`return ${key}`}yieldToken(value){return this.options.invokeResultFunction?`return ${value}(c)`:`return ${value}`}slicePath(idx){return idx==="0"?"path":`path.substring(${idx})`}substringPath(start,end){return`path.substring(${start},${end})`}searchPath(token,startIdx){return`path.indexOf('${token}'${startIdx==="0"?"":","+startIdx})`}createTopLevelCheck(part,prevPathLen,pathLen){const{length}=part;if(length<16){const result=new Array(length);result[0]="";for(let i=1;i<length;++i){result[i]=`if(path.charCodeAt(${prevPathLen})===${part.charCodeAt(i)})`;prevPathLen=plus(prevPathLen,1)}return result.join("")}return`if(path.substring(${prevPathLen},${pathLen})==='${part.substring(1)}')`}build(){return Function(...this.paramsKeys,`return (c)=>{${this.builder.join("")}}`)(...this.paramsValues)}}var replaceValue=function(_,value){if(value===null)return;if(value instanceof Map){const obj={};for(const pair of value)obj[String.fromCharCode(pair[0])]=pair[1];return obj}if(typeof value==="function")return value.toString();return value};class Tree{root=null;staticMap=null;store(path,store){if(path.includes(":")||path.charCodeAt(path.length-1)===42)this.storeDynamic(path,store);else this.storeStatic(path,store);return store}storeStatic(path,store){if(path.charCodeAt(0)===47)path=path.substring(1);const lastIdx=path.length-1;if(path.charCodeAt(lastIdx)===47)path=path.substring(0,lastIdx);this.staticMap??={};this.staticMap[path]??=store}storeDynamic(path,store){if(path.charCodeAt(0)!==47)path="/"+path;const isWildcard=path.charCodeAt(path.length-1)===42;if(isWildcard)path=path.slice(0,-1);const{inertParts,paramParts}=splitPath(path);let node=this.root??=new Node("/"),paramPartsIndex=0;for(let i=0,{length}=inertParts;i<length;++i){if(i!==0){const params=node.param(paramParts[paramPartsIndex]);++paramPartsIndex;if(params.inert===null){node=params.inert=new Node(inertParts[i]);continue}node=params.inert}let inertPart=inertParts[i];for(let j=0;;){if(j===inertPart.length){if(j<node.part.length)node.reset(inertPart,node.clone(node.part.substring(j)));break}if(j===node.part.length){if(node.inert===null)node.inert=new InertStore;else{const inert=node.inert.store[`${inertPart.charCodeAt(j)}`];if(typeof inert!=="undefined"){node=inert;inertPart=inertPart.substring(j);j=0;continue}}const childNode=new Node(inertPart.substring(j));node.inert.put(childNode);node=childNode;break}if(inertPart[j]!==node.part[j]){const newChild=new Node(inertPart.substring(j));const oldNode=node.clone(node.part.substring(j));node.reset(node.part.substring(0,j),oldNode);node.inert.put(newChild);node=newChild;break}++j}}if(paramPartsIndex<paramParts.length)node.param(paramParts[paramPartsIndex]).store??=store;else if(isWildcard)node.wildcardStore??=store;else node.store??=store}createStaticMatcher(options,fallback){const{staticMap}=this;if(options.invokeResultFunction===true){const fnFallback=typeof fallback==="function"?fallback:()=>fallback;return staticMap===null?fallback:(ctx)=>(staticMap[ctx.path]??fnFallback)(ctx)}return staticMap===null?()=>fallback:(ctx)=>staticMap[ctx.path]??fallback}compileRegex(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;const store=[null];const pattern=new RegExp("^"+root.compileRegex(store).substring(2));if(staticMap===null){if(options.invokeResultFunction===true){return fallback.length===0?(ctx)=>{const match=ctx.path.match(pattern);if(match===null)return fallback();ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}:(ctx)=>{const match=ctx.path.match(pattern);if(match===null)return fallback(ctx);ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}}return(ctx)=>{const match=ctx.path.match(pattern);if(match===null)return fallback;ctx.params=match.groups;return store[match.indexOf("",1)]}}if(options.invokeResultFunction===true){return fallback.length===0?(ctx)=>{const{path}=ctx;const staticMatch=staticMap[path];if(typeof staticMatch!=="undefined")return staticMatch;const match=path.match(pattern);if(match===null)return fallback();ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}:(ctx)=>{const{path}=ctx;const staticMatch=staticMap[path];if(typeof staticMatch!=="undefined")return staticMatch;const match=path.match(pattern);if(match===null)return fallback(ctx);ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}}return(ctx)=>{const{path}=ctx;const staticMatch=staticMap[path];if(typeof staticMatch!=="undefined")return staticMatch;const match=path.match(pattern);if(match===null)return fallback;ctx.params=match.groups;return store[match.indexOf("",1)]}}compile(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;const ctx=new BuildContext(options,["const{path}=c;"]);if(staticMap!==null)ctx.builder.push(`const m=${ctx.insert(staticMap)}[path];if(typeof m!=='undefined')${ctx.yieldToken("m")};`);root.compile(ctx,"0",false,false);if(root.wildcardStore===null)ctx.builder.push(ctx.yield(fallback));return ctx.build()}debug(space){return JSON.stringify(this.root,replaceValue,space)}}class Context{path;params}class BaseRouter{tree=new Tree;routes(routes){for(let i=0,{length}=routes;i<length;++i)this.put(...routes[i]);return this}put(path,handler){this.tree.store(path,handler);return this}}class Radix extends BaseRouter{constructor(){super(...arguments)}buildMatcher(options,fallback){options.invokeResultFunction=false;return this.tree.compile(options,fallback)}buildCaller(options,fallback){options.invokeResultFunction=true;return this.tree.compile(options,fallback)}}class Edge extends BaseRouter{constructor(){super(...arguments)}buildMatcher(options,fallback){options.invokeResultFunction=false;return this.tree.compileRegex(options,fallback)}buildCaller(options,fallback){options.invokeResultFunction=true;return this.tree.compileRegex(options,fallback)}}function extendContext(C,defaultOpts){if(typeof defaultOpts==="undefined")return C;const parts=[];for(const prop in defaultOpts)parts.push(`${prop}=${JSON.stringify(defaultOpts[prop])}`);return Function(`return (C)=>{return class A extends C{${parts.join()}}}`)()(C)}class Context2{req;path;pathStart;pathEnd;params;headers;status;statusText;constructor(req){this.req=req;const start=req.url.indexOf("/",12)+1,end=req.url.indexOf("?",start);this.pathStart=start;if(end===-1){this.path=req.url.substring(start);this.pathEnd=req.url.length}else{this.path=req.url.substring(start,end);this.pathEnd=end}}}class Router{options;methodRouter;fallbackRouter;fallback=noop;constructor(options={}){this.options=options;this.options=options}build(Construct=Context2){const{methodRouter,fallbackRouter}=this;const fallback=typeof fallbackRouter==="undefined"?this.fallback:fallbackRouter.buildCaller(this.options,this.fallback);if(typeof methodRouter==="undefined")return(req)=>fallback(new Construct(req));const methodCaller={};for(const method in methodRouter)methodCaller[method]=methodRouter[method].buildCaller(this.options,fallback);return(req)=>(methodCaller[req.method]??fallback)(new Construct(req))}}var noop=()=>null;class Blitz extends Router{constructor(){super(...arguments)}put(method,path,handler){((this.methodRouter??={})[method]??=new Radix).put(path,handler)}handle(path,handler){(this.fallbackRouter??=new Radix).put(path,handler)}}class EdgeRouter extends Router{constructor(){super(...arguments)}put(method,path,handler){((this.methodRouter??={})[method]??=new Edge).put(path,handler)}handle(path,handler){(this.fallbackRouter??=new Edge).put(path,handler)}}var normalize=function(path){return path.replace(/\/\/|\\\\|\\/g,"/")};var defaultStyleMap={basic(path){let startBracketIdx=path.indexOf("[");if(startBracketIdx===-1){const startPathExt2=path.lastIndexOf(".");if(startPathExt2===-1)return path.endsWith("index")?path.substring(0,path.length-5):path;if(path.charCodeAt(startPathExt2-1)===120){if(path.charCodeAt(startPathExt2-2)===101){if(path.charCodeAt(startPathExt2-3)===100){if(path.charCodeAt(startPathExt2-4)===110){if(path.charCodeAt(startPathExt2-5)===105){if(startPathExt2===5||path.charCodeAt(startPathExt2-6)===47)return path.substring(0,startPathExt2-5)}}}}}return path.substring(0,startPathExt2)}let pathBuilder="";let startIdx=0;do{pathBuilder+=path.substring(startIdx,startBracketIdx);if(path.charCodeAt(startBracketIdx+1)===46){if(path.charCodeAt(startBracketIdx+2)===46){if(path.charCodeAt(3)===46)return pathBuilder+"*"}}pathBuilder+=":";startIdx=path.indexOf("]",startBracketIdx);pathBuilder+=path.substring(startBracketIdx+1,startIdx);++startIdx;startBracketIdx=path.indexOf("[",startIdx)}while(startBracketIdx!==-1);const startPathExt=path.lastIndexOf(".");if(startPathExt===-1)pathBuilder+=path.endsWith("index")?path.substring(startIdx,path.length-5):path.substring(startIdx);else if(path.charCodeAt(startPathExt-1)===120){if(path.charCodeAt(startPathExt-2)===101){if(path.charCodeAt(startPathExt-3)===100){if(path.charCodeAt(startPathExt-4)===110){if(path.charCodeAt(startPathExt-5)===105){if(startPathExt===5||path.charCodeAt(startPathExt-6)===47)pathBuilder+=path.substring(0,startPathExt-5)}}}}}return pathBuilder},preserve(path){return path.charCodeAt(0)===47?path:"/"+path}};var compileOptions={invokeResultFunction:false};class RequestContext extends Context2{constructor(){super(...arguments)}result}class Router2{static Context=RequestContext;style;on;scanFiles;constructor({style,on,scan}){this.style=typeof style==="undefined"?defaultStyleMap.basic:typeof style==="string"?defaultStyleMap[style]:style;this.on=on;this.scanFiles=scan}scan(cwd="."){const{on,style,scanFiles}=this;const router=new Radix;for(const path of scanFiles(cwd))router.put(style(path),on(normalize(cwd+path)));const match=router.buildMatcher(compileOptions,null);return(req)=>{const ctx=new RequestContext(req);ctx.result=match(ctx);return ctx}}}var fs_default=Router2;export{exports_internal as internal,extendContext,Blitz as default,fs_default as FileSystemRouter,EdgeRouter,Context2 as Context,Router as BaseRouter};
var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:(newValue)=>all[name]=()=>newValue})};var exports_internal={};__export(exports_internal,{Tree:()=>{{return Tree}},Radix:()=>{{return Radix}},Edge:()=>{{return Edge}},Context:()=>{{return Context}},BaseRouter:()=>{{return BaseRouter}}});function plus(num,val){if(val===0)return num;const plusIdx=num.indexOf("+");return plusIdx===-1?Number.isNaN(+num)?`${num}+${val.toString()}`:(+num+val).toString():`${num.substring(0,plusIdx)}+${+num.substring(plusIdx+1)+val}`}class PathParts{inertParts=[];paramParts=[]}function splitPath(path){const parts=new PathParts;const{inertParts,paramParts}=parts;let paramIdx=path.indexOf(":"),start=0;while(paramIdx!==-1){if(paramIdx!==start)inertParts.push(path.substring(start,paramIdx));start=path.indexOf("/",paramIdx+1);if(start===-1){paramParts.push(path.substring(paramIdx+1));return parts}paramParts.push(path.substring(paramIdx+1,start));paramIdx=path.indexOf(":",start+1)}inertParts.push(path.substring(start));return parts}var commonPrefixEnd=function(part,otherPart){const minLen=Math.min(part.length,otherPart.length);for(let i=1;i<minLen;++i)if(part[i]!==otherPart[i])return i;return minLen};var replaceValue=function(key,value){if(value===null||key in ignoreKeys)return;if(typeof value==="function")return value.toString();return value};class ParamNode{paramName;store=null;inert=null;constructor(name){if(name==="$")throw new Error('Parameter name should not be "$" to avoid collision with wildcard parameter');this.paramName=name}merge(node){if(this.paramName!==node.paramName)throw new Error(`Cannot create merge route with parameter "${node.paramName}" because a route already exists with a different parameter name ("${this.paramName}") in the same location`);this.store??=node.store;if(node.inert!==null){if(this.inert===null)this.inert=node.inert;else this.inert.mergeWithInert(node.inert)}}mergeWithRoot(node){if(this.inert===null)this.inert=node;else this.inert.mergeWithRoot(node)}debug(){return JSON.parse(JSON.stringify(this,replaceValue))}}class InertStore{store={};size=0;lastChild;put(item){this.lastChild=item;this.store[item.key]=item;++this.size}}class Node{part;key;store=null;inert=null;params=null;wildcardStore=null;setPart(part){this.part=part;this.key=`${part.charCodeAt(0)}`}constructor(part){this.setPart(part)}reset(part,firstChild){const inert=new InertStore;inert.put(firstChild);this.inert=inert;this.setPart(part);this.store=this.params=this.wildcardStore=null}clone(part){const node=new Node(part);node.store=this.store;node.inert=this.inert;node.params=this.params;node.wildcardStore=this.wildcardStore;return node}setInert(node){const store=(this.inert??=new InertStore).store[node.key];if(typeof store==="undefined")this.inert.put(node);else store.mergeWithInert(node)}insert(path,store){let node=this;if(path.charCodeAt(0)!==47)path="/"+path;const isWildcard=path.charCodeAt(path.length-1)===42;if(isWildcard)path=path.slice(0,-1);const{inertParts,paramParts}=splitPath(path);let paramPartsIndex=0;for(let i=0,{length}=inertParts;i<length;++i){if(i!==0){const params=node.param(paramParts[paramPartsIndex]);++paramPartsIndex;if(params.inert===null){node=params.inert=new Node(inertParts[i]);continue}node=params.inert}let inertPart=inertParts[i];for(let j=0;;){if(j===inertPart.length){if(j<node.part.length)node.reset(inertPart,node.clone(node.part.substring(j)));break}if(j===node.part.length){if(node.inert===null)node.inert=new InertStore;else{const inert=node.inert.store[`${inertPart.charCodeAt(j)}`];if(typeof inert!=="undefined"){node=inert;inertPart=inertPart.substring(j);j=0;continue}}const childNode=new Node(inertPart.substring(j));node.inert.put(childNode);node=childNode;break}if(inertPart[j]!==node.part[j]){const newChild=new Node(inertPart.substring(j));const oldNode=node.clone(node.part.substring(j));node.reset(node.part.substring(0,j),oldNode);node.inert.put(newChild);node=newChild;break}++j}}if(paramPartsIndex<paramParts.length){const paramNode=node.param(paramParts[paramPartsIndex]);paramNode.store??=store;return paramNode}else if(isWildcard)node.wildcardStore??=store;else node.store??=store;return node}cloneSelf(){return this.clone(this.part)}mergeWithRoot(node){const{part}=this;const{length}=part;if(length===1)return this.mergeExact(node);if((this.store??=node.store)===null){if(part.charCodeAt(length-1)!==47)this.part+="/";this.mergeExact(node)}else{const newNode=new Node("/");newNode.mergeExact(node);this.setInert(newNode)}}mergeWithInert(node){const currentPart=this.part;const otherPart=node.part;if(currentPart===otherPart)return this.mergeExact(node);const prefixEnd=commonPrefixEnd(currentPart,otherPart);if(prefixEnd===currentPart.length)return this.setInert(node.clone(otherPart.substring(prefixEnd)));if(prefixEnd===otherPart.length){const newNode=node.cloneSelf();newNode.setInert(this.clone(currentPart.substring(prefixEnd)));this.setPart(newNode.part);this.store=newNode.store;this.inert=newNode.inert;this.params=newNode.params;this.wildcardStore=newNode.wildcardStore;return}this.reset(prefixEnd===0?"/":currentPart.substring(0,prefixEnd),this.clone(currentPart.substring(prefixEnd)));this.inert.put(node.clone(otherPart.substring(prefixEnd)))}mergeExact(node){this.store??=node.store;this.wildcardStore??=node.wildcardStore;if(node.inert!==null){if(this.inert===null)this.inert=node.inert;else{const newStore=node.inert.store;for(const key in newStore)this.setInert(newStore[key])}}if(node.params!==null){if(this.params===null)this.params=node.params;else this.params.merge(node.params)}}param(paramName){if(this.params===null)this.params=new ParamNode(paramName);else if(this.params.paramName!==paramName)throw new Error(`Cannot create route with parameter "${paramName}" because a route already exists with a different parameter name ("${this.params.paramName}") in the same location`);return this.params}compileRegex(resultStore){const parts=[];if(this.store!==null){parts.push("$()");resultStore.push(this.store)}if(this.inert!==null){const{inert:{store}}=this;for(const key in store)parts.push(store[key].compileRegex(resultStore))}if(this.params!==null){const{params}=this;const paramParts=[];resultStore.push(null);if(params.store!==null){paramParts.push("$()");resultStore.push(params.store)}if(params.inert!==null)paramParts.push(params.inert.compileRegex(resultStore));parts.push(paramParts.length===1?`(?<${params.paramName}>[^/]+)${paramParts[0]}`:`(?<${params.paramName}>[^/]+)(?:${paramParts.join("|")})`)}if(this.wildcardStore!==null){resultStore.push(null);resultStore.push(this.wildcardStore);parts.push("(?<$>.+)$()")}return parts.length===1?this.part.replace(/\//g,"\\/")+parts[0]:`${this.part.replace(/\//g,"\\/")}(?:${parts.join("|")})`}compile(ctx,prevPathLen,isChildParam,isNestedChildParam){const{builder}=ctx;const{part}=this;const pathLen=plus(prevPathLen,part.length-1);const isNotRoot=part.length!==1;if(isNotRoot){builder.push(ctx.createTopLevelCheck(part,prevPathLen,pathLen));builder.push("{")}if(this.store!==null)builder.push(`if(path.length===${pathLen})${ctx.yield(this.store)};`);if(this.inert!==null){const nextPathLen=plus(pathLen,1);if(this.inert.size===1){const{lastChild}=this.inert;builder.push(`if(path.charCodeAt(${pathLen})===${lastChild.key}){`);lastChild.compile(ctx,nextPathLen,isChildParam,isNestedChildParam);builder.push("}")}else{const{store}=this.inert;builder.push(`switch(path.charCodeAt(${pathLen})){`);for(const key in store){builder.push(`case ${key}:`);store[key].compile(ctx,nextPathLen,isChildParam,isNestedChildParam);builder.push("break;")}builder.push("}")}}if(this.params!==null){const{params}=this;const prevIndex=isChildParam?"p":pathLen;if(isChildParam){if(!isNestedChildParam)builder.push("let ");builder.push(`p=${pathLen};`)}const nextSlashIndex=ctx.searchPath("/",prevIndex),hasInert=params.inert!==null,hasStore=params.store!==null,{paramName}=params;if(hasInert){if(!isChildParam)builder.push("let ");builder.push(`i=${nextSlashIndex};`)}if(hasStore){builder.push(`if(${hasInert?"i":nextSlashIndex}===-1){`);const value=ctx.slicePath(prevIndex);builder.push("c.params");builder.push(isChildParam?`.${paramName}=${value};`:`={${paramName}:${value}};`);builder.push(ctx.yield(params.store));builder.push("}")}if(hasInert){const value=ctx.substringPath(prevIndex,"i");if(!hasStore)builder.push(`if(i!==-1){`);builder.push("c.params");builder.push(isChildParam?`.${paramName}=${value};`:`={${paramName}:${value}};`);params.inert.compile(ctx,"i+1",true,isChildParam);if(!hasStore)builder.push("}")}}if(this.wildcardStore!==null){const value=ctx.slicePath(pathLen);builder.push("c.params");builder.push(isChildParam?`.\$=${value};`:`={\$:${value}};`);builder.push(ctx.yield(this.wildcardStore));builder.push(";")}if(isNotRoot)builder.push("}")}debug(){return JSON.parse(JSON.stringify(this,replaceValue))}}var ignoreKeys={lastChild:null};function getArgs(value){return value.length===0?"()":"(c)"}class BuildContext{builder;paramsKeys=[];paramsValues=[];options;currentID=0;constructor(options,builder=[]){this.builder=builder;options.invokeResultFunction??=false;this.options=options}insert(value){const key="f"+this.currentID.toString();++this.currentID;this.paramsKeys.push(key);this.paramsValues.push(value);return key}yield(value){if(typeof value==="undefined")return"return";if(typeof value!=="function"){if(typeof value!=="symbol"&&typeof value!=="object")return`return ${JSON.stringify(value)}`}const key=this.insert(value);return this.options.invokeResultFunction?`return ${key}${getArgs(value)}`:`return ${key}`}yieldToken(value){return this.options.invokeResultFunction?`return ${value}(c)`:`return ${value}`}slicePath(idx){return idx==="0"?"path":`path.substring(${idx})`}substringPath(start,end){return`path.substring(${start},${end})`}searchPath(token,startIdx){return`path.indexOf('${token}'${startIdx==="0"?"":","+startIdx})`}createTopLevelCheck(part,prevPathLen,pathLen){const{length}=part;if(length<16){const result=new Array(length);result[0]="";for(let i=1;i<length;++i){result[i]=`if(path.charCodeAt(${prevPathLen})===${part.charCodeAt(i)})`;prevPathLen=plus(prevPathLen,1)}return result.join("")}return`if(path.substring(${prevPathLen},${pathLen})==='${part.substring(1)}')`}build(){return Function(...this.paramsKeys,`return (c)=>{${this.builder.join("")}}`)(...this.paramsValues)}}class Tree{root=null;staticMap=null;store(path,store){if(path.includes(":")||path.charCodeAt(path.length-1)===42)(this.root??=new Node("/")).insert(path,store);else this.storeStatic(path,store);return store}storeStatic(path,store){if(path.charCodeAt(0)===47)path=path.substring(1);const lastIdx=path.length-1;if(path.charCodeAt(lastIdx)===47)path=path.substring(0,lastIdx);this.staticMap??={};this.staticMap[path]??=store}mergeRoot(base,root){if(base.charCodeAt(0)!==47)base="/"+base;if(this.root===null){if(base.length===1){this.root=root;return}else this.root=new Node("/")}(this.root??=new Node("/")).insert(base,null).mergeWithRoot(root)}mergeStatic(base,staticMap){if(base.length<=1){if(this.staticMap===null)this.staticMap=staticMap;else{const oldStaticMap=this.staticMap;for(const key in staticMap)oldStaticMap[key]??=staticMap[key]}}else{if(base.includes(":")){const root=this.root??=new Node("/");for(const key in staticMap)root.insert(key.length===0?base:`${base}/${key}`,staticMap[key]);return}const startIdx=base.charCodeAt(0)===47?1:0;const{length}=base;const endIdx=base.charCodeAt(length-1)===47?length-1:length;if(startIdx!==0||endIdx!==length)base=base.substring(startIdx,endIdx);const oldStaticMap=this.staticMap??={};for(const key in staticMap)oldStaticMap[key.length===0?base:`${base}/${key}`]??=staticMap[key]}}merge(base,tree){const{staticMap,root}=tree;if(root!==null)this.mergeRoot(base,root);if(staticMap!==null)this.mergeStatic(base,staticMap)}createStaticMatcher(options,fallback){const{staticMap}=this;if(options.invokeResultFunction===true){const fnFallback=typeof fallback==="function"?fallback:()=>fallback;return staticMap===null?fallback:(ctx)=>(staticMap[ctx.path]??fnFallback)(ctx)}return staticMap===null?()=>fallback:(ctx)=>staticMap[ctx.path]??fallback}compileRegex(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;const store=[null];const pattern=new RegExp("^"+root.compileRegex(store).substring(2));if(staticMap===null){if(options.invokeResultFunction===true){return fallback.length===0?(ctx)=>{const match=ctx.path.match(pattern);if(match===null)return fallback();ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}:(ctx)=>{const match=ctx.path.match(pattern);if(match===null)return fallback(ctx);ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}}return(ctx)=>{const match=ctx.path.match(pattern);if(match===null)return fallback;ctx.params=match.groups;return store[match.indexOf("",1)]}}if(options.invokeResultFunction===true){return fallback.length===0?(ctx)=>{const{path}=ctx;const staticMatch=staticMap[path];if(typeof staticMatch!=="undefined")return staticMatch;const match=path.match(pattern);if(match===null)return fallback();ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}:(ctx)=>{const{path}=ctx;const staticMatch=staticMap[path];if(typeof staticMatch!=="undefined")return staticMatch;const match=path.match(pattern);if(match===null)return fallback(ctx);ctx.params=match.groups;return store[match.indexOf("",1)](ctx)}}return(ctx)=>{const{path}=ctx;const staticMatch=staticMap[path];if(typeof staticMatch!=="undefined")return staticMatch;const match=path.match(pattern);if(match===null)return fallback;ctx.params=match.groups;return store[match.indexOf("",1)]}}compile(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;const ctx=new BuildContext(options,["const{path}=c;"]);if(staticMap!==null)ctx.builder.push(`const m=${ctx.insert(staticMap)}[path];if(typeof m!=='undefined')${ctx.yieldToken("m")};`);root.compile(ctx,"0",false,false);if(root.wildcardStore===null)ctx.builder.push(ctx.yield(fallback));return ctx.build()}}class Context{path;params}class BaseRouter{tree=new Tree;routes(routes){for(let i=0,{length}=routes;i<length;++i)this.put(...routes[i]);return this}put(path,handler){this.tree.store(path,handler);return this}merge(base,router){this.tree.merge(base,router.tree)}}class Radix extends BaseRouter{constructor(){super(...arguments)}buildMatcher(options,fallback){options.invokeResultFunction=false;return this.tree.compile(options,fallback)}buildCaller(options,fallback){options.invokeResultFunction=true;return this.tree.compile(options,fallback)}}class Edge extends BaseRouter{constructor(){super(...arguments)}buildMatcher(options,fallback){options.invokeResultFunction=false;return this.tree.compileRegex(options,fallback)}buildCaller(options,fallback){options.invokeResultFunction=true;return this.tree.compileRegex(options,fallback)}}function extendContext(C,defaultOpts){if(typeof defaultOpts==="undefined")return C;const parts=[];for(const prop in defaultOpts)parts.push(`${prop}=${JSON.stringify(defaultOpts[prop])}`);return Function(`return (C)=>{return class A extends C{${parts.join()}}}`)()(C)}class Context2{req;path;pathStart;pathEnd;params;headers;status;statusText;constructor(req){this.req=req;const start=req.url.indexOf("/",12)+1,end=req.url.indexOf("?",start);this.pathStart=start;if(end===-1){this.path=req.url.substring(start);this.pathEnd=req.url.length}else{this.path=req.url.substring(start,end);this.pathEnd=end}}}class Router{options;methodRouter;fallbackRouter;fallback=noop;constructor(options={}){this.options=options;this.options=options}route(base,{methodRouter:otherMethodRouter,fallbackRouter:otherFallbackRouter}){if(typeof otherMethodRouter!=="undefined"){const methodRouter=this.methodRouter??={};for(const method in otherMethodRouter){const router=methodRouter[method];if(typeof router==="undefined")methodRouter[method]=otherMethodRouter[method];else router.merge(base,otherMethodRouter[method])}}if(typeof otherFallbackRouter!=="undefined"){const{fallbackRouter}=this;if(typeof fallbackRouter==="undefined")this.fallbackRouter=otherFallbackRouter;else fallbackRouter.merge(base,otherFallbackRouter)}}build(Construct=Context2){const{methodRouter,fallbackRouter}=this;const fallback=typeof fallbackRouter==="undefined"?this.fallback:fallbackRouter.buildCaller(this.options,this.fallback);if(typeof methodRouter==="undefined")return(req)=>fallback(new Construct(req));const methodCaller={};for(const method in methodRouter)methodCaller[method]=methodRouter[method].buildCaller(this.options,fallback);return(req)=>(methodCaller[req.method]??fallback)(new Construct(req))}}var noop=()=>null;class Blitz extends Router{constructor(){super(...arguments)}put(method,path,handler){((this.methodRouter??={})[method]??=new Radix).put(path,handler)}handle(path,handler){(this.fallbackRouter??=new Radix).put(path,handler)}}class EdgeRouter extends Router{constructor(){super(...arguments)}put(method,path,handler){((this.methodRouter??={})[method]??=new Edge).put(path,handler)}handle(path,handler){(this.fallbackRouter??=new Edge).put(path,handler)}}var normalize=function(path){return path.replace(/\/\/|\\\\|\\/g,"/")};var defaultStyleMap={basic(path){let startBracketIdx=path.indexOf("[");if(startBracketIdx===-1){const startPathExt2=path.lastIndexOf(".");if(startPathExt2===-1)return path.endsWith("index")?path.substring(0,path.length-5):path;if(path.charCodeAt(startPathExt2-1)===120){if(path.charCodeAt(startPathExt2-2)===101){if(path.charCodeAt(startPathExt2-3)===100){if(path.charCodeAt(startPathExt2-4)===110){if(path.charCodeAt(startPathExt2-5)===105){if(startPathExt2===5||path.charCodeAt(startPathExt2-6)===47)return path.substring(0,startPathExt2-5)}}}}}return path.substring(0,startPathExt2)}let pathBuilder="";let startIdx=0;do{pathBuilder+=path.substring(startIdx,startBracketIdx);if(path.charCodeAt(startBracketIdx+1)===46){if(path.charCodeAt(startBracketIdx+2)===46){if(path.charCodeAt(3)===46)return pathBuilder+"*"}}pathBuilder+=":";startIdx=path.indexOf("]",startBracketIdx);pathBuilder+=path.substring(startBracketIdx+1,startIdx);++startIdx;startBracketIdx=path.indexOf("[",startIdx)}while(startBracketIdx!==-1);const startPathExt=path.lastIndexOf(".");if(startPathExt===-1)pathBuilder+=path.endsWith("index")?path.substring(startIdx,path.length-5):path.substring(startIdx);else if(path.charCodeAt(startPathExt-1)===120){if(path.charCodeAt(startPathExt-2)===101){if(path.charCodeAt(startPathExt-3)===100){if(path.charCodeAt(startPathExt-4)===110){if(path.charCodeAt(startPathExt-5)===105){if(startPathExt===5||path.charCodeAt(startPathExt-6)===47)pathBuilder+=path.substring(0,startPathExt-5)}}}}}return pathBuilder},preserve(path){return path.charCodeAt(0)===47?path:"/"+path}};var compileOptions={invokeResultFunction:false};class RequestContext extends Context2{constructor(){super(...arguments)}result}class Router2{static Context=RequestContext;style;on;scanFiles;constructor({style,on,scan}){this.style=typeof style==="undefined"?defaultStyleMap.basic:typeof style==="string"?defaultStyleMap[style]:style;this.on=on;this.scanFiles=scan}scan(cwd="."){const{on,style,scanFiles}=this;const router=new Radix;for(const path of scanFiles(cwd))router.put(style(path),on(normalize(cwd+path)));const match=router.buildMatcher(compileOptions,null);return(req)=>{const ctx=new RequestContext(req);ctx.result=match(ctx);return ctx}}}var fs_default=Router2;export{exports_internal as internal,extendContext,Blitz as default,fs_default as FileSystemRouter,EdgeRouter,Context2 as Context,Router as BaseRouter};

@@ -18,2 +18,6 @@ import { Tree } from './tree';

/**
* Merge with another similar router
*/
merge(base: string, router: this): void;
/**
* Build a function to match and find the value

@@ -20,0 +24,0 @@ */

@@ -12,11 +12,22 @@ import { Node } from './nodes';

staticMap: Record<string, any> | null;
/**
* Register a path
*/
store(path: string, store: any): any;
/**
* Store static path
* Register a static path
*/
storeStatic(path: string, store: any): void;
/**
* Register a path
* Merge root node
*/
storeDynamic(path: string, store: any): void;
mergeRoot(base: string, root: Node): void;
/**
* Merge static routes
*/
mergeStatic(base: string, staticMap: Record<string, any>): void;
/**
* Set a tree as a children
*/
merge(base: string, tree: Tree): void;
createStaticMatcher(options: Options, fallback: any): Matcher;

@@ -31,6 +42,2 @@ /**

compile(options: Options, fallback: any): Matcher;
/**
* Return the tree in string
*/
debug(space?: number | string): string;
}

@@ -10,2 +10,5 @@ import type BuildContext from '../compiler/context';

constructor(name: string);
merge(node: ParamNode): void;
mergeWithRoot(node: Node): void;
debug(): any;
}

@@ -45,2 +48,26 @@ export declare class InertStore {

/**
* Store a node as an inert
*/
setInert(node: Node): void;
/**
* Insert a handler
*/
insert(path: string, store: any): ParamNode | Node;
/**
* Clone this
*/
cloneSelf(): Node;
/**
* Merge a node with a root node
*/
mergeWithRoot(node: Node): void;
/**
* Merge a node with an inert node (same first character)
*/
mergeWithInert(node: Node): void;
/**
* Merge a node with a similar role
*/
mergeExact(node: Node): void;
/**
* Set parametric node

@@ -57,2 +84,3 @@ */

compile(ctx: BuildContext, prevPathLen: string, isChildParam: boolean, isNestedChildParam: boolean): void;
debug(): any;
}

@@ -32,2 +32,6 @@ /// <reference types="node" />

/**
* Merge with another similar router
*/
route(base: string, { methodRouter: otherMethodRouter, fallbackRouter: otherFallbackRouter }: this): void;
/**
* Build the router

@@ -34,0 +38,0 @@ */

{
"name": "@bit-js/blitz",
"main": "lib/index.js",
"version": "1.0.18",
"version": "1.0.19",
"type": "module",

@@ -6,0 +6,0 @@ "devDependencies": {

@@ -19,2 +19,5 @@ # Blitz

// Register another router with the same type as a subrouter
router.route('/api', anotherRouter);
// Get the fetch function (use with Bun and Deno)

@@ -21,0 +24,0 @@ const fetch = router.build();

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