@mapl/router 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # `@mapl/router`
2
+
3
+ A fast compiled radix tree router.
4
+
5
+ ```ts
6
+ import {
7
+ PARAMS,
8
+ PATHNAME,
9
+ PATHNAME_LEN,
10
+ compileNode,
11
+ type RouterCompilerState,
12
+ } from "@mapl/router/tree/compiler";
13
+ import { createNode, insertItem } from "@mapl/router/tree/node";
14
+ import { getExternalKeys, getContent } from "@mapl/compiler";
15
+
16
+ // Initialize the root node
17
+ const root = createNode("/");
18
+
19
+ // Add some routes
20
+ insertItem(root, "/", 0);
21
+ insertItem(root, "/user/*", 1);
22
+ insertItem(root, "/**", 2);
23
+
24
+ // Initialize the compiler state
25
+ const state: RouterCompilerState<any> = {
26
+ contentBuilder: [],
27
+ declarationBuilders: [],
28
+ localVarCount: 0,
29
+ externalValues: [],
30
+
31
+ // Same args as compileNode except the first one
32
+ compileItem: (item, state) => {
33
+ state.contentBuilder.push(`return f${state.externalValues.length};`);
34
+ state.externalValues.push(item);
35
+ },
36
+ };
37
+
38
+ // Compile from root node
39
+ compileNode(root, state, false, false, 0, "");
40
+
41
+ // Create the match function using the result state
42
+ const match = Function(
43
+ ...getExternalKeys(state),
44
+ `return (${PATHNAME},${PARAMS})=>{const ${PATHNAME_LEN}=${PATHNAME}.length;${getContent(state)}}`,
45
+ )(...state.externalValues);
46
+
47
+ // Example usage
48
+ const res0 = match("/", []);
49
+ res0; // 0
50
+
51
+ const params1 = [];
52
+ const res1 = match("/user/0", params1);
53
+ params1; // ['0']
54
+ res1; // 1
55
+
56
+ const params2 = [];
57
+ const res2 = match("/navigate/to/about", params2);
58
+ params2; // ['navigate/to/about']
59
+ res2; // 2
60
+ ```
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@mapl/router",
3
+ "version": "0.0.1",
4
+ "description": "Fast compiled router for all runtimes",
5
+ "keywords": [
6
+ "fast",
7
+ "compiled",
8
+ "router",
9
+ "node",
10
+ "bun",
11
+ "deno"
12
+ ],
13
+ "license": "MIT",
14
+ "type": "module",
15
+ "main": "./index.js",
16
+ "types": "./index.d.ts",
17
+ "scripts": {
18
+ "build:test": "bun scripts/build.ts && bun test",
19
+ "build:bench": "bun build:test && bun scripts/bench.ts",
20
+ "build:publish": "bun build:test && bun scripts/publish.ts",
21
+ "lint": "eslint ./src",
22
+ "lint:fix": "eslint ./src --fix"
23
+ },
24
+ "devDependencies": {
25
+ "@stylistic/eslint-plugin": "latest",
26
+ "eslint": "latest",
27
+ "typescript-eslint": "latest",
28
+ "eslint-plugin-jsdoc": "latest",
29
+ "@types/bun": "latest",
30
+ "mitata": "latest",
31
+ "typescript": "latest"
32
+ },
33
+ "dependencies": {
34
+ "@mapl/compiler": "^0.0.2"
35
+ }
36
+ }
@@ -0,0 +1,13 @@
1
+ import type { Node } from './node';
2
+ import type { CompilerState } from '@mapl/compiler';
3
+ type ParametersExcludeState<T> = T extends (arg0: any, arg1: any, ...rest: infer R) => any ? R : never;
4
+ export interface RouterCompilerState<Item> extends CompilerState {
5
+ compileItem: (item: Item, state: this, ...args: ParametersExcludeState<typeof compileNode>) => void;
6
+ }
7
+ export declare const PATHNAME = "__req_p";
8
+ export declare const PATHNAME_LEN = "__req_pl";
9
+ export declare const PARAMS = "__req_ps";
10
+ export declare const PREV_PARAM_INDEX = "__req_ppi";
11
+ export declare const CURRENT_PARAM_INDEX = "__req_cpi";
12
+ export declare function compileNode(node: Node, state: RouterCompilerState<any>, hasParam: boolean, hasMultipleParams: boolean, startIndexValue: number, startIndexPrefix: string): void;
13
+ export {};
@@ -0,0 +1 @@
1
+ export function compileNode(node,state,hasParam,hasMultipleParams,startIndexValue,startIndexPrefix){const builder=state.contentBuilder;const part=node[0];const partLen=part.length;startIndexValue++;if(partLen!==1){builder.push(`if(__req_pl>${startIndexPrefix}${startIndexValue+partLen-2})`);for(let i=1;i<partLen;i++,startIndexValue++)builder.push(`if(__req_p.charCodeAt(${startIndexPrefix}${startIndexValue})===${part.charCodeAt(i)})`);builder.push("{")}if(node[1]!==null){builder.push(`if(__req_pl===${startIndexPrefix}${startIndexValue}){`);state.compileItem(node[1],state,hasParam,hasMultipleParams,startIndexValue,startIndexPrefix);builder.push("}")}if(node[2]!==null){const children=node[2];const childrenKeys=Object.keys(children);if(childrenKeys.length===1){builder.push(`if(__req_p.charCodeAt(${startIndexPrefix}${startIndexValue})===${childrenKeys[0]}){`);compileNode(children[childrenKeys[0]],state,hasParam,hasMultipleParams,startIndexValue,startIndexPrefix);builder.push("}")}else{builder.push(`switch(__req_p.charCodeAt(${startIndexPrefix}${startIndexValue})){`);for(let i=0,l=childrenKeys.length;i<l;i++){builder.push(`case ${childrenKeys[i]}:`);compileNode(children[childrenKeys[i]],state,hasParam,hasMultipleParams,startIndexValue,startIndexPrefix);builder.push("break;")}builder.push("}")}}if(node[3]!==null){const params=node[3];const hasStore=params[1]!==null;const hasChild=params[0]!==null;const requireAllocation=hasParam?hasMultipleParams:hasChild||!hasStore;if(requireAllocation)builder.push("{");if(hasParam)builder.push(`${hasMultipleParams?"":"let "}__req_ppi=${startIndexPrefix}${startIndexValue};`);const currentIndex=hasParam?"__req_ppi":`${startIndexPrefix}${startIndexValue}`;const slashIndex=`__req_p.indexOf('/',${currentIndex})`;if(hasChild||!hasStore)builder.push(`${hasParam?"":"let "}__req_cpi=${slashIndex};`);if(hasStore){builder.push(`if(${hasChild?"__req_cpi":slashIndex}===-1){__req_ps.push(__req_p.slice(${currentIndex}));`);state.compileItem(params[1],state,true,hasParam,startIndexValue,startIndexPrefix);builder.push("}")}if(hasChild){builder.push(`if(${hasStore?"":"__req_cpi!==-1&&"}__req_cpi!==${currentIndex}){__req_ps.push(__req_p.substring(${currentIndex},__req_cpi));`);compileNode(params[0],state,true,hasParam,0,"__req_cpi+");builder.push("__req_ps.pop();}")}if(requireAllocation)builder.push("}")}if(node[4]!==null){const noStore=node[1]===null;if(noStore)builder.push(`if(__req_pl!==${startIndexPrefix}${startIndexValue}){`);builder.push(`__req_ps.push(__req_p.slice(${startIndexPrefix}${startIndexValue}));`);state.compileItem(node[4],state,hasParam,hasMultipleParams,startIndexValue,startIndexPrefix);if(noStore)builder.push("}")}if(partLen!==1)builder.push("}")}export const PATHNAME="__req_p";export const PATHNAME_LEN="__req_pl";export const PARAMS="__req_ps";export const PREV_PARAM_INDEX="__req_ppi";export const CURRENT_PARAM_INDEX="__req_cpi";
@@ -0,0 +1,2 @@
1
+ import type { Node } from './node';
2
+ export declare function matchItem(node: Node, path: string, params: string[], startIdx: number): unknown;
@@ -0,0 +1 @@
1
+ export function matchItem(node,path,params,startIdx){const part=node[0];const pathPartLen=part.length;const pathLen=path.length;if(pathPartLen>1){if(startIdx+pathPartLen>pathLen)return null;startIdx++;for(let i=1;i<pathPartLen;i++,startIdx++){if(part.charCodeAt(i)!==path.charCodeAt(startIdx))return null}}else startIdx++;if(startIdx===pathLen)return node[1];if(node[2]!==null){const child=node[2][path.charCodeAt(startIdx)];if(typeof child!=="undefined"){const matchResult=matchItem(child,path,params,startIdx);if(matchResult!==null)return matchResult}}if(node[3]!==null){const paramsNode=node[3];const slashIdx=path.indexOf("/",startIdx);if(slashIdx===-1){if(paramsNode[1]!==null){params.push(path.slice(startIdx));return paramsNode[1]}}else if(slashIdx!==startIdx&&paramsNode[0]!==null){params.push(path.substring(startIdx,slashIdx));const matchResult=matchItem(paramsNode[0],path,params,slashIdx);if(matchResult!==null)return matchResult;params.pop()}}if(node[4]!==null){params.push(path.slice(startIdx));return node[4]}return null}
package/tree/node.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export type Node = [
2
+ part: string,
3
+ store: any,
4
+ children: Record<number, Node> | null,
5
+ params: ParamNode | null,
6
+ wildcardStore: unknown
7
+ ];
8
+ export type ParamNode = [
9
+ child: Node | null,
10
+ store: unknown
11
+ ];
12
+ export declare function createNode(part: string): Node;
13
+ export declare function createParamNode(node: Node, nextNode: ParamNode[0]): ParamNode;
14
+ export declare function cloneNode(node: Node, part: string): Node;
15
+ export declare function resetNode(node: Node, part: string, children: Node[2]): void;
16
+ export declare function visitNode(node: Node, path: string): Node;
17
+ export declare function insertItem(node: Node, path: string, item: unknown): void;
package/tree/node.js ADDED
@@ -0,0 +1 @@
1
+ export function createNode(part){return[part,null,null,null,null]}export function createParamNode(node,nextNode){return node[3]=[nextNode,null]}export function cloneNode(node,part){return[part,node[1],node[2],node[3],node[4]]}export function resetNode(node,part,children){node[0]=part;node[2]=children;node[1]=null;node[3]=null;node[4]=null}export function visitNode(node,path){const parts=path.split("*");for(let i=0,{length}=parts;i<length;++i){if(i!==0){if(node[3]===null){const nextNode=createNode(parts[i]);createParamNode(node,nextNode);node=nextNode}else node=node[3][0]??=createNode(parts[i])}for(let j=0,pathPart=parts[i];;++j){const nodePart=node[0];if(j===pathPart.length){if(j<nodePart.length){const children={};children[nodePart.charCodeAt(j)]=cloneNode(node,nodePart.slice(j));resetNode(node,pathPart,children)}break}if(j===nodePart.length){if(node[2]===null)node[2]={};else{const nextNode=node[2][pathPart.charCodeAt(j)];if(typeof nextNode!=="undefined"){node=nextNode;pathPart=pathPart.slice(j);j=0;continue}}const nextNode=createNode(pathPart.slice(j));node[2][pathPart.charCodeAt(j)]=nextNode;node=nextNode;break}if(pathPart.charCodeAt(j)!==nodePart.charCodeAt(j)){const children={};children[nodePart.charCodeAt(j)]=cloneNode(node,nodePart.slice(j));const nextNode=createNode(pathPart.slice(j));children[pathPart.charCodeAt(j)]=createNode(pathPart.slice(j));resetNode(node,nodePart.substring(0,j),children);node=nextNode;break}}}return node}export function insertItem(node,path,item){if(path.charCodeAt(path.length-1)===42){if(path.charCodeAt(path.length-2)===42)visitNode(node,path.substring(0,path.length-2))[4]=item;else createParamNode(visitNode(node,path.substring(0,path.length-1)),null)[1]=item}else visitNode(node,path)[1]=item}