@mapl/web 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,31 @@
1
+ # Library template
2
+
3
+ An NPM library template using Bun.
4
+
5
+ ## Scripts
6
+
7
+ All script sources and usage.
8
+
9
+ ### [Build](./scripts/build.ts)
10
+
11
+ Emit `.js` and `.d.ts` files to [`lib`](./lib).
12
+
13
+ ### [Publish](./scripts/publish.ts)
14
+
15
+ Move [`package.json`](./package.json), [`README.md`](./README.md) to [`lib`](./lib) and publish the package.
16
+
17
+ ### [Bench](./scripts/bench.ts)
18
+
19
+ Run files that ends with `.bench.ts` extension.
20
+
21
+ To run a specific file.
22
+ ```bash
23
+ bun bench index # Run bench/index.bench.ts
24
+ ```
25
+
26
+ To run the benchmark in `node`, add a `--node` parameter
27
+ ```bash
28
+ bun bench --node
29
+
30
+ bun bench --node index # Run bench/index.bench.ts with node
31
+ ```
package/constants.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export * from '@mapl/framework/constants';
2
+ export declare const WEB: string;
3
+ export declare const REQ: string;
4
+ export declare const CTX_FN: string;
5
+ export declare const CTX_INIT: string;
6
+ export declare const URL: string;
7
+ export declare const PATH: string;
8
+ export declare const PATH_START: string;
9
+ export declare const PATH_END: string;
10
+ export declare const PARSE_PATH: string;
11
+ export declare const CHTML: string;
12
+ export declare const CJSON: string;
13
+ export declare const GLOBALS: string;
package/constants.js ADDED
@@ -0,0 +1 @@
1
+ import{MAPL,HEADERS,CTX}from"@mapl/framework/constants";export*from"@mapl/framework/constants";export let WEB=MAPL+"w";export let REQ=WEB+"r";export let CTX_FN=WEB+"ci";export let CTX_INIT="let "+HEADERS+"=[],"+CTX+"="+CTX_FN+"("+REQ+","+HEADERS+");";export let URL=REQ+"u";export let PATH=REQ+"p";export let PATH_START=PATH+"s";export let PATH_END=PATH+"e";export let PARSE_PATH="let "+URL+"="+REQ+".url,"+PATH_START+"="+URL+'.indexOf("/",12)+1,'+PATH_END+"1="+URL+'.indexOf("?",'+PATH_START+"),"+PATH+"="+PATH_END+"===-1?"+PATH+".slice("+PATH_END+"):"+PATH+".substring("+PATH_START+","+PATH_END+");";export let CHTML=WEB+"h";export let CJSON=WEB+"j";export let GLOBALS="let ["+CHTML+","+CJSON+']=["text/html","application/json"].map(c=>["content-type",c]);';
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { default as router } from './router';
2
+ import type { AnyRouter } from './router';
3
+ export declare const compile: (app: AnyRouter) => (req: Request) => any;
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export{default as router}from"./router";import genericCompile from"./router/compiler/generic";export let compile=(app)=>genericCompile(app,[]);
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@mapl/web",
3
+ "version": "0.0.1",
4
+ "description": "A compiled web standard framework",
5
+ "keywords": [],
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "./index.js",
9
+ "types": "./index.d.ts",
10
+ "scripts": {
11
+ "task": "bun scripts/task.ts",
12
+ "build:test": "bun task build && bun test",
13
+ "build:publish": "bun task build && bun task report-size && bun task publish",
14
+ "lint": "eslint ./src",
15
+ "lint:fix": "eslint ./src --fix"
16
+ },
17
+ "devDependencies": {
18
+ "@stylistic/eslint-plugin": "latest",
19
+ "@types/bun": "latest",
20
+ "@types/uglify-js": "latest",
21
+ "eslint": "latest",
22
+ "eslint-plugin-jsdoc": "latest",
23
+ "mitata": "latest",
24
+ "terser": "^5.39.0",
25
+ "tsx": "latest",
26
+ "typescript": "latest",
27
+ "typescript-eslint": "latest"
28
+ },
29
+ "dependencies": {
30
+ "@mapl/framework": "^0.0.19",
31
+ "@mapl/router": "^0.4.10",
32
+ "safe-throw": "^0.0.9"
33
+ }
34
+ }
@@ -0,0 +1,3 @@
1
+ import type { AnyRouter } from '..';
2
+ declare const _default: (router: AnyRouter, args: string[]) => (req: Request) => any;
3
+ export default _default;
@@ -0,0 +1 @@
1
+ export default (router,args)=>{let baseRouter={};let dependencies=[];compileGroup(router.group,[baseRouter,dependencies,createArgSet(["mc",...args]),"let mh=[],mc=mwci(mwr,mh);",compileHandler,compileErrorHandler,transformRoute],"","",false,false,"");return buildFunc('let [mwh,mwj]=["text/html","application/json"].map(c=>["content-type",c]);return (mwr)=>{'+compile(baseRouter,o2,"mwr.method",'let mwru=mwr.url,mwrps=mwru.indexOf("/",12)+1,mwrpe1=mwru.indexOf("?",mwrps),mwrp=mwrpe===-1?mwrp.slice(mwrpe):mwrp.substring(mwrps,mwrpe);',1)+"}",dependencies)};import{buildFunc,compileGroup,createArgSet,isFuncAsync,selectArgs}from"@mapl/framework";import{o2}from"@mapl/router/tree/compiler";import compile from"@mapl/router/method/compiler";import{transformRoute}from"@mapl/router/transform";let paramArgs=createArgSet(new Array(16).fill(0).map((_1,i)=>"q"+i));let compileHandler=(data,state,scopeAsync,contextCreated)=>{let fn=data[2];let dat=data[3];let str="";let call="mp"+state[1].push(fn)+"(";{let paramCount=data[1][0].length;if(paramCount>0)call+=paramArgs[paramCount];if(fn.length>paramCount){if(paramCount>0)call+=",";call+=selectArgs(state[2],fn.length-paramCount);if(!contextCreated){contextCreated=true;str+=state[3]}}}call+=")";{let typ=dat.type;if(typ==null){return str+"return new Response("+call+(contextCreated?",mc);":");")}if(typ==="raw")return str+"return "+call+";";if(!contextCreated)str+=state[3];let append="";if(isFuncAsync(fn)){call="await "+call;if(!scopeAsync){str+="return (async()=>{";append="});"}}str+="mh.push("+(typ==="json"?"mwj":"mwh")+");return new Response("+(typ==="json"?"JSON.stringify("+call+")":call)+",mc);"+append}return str};let compileErrorHandler=(data,state,scopeAsync,contextCreated)=>{let fn=data[0];let dat=data[1];let str="";let call="mp"+state[1].push(fn)+"(me";if(fn.length>1){call+=","+selectArgs(state[2],fn.length-1);if(!contextCreated){contextCreated=true;str+=state[3]}}call+=")";{let typ=dat.type;if(typ==null){return str+"return new Response("+call+(contextCreated?",mc);":");")}if(typ==="raw")return str+"return "+call+";";if(!contextCreated)str+=state[3];let append="";if(isFuncAsync(fn)){call="await "+call;if(!scopeAsync){str+="return (async()=>{";append="});"}}str+="mh.push("+(typ==="json"?"mwj":"mwh")+");return new Response("+(typ==="json"?"JSON.stringify("+call+")":call)+",mc);"+append}return str};
@@ -0,0 +1,9 @@
1
+ export type Header = [string, string] | readonly [string, string];
2
+ export type Headers = Header[];
3
+ export interface Context {
4
+ req: Request;
5
+ headers: Headers;
6
+ status?: number;
7
+ statusText?: string;
8
+ }
9
+ export declare const createContext: (req: Request, headers: Headers) => Context;
@@ -0,0 +1 @@
1
+ import{proto}from"./utils";let ctxProto=proto({req:null,headers:null,status:200});export let createContext=(req,headers)=>{let obj=Object.create(ctxProto);obj.headers=headers;obj.req=req;return obj};
@@ -0,0 +1,14 @@
1
+ import type { Group } from '@mapl/framework';
2
+ import type { Err } from 'safe-throw';
3
+ import type { Context } from './context';
4
+ export type ErrorFunc<E extends Err = Err, T extends {} = Record<string, any>, Args extends any[] = any[]> = (err: E, c: Context & T, ...args: Args) => any;
5
+ export type HandlerFunc<Params extends string[] = string[], T extends {} = Record<string, any>, Args extends any[] = any[]> = (...args: [...params: Params, c: Context & T, ...args: Args]) => any;
6
+ export type MiddlewareFunc<T extends {} = Record<string, any>, Args extends any[] = any[]> = (c: Context & T, ...args: Args) => any;
7
+ /**
8
+ * Basic information to compile
9
+ */
10
+ export interface Data {
11
+ type?: 'json' | 'html' | 'raw';
12
+ }
13
+ export type HandlerData = Data & Record<symbol, any>;
14
+ export type HandlerGroup = Group<ErrorFunc, HandlerFunc, HandlerData>;
@@ -0,0 +1,21 @@
1
+ import type { Err, InferErr, InferResult } from 'safe-throw';
2
+ import type { InferRoute } from '@mapl/router/transform';
3
+ import type { ErrorFunc, HandlerData, HandlerFunc, HandlerGroup, MiddlewareFunc } from './handler';
4
+ import { type Methods } from './method';
5
+ export type RouteRegister<in out Args extends any[], in out State extends {}, in out E extends Err> = {
6
+ [K in Methods | 'any']: <Path extends string>(path: Path, handler: HandlerFunc<InferRoute<Path>, State, Args>, ...data: HandlerData[]) => Router<Args, State, E>;
7
+ };
8
+ export interface Router<in out Args extends any[], in out State extends {} = {}, in out E extends Err = never> extends RouteRegister<Args, State, E> {
9
+ _state: State;
10
+ _err: E;
11
+ group: HandlerGroup;
12
+ apply: (fn: MiddlewareFunc<State, Args>) => this;
13
+ check: <const T extends MiddlewareFunc<State, Args>>(fn: T) => Router<Args, State, E | InferErr<ReturnType<T>>>;
14
+ set: <Prop extends string, const T extends MiddlewareFunc<State, Args>>(prop: Prop, fn: T) => Router<Args, State & Record<Prop, ReturnType<T>>, E>;
15
+ parse: <Prop extends string, const T extends MiddlewareFunc<State, Args>>(prop: Prop, fn: T) => Router<Args, State & Record<Prop, InferResult<ReturnType<T>>>, E | InferErr<ReturnType<T>>>;
16
+ route: <Prefix extends string, const App extends Router<Args, any, any>>(prefix: Prefix, app: App) => this;
17
+ err: (fn: ErrorFunc<E, State, Args>, ...data: HandlerData[]) => this;
18
+ }
19
+ export type AnyRouter = Router<any, any, any> | Router<any, any>;
20
+ declare const _default: () => Router<[]>;
21
+ export default _default;
@@ -0,0 +1 @@
1
+ export default ()=>{let obj=Object.create(routerProto);obj.group=[[],[],null,[]];return obj};import{proto}from"./utils";import{ALL,METHODS}from"./method";let createMethodRegister=(method)=>function(path,handler,...data){this.group[1].push([method,path,handler,proto(...data)]);return this};let routerProto=proto({group:null,apply(f){this.group[0].push([0,f]);return this},check(f){this.group[0].push([1,f]);return this},set(prop,f){this.group[0].push([2,f,prop]);return this},parse(prop,f){this.group[0].push([3,f,prop]);return this},route(prefix,app){this.group[3].push([prefix,app.group]);return this},any:createMethodRegister(ALL),err(f,...data){this.group[2]=[f,proto(...data)];return this}},Object.fromEntries(METHODS.map((method)=>[method,createMethodRegister(method.toUpperCase())])));
@@ -0,0 +1,5 @@
1
+ import { ALL } from '@mapl/router/method';
2
+ export declare const METHODS: readonly ["get", "post", "put", "delete", "patch", "options", "trace"];
3
+ export type Methods = typeof METHODS[number];
4
+ export type RequestMethod = Uppercase<Methods> | ALL | (string & {});
5
+ export { ALL };
@@ -0,0 +1 @@
1
+ import{ALL}from"@mapl/router/method";export let METHODS=["get","post","put","delete","patch","options","trace"];export{ALL};
@@ -0,0 +1,2 @@
1
+ export type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends ((x: infer I) => void) ? I : never;
2
+ export declare const proto: <T extends any[]>(...f: T) => UnionToIntersection<T[number]>;
@@ -0,0 +1 @@
1
+ export let proto=(...f)=>Object.assign(Object.create(null),...f);