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.23 to 1.2.0

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}}});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{name;store=null;inert=null;constructor(name){if(name==="$")throw new Error('Parameter name should not be "$" to avoid collision with wildcard parameter');this.name=name}merge(node){if(this.name!==node.name)throw new Error(`Cannot create merge route with parameter "${node.name}" because a route already exists with a different parameter name ("${this.name}") 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.part[0]]=item;++this.size}}class Node{part;store=null;inert=null;params=null;wildcardStore=null;constructor(part){this.part=part}reset(part,firstChild){const inert=new InertStore;inert.put(firstChild);this.inert=inert;this.part=part;this.store=this.params=this.wildcardStore=null}split(part,firstChild,secondChild){const inert=new InertStore;inert.put(firstChild);inert.put(secondChild);this.inert=inert;this.part=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.part[0]];if(typeof store==="undefined")this.inert.put(node);else store.mergeWithInert(node)}insert(path,store){let node=this;const lastIdx=path.length-1;const isWildcard=path.charCodeAt(lastIdx)===42;const{inertParts,paramParts}=splitPath(isWildcard?path.substring(0,lastIdx):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[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));node.split(node.part.substring(0,j),node.clone(node.part.substring(j)),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.part=newNode.part;this.store=newNode.store;this.inert=newNode.inert;this.params=newNode.params;this.wildcardStore=newNode.wildcardStore;return}this.split(prefixEnd===0?"/":currentPart.substring(0,prefixEnd),this.clone(currentPart.substring(prefixEnd)),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.name!==paramName)throw new Error(`Cannot create route with parameter "${paramName}" because a route already exists with a different parameter name ("${this.params.name}") in the same location`);return this.params}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("{")}const hasStore=this.store!==null;if(hasStore)builder.push(`if(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.part.charCodeAt(0)}){`);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.charCodeAt(0)}:`);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 paramHasInert=params.inert!==null,paramHasStore=params.store!==null,{name}=params;if(!isChildParam)builder.push("let ");builder.push(`i=${ctx.searchPath("/",prevIndex)};`);builder.push(`if(i!==${prevIndex}){`);if(paramHasStore){builder.push(`if(i===-1){`);const value=ctx.slicePath(prevIndex);builder.push(`params.${name}=${value};`);builder.push(ctx.yield(params.store));builder.push("}")}if(paramHasInert){const value=ctx.substringPath(prevIndex,"i");if(!paramHasStore)builder.push(`if(i!==-1){`);builder.push(`params.${name}=${value};`);params.inert.compile(ctx,"i+1",true,isChildParam);if(!paramHasStore)builder.push("}")}builder.push("}")}if(this.wildcardStore!==null){if(!hasStore)builder.push(`if(length!==${pathLen}){`);const value=ctx.slicePath(pathLen);builder.push(`params.\$=${value};`);builder.push(ctx.yield(this.wildcardStore));builder.push(";");if(!hasStore)builder.push("}")}if(isNotRoot)builder.push("}")}matchRoute(path,param,startIndex){const{part}=this;const{length}=path;const pathPartLen=part.length;const pathPartEndIndex=startIndex+pathPartLen;if(pathPartLen>1){if(pathPartEndIndex>length)return null;if(pathPartLen<15){for(let i=1,j=startIndex+1;i<pathPartLen;++i,++j)if(part[i]!==path[j])return null}else if(path.substring(startIndex,pathPartEndIndex)!==part)return null}startIndex=pathPartEndIndex;if(startIndex===length)return this.store;if(this.inert!==null){const staticChild=this.inert.store[path[startIndex]];if(typeof staticChild!=="undefined"){const route=staticChild.matchRoute(path,param,startIndex);if(route!==null)return route}}if(this.params!==null){const{params}=this;const slashIndex=path.indexOf("/",startIndex);if(slashIndex!==startIndex){if(slashIndex===-1){if(params.store!==null){param[params.name]=path.substring(startIndex);return params.store}}else if(params.inert!==null){const route=params.inert.matchRoute(path,param,slashIndex);if(route!==null){param[params.name]=path.substring(startIndex,slashIndex);return route}}}}if(this.wildcardStore!==null){param.$=path.substring(startIndex);return this.wildcardStore}return null}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<15){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.charCodeAt(0)!==47)throw new Error("Path should start with a slash");const{length}=path;const lastCharCode=path.charCodeAt(length-1);if(length!==1&&lastCharCode===47)throw new Error("Path should not end with a slash");if(path.includes(":")||lastCharCode===42)(this.root??=new Node("/")).insert(path,store);else(this.staticMap??={})[path]??=store;return store}mergeRoot(base,root){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<2){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===1?base:`${base}${key}`,staticMap[key]);return}const oldStaticMap=this.staticMap??={};for(const key in staticMap)oldStaticMap[key.length===1?base:`${base}${key}`]??=staticMap[key]}}merge(base,tree){if(base.charCodeAt(0)!==47)throw new Error("Path should start with a slash");const{length}=base;if(length!==1&&base.charCodeAt(length-1)===47)throw new Error("Path should not end with a slash");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)return staticMap===null?fallback:(ctx)=>(staticMap[ctx.path]??fallback)(ctx);return staticMap===null?()=>fallback:(ctx)=>staticMap[ctx.path]??fallback}compile(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;const builder=["const {path}=c;"];const ctx=new BuildContext(options,builder);if(staticMap!==null)builder.push(`const m=${ctx.insert(staticMap)}[path];if(typeof m!=='undefined')${ctx.yieldToken("m")};`);builder.push("const {length}=path,params=c.params={};");root.compile(ctx,"1",false,false);if(root.wildcardStore===null)builder.push(ctx.yield(fallback));return ctx.build()}compileMatcher(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;if(staticMap===null)return options.invokeResultFunction===true?(ctx)=>(root.matchRoute(ctx.path,ctx.params={},0)??fallback)(ctx):(ctx)=>root.matchRoute(ctx.path,ctx.params={},0)??fallback;return options.invokeResultFunction===true?(ctx)=>{const{path}=ctx;return staticMap[path]??(root.matchRoute(path,ctx.params={},0)??fallback)(ctx)}:(ctx)=>{const{path}=ctx;return staticMap[path]??root.matchRoute(path,ctx.params={},0)??fallback}}}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.compileMatcher(options,fallback)}buildCaller(options,fallback){options.invokeResultFunction=true;return this.tree.compileMatcher(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),end=req.url.indexOf("?",start+1);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};
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{name;store=null;inert=null;constructor(name){if(name==="$")throw new Error('Parameter name should not be "$" to avoid collision with wildcard parameter');this.name=name}merge(node){if(this.name!==node.name)throw new Error(`Cannot create merge route with parameter "${node.name}" because a route already exists with a different parameter name ("${this.name}") 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.part[0]]=item;++this.size}}class Node{part;store=null;inert=null;params=null;wildcardStore=null;constructor(part){this.part=part}reset(part,firstChild){const inert=new InertStore;inert.put(firstChild);this.inert=inert;this.part=part;this.store=this.params=this.wildcardStore=null}split(part,firstChild,secondChild){const inert=new InertStore;inert.put(firstChild);inert.put(secondChild);this.inert=inert;this.part=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.part[0]];if(typeof store==="undefined")this.inert.put(node);else store.mergeWithInert(node)}insert(path,store){let node=this;const lastIdx=path.length-1;const isWildcard=path.charCodeAt(lastIdx)===42;const{inertParts,paramParts}=splitPath(isWildcard?path.substring(0,lastIdx):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[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));node.split(node.part.substring(0,j),node.clone(node.part.substring(j)),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.part=newNode.part;this.store=newNode.store;this.inert=newNode.inert;this.params=newNode.params;this.wildcardStore=newNode.wildcardStore;return}this.split(prefixEnd===0?"/":currentPart.substring(0,prefixEnd),this.clone(currentPart.substring(prefixEnd)),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.name!==paramName)throw new Error(`Cannot create route with parameter "${paramName}" because a route already exists with a different parameter name ("${this.params.name}") in the same location`);return this.params}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("{")}const hasStore=this.store!==null;if(hasStore)builder.push(`if(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.part.charCodeAt(0)}){`);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.charCodeAt(0)}:`);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 paramHasInert=params.inert!==null,paramHasStore=params.store!==null,{name}=params;if(!isChildParam)builder.push("let ");builder.push(`i=${ctx.searchPath("/",prevIndex)};`);builder.push(`if(i!==${prevIndex}){`);if(paramHasStore){builder.push(`if(i===-1){`);const value=ctx.slicePath(prevIndex);builder.push(`params.${name}=${value};`);builder.push(ctx.yield(params.store));builder.push("}")}if(paramHasInert){const value=ctx.substringPath(prevIndex,"i");if(!paramHasStore)builder.push(`if(i!==-1){`);builder.push(`params.${name}=${value};`);params.inert.compile(ctx,"i+1",true,isChildParam);if(!paramHasStore)builder.push("}")}builder.push("}")}if(this.wildcardStore!==null){if(!hasStore)builder.push(`if(length!==${pathLen}){`);const value=ctx.slicePath(pathLen);builder.push(`params.\$=${value};`);builder.push(ctx.yield(this.wildcardStore));builder.push(";");if(!hasStore)builder.push("}")}if(isNotRoot)builder.push("}")}matchRoute(path,param,startIndex){const{part}=this;const{length}=path;const pathPartLen=part.length;const pathPartEndIndex=startIndex+pathPartLen;if(pathPartLen>1){if(pathPartEndIndex>length)return null;if(pathPartLen<15){for(let i=1,j=startIndex+1;i<pathPartLen;++i,++j)if(part[i]!==path[j])return null}else if(path.substring(startIndex,pathPartEndIndex)!==part)return null}startIndex=pathPartEndIndex;if(startIndex===length)return this.store;if(this.inert!==null){const staticChild=this.inert.store[path[startIndex]];if(typeof staticChild!=="undefined"){const route=staticChild.matchRoute(path,param,startIndex);if(route!==null)return route}}if(this.params!==null){const{params}=this;const slashIndex=path.indexOf("/",startIndex);if(slashIndex!==startIndex){if(slashIndex===-1){if(params.store!==null){param[params.name]=path.substring(startIndex);return params.store}}else if(params.inert!==null){const route=params.inert.matchRoute(path,param,slashIndex);if(route!==null){param[params.name]=path.substring(startIndex,slashIndex);return route}}}}if(this.wildcardStore!==null){param.$=path.substring(startIndex);return this.wildcardStore}return null}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<15){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.charCodeAt(0)!==47)throw new Error("Path should start with a slash");const{length}=path;const lastCharCode=path.charCodeAt(length-1);if(length!==1&&lastCharCode===47)throw new Error("Path should not end with a slash");if(path.includes(":")||lastCharCode===42)(this.root??=new Node("/")).insert(path,store);else(this.staticMap??={})[path]??=store;return store}mergeRoot(base,root){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<2){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===1?base:`${base}${key}`,staticMap[key]);return}const oldStaticMap=this.staticMap??={};for(const key in staticMap)oldStaticMap[key.length===1?base:`${base}${key}`]??=staticMap[key]}}merge(base,tree){if(base.charCodeAt(0)!==47)throw new Error("Path should start with a slash");const{length}=base;if(length!==1&&base.charCodeAt(length-1)===47)throw new Error("Path should not end with a slash");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)return staticMap===null?fallback:(ctx)=>(staticMap[ctx.path]??fallback)(ctx);return staticMap===null?()=>fallback:(ctx)=>staticMap[ctx.path]??fallback}compile(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;const builder=["const {path}=c;"];const ctx=new BuildContext(options,builder);if(staticMap!==null)builder.push(`const m=${ctx.insert(staticMap)}[path];if(typeof m!=='undefined')${ctx.yieldToken("m")};`);builder.push("const {length}=path,params=c.params={};");root.compile(ctx,"1",false,false);if(root.wildcardStore===null)builder.push(ctx.yield(fallback));return ctx.build()}compileMatcher(options,fallback){const{root}=this;if(root===null)return this.createStaticMatcher(options,fallback);const{staticMap}=this;if(staticMap===null)return options.invokeResultFunction===true?(ctx)=>(root.matchRoute(ctx.path,ctx.params={},0)??fallback)(ctx):(ctx)=>root.matchRoute(ctx.path,ctx.params={},0)??fallback;return options.invokeResultFunction===true?(ctx)=>{const{path}=ctx;return(staticMap[path]??root.matchRoute(path,ctx.params={},0)??fallback)(ctx)}:(ctx)=>{const{path}=ctx;return staticMap[path]??root.matchRoute(path,ctx.params={},0)??fallback}}}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.compileMatcher(options,fallback)}buildCaller(options,fallback){options.invokeResultFunction=true;return this.tree.compileMatcher(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),end=req.url.indexOf("?",start+1);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};
{
"name": "@bit-js/blitz",
"main": "lib/index.js",
"version": "1.0.23",
"version": "1.2.0",
"type": "module",

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

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