refactor(router): use `#` for private props to reduce the minified file size (#3660)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by EdamAmex · committed by GitHub · parent 7e17b76 · Browse files · 7 files·+93 added−90 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+93 added−90 removed
- other:+93 added−90 removed
Provenance
- Commit
7b30835- Tree
42f5445- Author
EdamAmex <121654029+EdamAme-x@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
7e17b76
7 files changed+93 added−90 removed
modified:src/router/linear-router/router.ts+4 added-4 removed
8 unmodified lines9101112131314151617181920212122232425262728272829303132106 unmodified linesExpand all8 unmodified linesconst splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/gconst splitByStarRe = /\*/export class LinearRouter<T> implements Router<T> { name: string = 'LinearRouter' routes: [string, string, T][] = [] #routes: [string, string, T][] = []
add(method: string, path: string, handler: T) { for ( let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length; i < len; i++ ) { this.routes.push([method, paths[i], handler]) this.#routes.push([method, paths[i], handler]) } }
match(method: string, path: string): Result<T> { const handlers: [T, Params][] = [] ROUTES_LOOP: for (let i = 0, len = this.routes.length; i < len; i++) { const [routeMethod, routePath, handler] = this.routes[i] ROUTES_LOOP: for (let i = 0, len = this.#routes.length; i < len; i++) { const [routeMethod, routePath, handler] = this.#routes[i] if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { if (routePath === '*' || routePath === '/*') { handlers.push([handler, emptyParams]) continue106 unmodified linesExpand allmodified:src/router/reg-exp-router/node.ts+19 added-19 removed
41 unmodified lines42 return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length43 }44 45 export class Node {46- index?: number47- varIndex?: number48- children: Record<string, Node> = Object.create(null)46+ #index?: number47+ #varIndex?: number48+ #children: Record<string, Node> = Object.create(null)49 50 insert(51 tokens: readonly string[],52 index: number,1 unmodified line54 context: Context,55 pathErrorCheckOnly: boolean56 ): void {57 if (tokens.length === 0) {58- if (this.index !== undefined) {58+ if (this.#index !== undefined) {59 throw PATH_ERROR60 }61 if (pathErrorCheckOnly) {62 return63 }64 65- this.index = index65+ this.#index = index66 return67 }68 69 const [token, ...restTokens] = tokens17 unmodified lines87 throw PATH_ERROR88 }89 }90 91- node = this.children[regexpStr]91+ node = this.#children[regexpStr]92 if (!node) {93 if (94- Object.keys(this.children).some(94+ Object.keys(this.#children).some(95 (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR96 )97 ) {98 throw PATH_ERROR99 }100 if (pathErrorCheckOnly) {101 return102 }103- node = this.children[regexpStr] = new Node()103+ node = this.#children[regexpStr] = new Node()104 if (name !== '') {105- node.varIndex = context.varIndex++105+ node.#varIndex = context.varIndex++106 }107 }108 if (!pathErrorCheckOnly && name !== '') {109- paramMap.push([name, node.varIndex as number])109+ paramMap.push([name, node.#varIndex as number])110 }111 } else {112- node = this.children[token]112+ node = this.#children[token]113 if (!node) {114 if (115- Object.keys(this.children).some(115+ Object.keys(this.#children).some(116 (k) =>117 k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR118 )119 ) {1 unmodified line121 }122 if (pathErrorCheckOnly) {123 return124 }125- node = this.children[token] = new Node()125+ node = this.#children[token] = new Node()126 }127 }128 129 node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)130 }131 132 buildRegExpStr(): string {133- const childKeys = Object.keys(this.children).sort(compareKey)133+ const childKeys = Object.keys(this.#children).sort(compareKey)134 135 const strList = childKeys.map((k) => {136- const c = this.children[k]136+ const c = this.#children[k]137 return (138- (typeof c.varIndex === 'number'139- ? `(${k})@${c.varIndex}`138+ (typeof c.#varIndex === 'number'139+ ? `(${k})@${c.#varIndex}`140 : regExpMetaChars.has(k)141 ? `\\${k}`142 : k) + c.buildRegExpStr()143 )144 })145 146- if (typeof this.index === 'number') {147- strList.unshift(`#${this.index}`)146+ if (typeof this.#index === 'number') {147+ strList.unshift(`#${this.#index}`)148 }149 150 if (strList.length === 0) {151 return ''8 unmodified linesmodified:src/router/reg-exp-router/router.ts+10 added-9 removed
121 unmodified lines122 }123 124 export class RegExpRouter<T> implements Router<T> {125 name: string = 'RegExpRouter'126- middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>127- routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>126+ #middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>127+ #routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>128 129 constructor() {130- this.middleware = { [METHOD_NAME_ALL]: Object.create(null) }131- this.routes = { [METHOD_NAME_ALL]: Object.create(null) }130+ this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }131+ this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }132 }133 134 add(method: string, path: string, handler: T) {135- const { middleware, routes } = this135+ const middleware = this.#middleware136+ const routes = this.#routes137 138 if (!middleware || !routes) {139 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)140 }91 unmodified lines232 233 #buildAllMatchers(): Record<string, Matcher<T> | null> {234 const matchers: Record<string, Matcher<T> | null> = Object.create(null)235 235- Object.keys(this.routes!)236- .concat(Object.keys(this.middleware!))236+ Object.keys(this.#routes!)237+ .concat(Object.keys(this.#middleware!))238 .forEach((method) => {239 matchers[method] ||= this.#buildMatcher(method)240 })241 242 // Release cache242- this.middleware = this.routes = undefined243+ this.#middleware = this.#routes = undefined244 245 return matchers246 }247 1 unmodified line249 const routes: [string, HandlerWithMetadata<T>[]][] = []250 251 let hasOwnRoute = method === METHOD_NAME_ALL252 252- ;[this.middleware!, this.routes!].forEach((r) => {253+ ;[this.#middleware!, this.#routes!].forEach((r) => {254 const ownRoute = r[method]255 ? Object.keys(r[method]).map((path) => [path, r[method][path]])256 : []257 if (ownRoute.length !== 0) {19 unmodified linesmodified:src/router/reg-exp-router/trie.ts+4 added-4 removed
2 unmodified lines3 4 export type ReplacementMap = number[]5 6 export class Trie {7- context: Context = { varIndex: 0 }8- root: Node = new Node()7+ #context: Context = { varIndex: 0 }8+ #root: Node = new Node()9 10 insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {11 const paramAssoc: ParamAssocArray = []12 27 unmodified lines40 }41 }42 }43 44- this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly)44+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)45 46 return paramAssoc47 }48 49 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {50- let regexp = this.root.buildRegExpStr()50+ let regexp = this.#root.buildRegExpStr()51 if (regexp === '') {52 return [/^$/, [], []] // never match53 }54 20 unmodified linesmodified:src/router/smart-router/router.ts+14 added-12 removed
1 unmodified line2 import { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from '../../router'3 4 export class SmartRouter<T> implements Router<T> {5 name: string = 'SmartRouter'6- routers: Router<T>[] = []7- routes?: [string, string, T][] = []6+ #routers: Router<T>[] = []7+ #routes?: [string, string, T][] = []8 9- constructor(init: Pick<SmartRouter<T>, 'routers'>) {10- Object.assign(this, init)9+ constructor(init: { routers: Router<T>[] }) {10+ this.#routers = init.routers11 }12 13 add(method: string, path: string, handler: T) {14- if (!this.routes) {14+ if (!this.#routes) {15 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)16 }17 18- this.routes.push([method, path, handler])18+ this.#routes.push([method, path, handler])19 }20 21 match(method: string, path: string): Result<T> {22- if (!this.routes) {22+ if (!this.#routes) {23 throw new Error('Fatal error')24 }25 26- const { routers, routes } = this26+ const routers = this.#routers27+ const routes = this.#routes28+29 const len = routers.length30 let i = 031 let res32 for (; i < len; i++) {10 unmodified lines43 throw e44 }45 46 this.match = router.match.bind(router)45- this.routers = [router]46- this.routes = undefined47+ this.#routers = [router]48+ this.#routes = undefined49 break50 }51 52 if (i === len) {7 unmodified lines60 return res as Result<T>61 }62 63 get activeRouter(): Router<T> {62- if (this.routes || this.routers.length !== 1) {64+ if (this.#routes || this.#routers.length !== 1) {65 throw new Error('No active router has been determined yet.')66 }67 66- return this.routers[0]68+ return this.#routers[0]69 }70 }modified:src/router/trie-router/node.ts+37 added-37 removed
12 unmodified lines13 params: Record<string, string>14 }15 16 export class Node<T> {17- methods: Record<string, HandlerSet<T>>[]17+ #methods: Record<string, HandlerSet<T>>[]18 19- children: Record<string, Node<T>>20- patterns: Pattern[]21- order: number = 022- params: Record<string, string> = Object.create(null)19+ #children: Record<string, Node<T>>20+ #patterns: Pattern[]21+ #order: number = 022+ #params: Record<string, string> = Object.create(null)23 24 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {25- this.children = children || Object.create(null)26- this.methods = []25+ this.#children = children || Object.create(null)26+ this.#methods = []27 if (method && handler) {28 const m: Record<string, HandlerSet<T>> = Object.create(null)29 m[method] = { handler, possibleKeys: [], score: 0 }30- this.methods = [m]30+ this.#methods = [m]31 }32- this.patterns = []32+ this.#patterns = []33 }34 35 insert(method: string, path: string, handler: T): Node<T> {36- this.order = ++this.order36+ this.#order = ++this.#order37 38 // eslint-disable-next-line @typescript-eslint/no-this-alias39 let curNode: Node<T> = this40 const parts = splitRoutingPath(path)2 unmodified lines43 44 for (let i = 0, len = parts.length; i < len; i++) {45 const p: string = parts[i]46 47- if (Object.keys(curNode.children).includes(p)) {48- curNode = curNode.children[p]47+ if (Object.keys(curNode.#children).includes(p)) {48+ curNode = curNode.#children[p]49 const pattern = getPattern(p)50 if (pattern) {51 possibleKeys.push(pattern[1])52 }53 continue54 }55 56- curNode.children[p] = new Node()56+ curNode.#children[p] = new Node()57 58 const pattern = getPattern(p)59 if (pattern) {60- curNode.patterns.push(pattern)60+ curNode.#patterns.push(pattern)61 possibleKeys.push(pattern[1])62 }63- curNode = curNode.children[p]63+ curNode = curNode.#children[p]64 }65 66 const m: Record<string, HandlerSet<T>> = Object.create(null)67 68 const handlerSet: HandlerSet<T> = {69 handler,70 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),71- score: this.order,71+ score: this.#order,72 }73 74 m[method] = handlerSet75- curNode.methods.push(m)75+ curNode.#methods.push(m)76 77 return curNode78 }79 4 unmodified lines84 nodeParams: Record<string, string>,85 params: Record<string, string>86 ): HandlerParamsSet<T>[] {87 const handlerSets: HandlerParamsSet<T>[] = []88- for (let i = 0, len = node.methods.length; i < len; i++) {89- const m = node.methods[i]88+ for (let i = 0, len = node.#methods.length; i < len; i++) {89+ const m = node.#methods[i]90 const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>91 const processedSet: Record<number, boolean> = {}92 if (handlerSet !== undefined) {93 handlerSet.params = Object.create(null)12 unmodified lines106 }107 108 search(method: string, path: string): [[T, Params][]] {109 const handlerSets: HandlerParamsSet<T>[] = []110- this.params = Object.create(null)110+ this.#params = Object.create(null)111 112 // eslint-disable-next-line @typescript-eslint/no-this-alias113 const curNode: Node<T> = this114 let curNodes = [curNode]5 unmodified lines120 const tempNodes: Node<T>[] = []121 122 for (let j = 0, len2 = curNodes.length; j < len2; j++) {123 const node = curNodes[j]124- const nextNode = node.children[part]124+ const nextNode = node.#children[part]125 126 if (nextNode) {127- nextNode.params = node.params127+ nextNode.#params = node.#params128 if (isLast) {129 // '/hello/*' => match '/hello'130- if (nextNode.children['*']) {130+ if (nextNode.#children['*']) {131 handlerSets.push(132 ...this.#getHandlerSets(133- nextNode.children['*'],133+ nextNode.#children['*'],134 method,135- node.params,135+ node.#params,136 Object.create(null)137 )138 )139 }140 handlerSets.push(141- ...this.#getHandlerSets(nextNode, method, node.params, Object.create(null))141+ ...this.#getHandlerSets(nextNode, method, node.#params, Object.create(null))142 )143 } else {144 tempNodes.push(nextNode)145 }146 }147 148- for (let k = 0, len3 = node.patterns.length; k < len3; k++) {149- const pattern = node.patterns[k]148+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {149+ const pattern = node.#patterns[k]150 151- const params = { ...node.params }151+ const params = { ...node.#params }152 153 // Wildcard154 // '/hello/*/foo' => match /hello/bar/foo155 if (pattern === '*') {156- const astNode = node.children['*']156+ const astNode = node.#children['*']157 if (astNode) {158 handlerSets.push(159- ...this.#getHandlerSets(astNode, method, node.params, Object.create(null))159+ ...this.#getHandlerSets(astNode, method, node.#params, Object.create(null))160 )161 tempNodes.push(astNode)162 }163 continue4 unmodified lines168 }169 170 const [key, name, matcher] = pattern171 172- const child = node.children[key]172+ const child = node.#children[key]173 174 // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js175 const restPathString = parts.slice(i).join('/')176 if (matcher instanceof RegExp && matcher.test(restPathString)) {177 params[name] = restPathString178- handlerSets.push(...this.#getHandlerSets(child, method, node.params, params))178+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params))179 continue180 }181 182 if (matcher === true || matcher.test(part)) {183 params[name] = part184 if (isLast) {185- handlerSets.push(...this.#getHandlerSets(child, method, params, node.params))186- if (child.children['*']) {185+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params))186+ if (child.#children['*']) {187 handlerSets.push(188- ...this.#getHandlerSets(child.children['*'], method, params, node.params)188+ ...this.#getHandlerSets(child.#children['*'], method, params, node.#params)189 )190 }191 } else {192- child.params = params192+ child.#params = params193 tempNodes.push(child)194 }195 }196 }11 unmodified linesmodified:src/router/trie-router/router.ts+5 added-5 removed
2 unmodified lines3456778910101112131415161717181920212222232425262627282 unmodified linesimport { Node } from './node'
export class TrieRouter<T> implements Router<T> { name: string = 'TrieRouter' node: Node<T> #node: Node<T>
constructor() { this.node = new Node() this.#node = new Node() }
add(method: string, path: string, handler: T) { const results = checkOptionalParameter(path) if (results) { for (let i = 0, len = results.length; i < len; i++) { this.node.insert(method, results[i], handler) this.#node.insert(method, results[i], handler) } return }
this.node.insert(method, path, handler) this.#node.insert(method, path, handler) }
match(method: string, path: string): Result<T> { return this.node.search(method, path) return this.#node.search(method, path) }}