@formvk/path 0.0.0-stage → 0.1.0

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/src/index.ts ADDED
@@ -0,0 +1,583 @@
1
+ import {
2
+ deleteInByDestructor,
3
+ existInByDestructor,
4
+ getDestructor,
5
+ getInByDestructor,
6
+ setInByDestructor,
7
+ } from './destructor'
8
+ import { Matcher } from './matcher'
9
+ import { Parser } from './parser'
10
+ import { isArr, isEqual, isFn, isNum, isObj, isRegExp, isStr } from './shared'
11
+ import type { MatcherFunction, Node, Pattern, Segments } from './types'
12
+
13
+ const pathCache = new Map()
14
+
15
+ const isMatcher = Symbol('PATH_MATCHER')
16
+
17
+ function isMatcherFunction(val: any): val is MatcherFunction {
18
+ return isFn(val) && (val as { [isMatcher]?: boolean })[isMatcher] === true
19
+ }
20
+
21
+ function isValid(val: any) {
22
+ return val !== undefined && val !== null
23
+ }
24
+
25
+ interface ParsedPattern {
26
+ entire: string | RegExp
27
+ segments: Segments
28
+ isRegExp: boolean
29
+ isMatchPattern: boolean
30
+ isWildMatchPattern: boolean
31
+ haveRelativePattern: boolean
32
+ haveExcludePattern: boolean
33
+ tree?: Node
34
+ }
35
+
36
+ function isSimplePath(val: string) {
37
+ return (
38
+ val.indexOf('*') === -1 &&
39
+ val.indexOf('~') === -1 &&
40
+ val.indexOf('[') === -1 &&
41
+ val.indexOf(']') === -1 &&
42
+ val.indexOf(',') === -1 &&
43
+ val.indexOf(':') === -1 &&
44
+ val.indexOf(' ') === -1 &&
45
+ val[0] !== '.'
46
+ )
47
+ }
48
+
49
+ function isAssignable(val: any) {
50
+ return typeof val === 'object' || typeof val === 'function'
51
+ }
52
+
53
+ function isNumberIndex(val: any) {
54
+ return isStr(val) ? /^\d+$/.test(val) : isNum(val)
55
+ }
56
+
57
+ function getIn(segments: Segments, source: any) {
58
+ for (let i = 0; i < segments.length; i++) {
59
+ const index = segments[i]
60
+ const rules = getDestructor(index as string)
61
+ if (!rules) {
62
+ if (!isValid(source)) return
63
+ source = source[index]
64
+ } else {
65
+ source = getInByDestructor(source, rules, { setIn, getIn })
66
+ break
67
+ }
68
+ }
69
+ return source
70
+ }
71
+
72
+ function setIn(segments: Segments, source: any, value: any) {
73
+ for (let i = 0; i < segments.length; i++) {
74
+ const index = segments[i]
75
+ const rules = getDestructor(index as string)
76
+ if (!rules) {
77
+ if (!isValid(source) || !isAssignable(source)) return
78
+ if (isArr(source) && !isNumberIndex(index)) {
79
+ return
80
+ }
81
+ if (!isValid(source[index])) {
82
+ if (value === undefined) {
83
+ if (source[index] === null) source[index] = value
84
+ return
85
+ }
86
+ if (i < segments.length - 1) {
87
+ source[index] = isNum(segments[i + 1]) ? [] : {}
88
+ }
89
+ }
90
+ if (i === segments.length - 1) {
91
+ source[index] = value
92
+ }
93
+ source = source[index]
94
+ } else {
95
+ setInByDestructor(source, rules, value, { setIn, getIn })
96
+ break
97
+ }
98
+ }
99
+ }
100
+
101
+ function deleteIn(segments: Segments, source: any) {
102
+ for (let i = 0; i < segments.length; i++) {
103
+ const index = segments[i]
104
+ const rules = getDestructor(index as string)
105
+ if (!rules) {
106
+ if (i === segments.length - 1 && isValid(source)) {
107
+ delete source[index]
108
+ return
109
+ }
110
+
111
+ if (!isValid(source) || !isAssignable(source)) return
112
+ source = source[index]
113
+ if (!isObj(source)) {
114
+ return
115
+ }
116
+ } else {
117
+ deleteInByDestructor(source, rules, {
118
+ setIn,
119
+ getIn,
120
+ deleteIn,
121
+ })
122
+ break
123
+ }
124
+ }
125
+ }
126
+
127
+ const hasOwnProperty = Object.prototype.hasOwnProperty
128
+
129
+ function existIn(segments: Segments, source: any, start: number | Path) {
130
+ if (start instanceof Path) {
131
+ start = start.length
132
+ }
133
+ for (let i = start; i < segments.length; i++) {
134
+ const index = segments[i]
135
+ const rules = getDestructor(index as string)
136
+ if (!rules) {
137
+ if (i === segments.length - 1) {
138
+ return hasOwnProperty.call(source, index)
139
+ }
140
+
141
+ if (!isValid(source) || !isAssignable(source)) return false
142
+ source = source[index]
143
+
144
+ if (!isObj(source)) {
145
+ return false
146
+ }
147
+ } else {
148
+ return existInByDestructor(source, rules, start, {
149
+ setIn,
150
+ getIn,
151
+ deleteIn,
152
+ existIn,
153
+ })
154
+ }
155
+ }
156
+ }
157
+
158
+ function parse(pattern: Pattern, base?: Pattern): ParsedPattern {
159
+ if (pattern instanceof Path) {
160
+ return {
161
+ entire: pattern.entire,
162
+ segments: pattern.segments.slice(),
163
+ isRegExp: false,
164
+ haveRelativePattern: pattern.haveRelativePattern,
165
+ isWildMatchPattern: pattern.isWildMatchPattern,
166
+ isMatchPattern: pattern.isMatchPattern,
167
+ haveExcludePattern: pattern.haveExcludePattern,
168
+ tree: pattern.tree,
169
+ }
170
+ } else if (isStr(pattern)) {
171
+ if (!pattern) {
172
+ return {
173
+ entire: '',
174
+ segments: [],
175
+ isRegExp: false,
176
+ isWildMatchPattern: false,
177
+ haveRelativePattern: false,
178
+ haveExcludePattern: false,
179
+ isMatchPattern: false,
180
+ }
181
+ }
182
+ if (isSimplePath(pattern)) {
183
+ return {
184
+ entire: pattern,
185
+ segments: pattern.split('.'),
186
+ isRegExp: false,
187
+ haveRelativePattern: false,
188
+ isWildMatchPattern: false,
189
+ haveExcludePattern: false,
190
+ isMatchPattern: false,
191
+ }
192
+ }
193
+ const parser = new Parser(pattern, Path.parse(base))
194
+ const tree = parser.parse()
195
+ if (!parser.isMatchPattern) {
196
+ const segments = parser.data.segments
197
+ return {
198
+ entire: segments.join('.'),
199
+ segments,
200
+ tree,
201
+ isRegExp: false,
202
+ haveRelativePattern: parser.haveRelativePattern,
203
+ isWildMatchPattern: false,
204
+ haveExcludePattern: false,
205
+ isMatchPattern: false,
206
+ }
207
+ } else {
208
+ return {
209
+ entire: pattern,
210
+ segments: [],
211
+ isRegExp: false,
212
+ haveRelativePattern: false,
213
+ isWildMatchPattern: parser.isWildMatchPattern,
214
+ haveExcludePattern: parser.haveExcludePattern,
215
+ isMatchPattern: true,
216
+ tree,
217
+ }
218
+ }
219
+ } else if (isMatcherFunction(pattern)) {
220
+ return parse(pattern.path)
221
+ } else if (isArr(pattern)) {
222
+ return {
223
+ entire: pattern.join('.'),
224
+ segments: pattern.reduce<Segments>((buf, key) => {
225
+ return buf.concat(parseString(key))
226
+ }, []),
227
+ isRegExp: false,
228
+ haveRelativePattern: false,
229
+ isWildMatchPattern: false,
230
+ haveExcludePattern: false,
231
+ isMatchPattern: false,
232
+ }
233
+ } else if (isRegExp(pattern)) {
234
+ return {
235
+ entire: pattern,
236
+ segments: [],
237
+ isRegExp: true,
238
+ haveRelativePattern: false,
239
+ isWildMatchPattern: false,
240
+ haveExcludePattern: false,
241
+ isMatchPattern: true,
242
+ }
243
+ } else {
244
+ return {
245
+ entire: '',
246
+ isRegExp: false,
247
+ segments: pattern !== undefined ? [pattern] : [],
248
+ haveRelativePattern: false,
249
+ isWildMatchPattern: false,
250
+ haveExcludePattern: false,
251
+ isMatchPattern: false,
252
+ }
253
+ }
254
+ }
255
+
256
+ function parseString(source: any): any {
257
+ if (isStr(source)) {
258
+ source = source.replace(/\s*/g, '')
259
+ try {
260
+ const { segments, isMatchPattern } = parse(source)
261
+ return !isMatchPattern ? segments : source
262
+ } catch (e) {
263
+ return source
264
+ }
265
+ } else if (source instanceof Path) {
266
+ return source.segments
267
+ }
268
+ return source
269
+ }
270
+
271
+ export class Path {
272
+ public entire: string | RegExp
273
+ public segments: Segments
274
+ public isMatchPattern: boolean
275
+ public isWildMatchPattern: boolean
276
+ public isRegExp: boolean
277
+ public haveRelativePattern: boolean
278
+ public haveExcludePattern: boolean
279
+ public matchScore = 0
280
+ public tree: Node
281
+ private matchCache: any
282
+ private includesCache: any
283
+
284
+ constructor(input: Pattern, base?: Pattern) {
285
+ const {
286
+ tree,
287
+ segments,
288
+ entire,
289
+ isRegExp,
290
+ isMatchPattern,
291
+ isWildMatchPattern,
292
+ haveRelativePattern,
293
+ haveExcludePattern,
294
+ } = parse(input, base)
295
+ this.entire = entire
296
+ this.segments = segments
297
+ this.isMatchPattern = isMatchPattern
298
+ this.isWildMatchPattern = isWildMatchPattern
299
+ this.haveRelativePattern = haveRelativePattern
300
+ this.isRegExp = isRegExp
301
+ this.haveExcludePattern = haveExcludePattern
302
+ this.tree = tree as Node
303
+ this.matchCache = new Map()
304
+ this.includesCache = new Map()
305
+ }
306
+
307
+ toString() {
308
+ return this.entire?.toString()
309
+ }
310
+
311
+ toArr() {
312
+ return this.segments?.slice()
313
+ }
314
+
315
+ get length() {
316
+ return this.segments.length
317
+ }
318
+
319
+ concat = (...args: Pattern[]) => {
320
+ if (this.isMatchPattern || this.isRegExp) {
321
+ throw new Error(`${this.entire} cannot be concat`)
322
+ }
323
+ const path = new Path('')
324
+ path.segments = this.segments.concat(...args.map(s => parseString(s)))
325
+ path.entire = path.segments.join('.')
326
+ return path
327
+ }
328
+
329
+ slice = (start?: number, end?: number) => {
330
+ if (this.isMatchPattern || this.isRegExp) {
331
+ throw new Error(`${this.entire} cannot be slice`)
332
+ }
333
+ const path = new Path('')
334
+ path.segments = this.segments.slice(start, end)
335
+ path.entire = path.segments.join('.')
336
+ return path
337
+ }
338
+
339
+ push = (...items: Pattern[]) => {
340
+ return this.concat(...items)
341
+ }
342
+
343
+ pop = () => {
344
+ if (this.isMatchPattern || this.isRegExp) {
345
+ throw new Error(`${this.entire} cannot be pop`)
346
+ }
347
+ return new Path(this.segments.slice(0, this.segments.length - 1))
348
+ }
349
+
350
+ splice = (start: number, deleteCount?: number, ...items: Array<string | number>) => {
351
+ if (this.isMatchPattern || this.isRegExp) {
352
+ throw new Error(`${this.entire} cannot be splice`)
353
+ }
354
+ items = items.reduce((buf, item) => buf.concat(parseString(item)), [])
355
+ const segments_ = this.segments.slice()
356
+ segments_.splice(start, deleteCount!, ...items)
357
+ return new Path(segments_)
358
+ }
359
+
360
+ forEach = (callback: (key: string | number) => any) => {
361
+ if (this.isMatchPattern || this.isRegExp) {
362
+ throw new Error(`${this.entire} cannot be each`)
363
+ }
364
+ this.segments.forEach(callback)
365
+ }
366
+
367
+ map = (callback: (key: string | number) => any) => {
368
+ if (this.isMatchPattern || this.isRegExp) {
369
+ throw new Error(`${this.entire} cannot be map`)
370
+ }
371
+ return this.segments.map(callback)
372
+ }
373
+
374
+ reduce = <T>(callback: (buf: T, item: string | number, index: number) => T, initial: T): T => {
375
+ if (this.isMatchPattern || this.isRegExp) {
376
+ throw new Error(`${this.entire} cannot be reduce`)
377
+ }
378
+ return this.segments.reduce(callback, initial)
379
+ }
380
+
381
+ parent = () => {
382
+ return this.slice(0, this.length - 1)
383
+ }
384
+
385
+ includes = (pattern: Pattern) => {
386
+ const { entire, segments, isMatchPattern } = Path.parse(pattern)
387
+ const cache = this.includesCache.get(entire)
388
+ if (cache !== undefined) return cache
389
+ const cacheWith = (value: boolean): boolean => {
390
+ this.includesCache.set(entire, value)
391
+ return value
392
+ }
393
+ if (this.isMatchPattern) {
394
+ if (!isMatchPattern) {
395
+ return cacheWith(this.match(segments))
396
+ } else {
397
+ throw new Error(`${this.entire} cannot be used to match ${entire}`)
398
+ }
399
+ }
400
+ if (isMatchPattern) {
401
+ throw new Error(`${this.entire} cannot be used to match ${entire}`)
402
+ }
403
+ if (segments.length > this.segments.length) return cacheWith(false)
404
+ for (let i = 0; i < segments.length; i++) {
405
+ if (!isEqual(String(segments[i]), String(this.segments[i]))) {
406
+ return cacheWith(false)
407
+ }
408
+ }
409
+ return cacheWith(true)
410
+ }
411
+
412
+ transform = <T>(regexp: string | RegExp, callback: (...args: string[]) => T): T | string => {
413
+ if (!isFn(callback)) return ''
414
+ if (this.isMatchPattern) {
415
+ throw new Error(`${this.entire} cannot be transformed`)
416
+ }
417
+ const reg = new RegExp(regexp)
418
+ const args = this.segments.filter(key => reg.test(key as string)) as string[]
419
+ return callback(...args)
420
+ }
421
+
422
+ match = (pattern: Pattern): boolean => {
423
+ const path = Path.parse(pattern)
424
+ const cache = this.matchCache.get(path.entire)
425
+ if (cache !== undefined) {
426
+ if (cache.record && cache.record.score !== undefined) {
427
+ this.matchScore = cache.record.score
428
+ }
429
+ return cache.matched
430
+ }
431
+ const cacheWith = (value: any) => {
432
+ this.matchCache.set(path.entire, value)
433
+ return value
434
+ }
435
+ if (path.isMatchPattern) {
436
+ if (this.isMatchPattern) {
437
+ throw new Error(`${path.entire} cannot match ${this.entire}`)
438
+ } else {
439
+ this.matchScore = 0
440
+ return cacheWith(path.match(this.segments))
441
+ }
442
+ } else {
443
+ if (this.isMatchPattern) {
444
+ if (this.isRegExp) {
445
+ try {
446
+ return (this.entire as RegExp).test(String(path.entire))
447
+ } finally {
448
+ ;(this.entire as RegExp).lastIndex = 0
449
+ }
450
+ }
451
+ const record = {
452
+ score: 0,
453
+ }
454
+ const result = cacheWith(new Matcher(this.tree, record).match(path.segments))
455
+ this.matchScore = record.score
456
+ return result.matched
457
+ } else {
458
+ const record = {
459
+ score: 0,
460
+ }
461
+ const result = cacheWith(Matcher.matchSegments(this.segments, path.segments, record))
462
+ this.matchScore = record.score
463
+ return result.matched
464
+ }
465
+ }
466
+ }
467
+
468
+ //别名组匹配
469
+ matchAliasGroup = (name: Pattern, alias: Pattern) => {
470
+ const namePath = Path.parse(name)
471
+ const aliasPath = Path.parse(alias)
472
+ const nameMatched = this.match(namePath)
473
+ const nameMatchedScore = this.matchScore
474
+ const aliasMatched = this.match(aliasPath)
475
+ const aliasMatchedScore = this.matchScore
476
+ if (this.haveExcludePattern) {
477
+ if (nameMatchedScore >= aliasMatchedScore) {
478
+ return nameMatched
479
+ } else {
480
+ return aliasMatched
481
+ }
482
+ } else {
483
+ return nameMatched || aliasMatched
484
+ }
485
+ }
486
+
487
+ existIn = (source?: any, start: number | Path = 0) => {
488
+ return existIn(this.segments, source, start)
489
+ }
490
+
491
+ getIn = (source?: any) => {
492
+ return getIn(this.segments, source)
493
+ }
494
+
495
+ setIn = (source?: any, value?: any) => {
496
+ setIn(this.segments, source, value)
497
+ return source
498
+ }
499
+
500
+ deleteIn = (source?: any) => {
501
+ deleteIn(this.segments, source)
502
+ return source
503
+ }
504
+
505
+ ensureIn = (source?: any, defaults?: any) => {
506
+ const results = this.getIn(source)
507
+ if (results === undefined) {
508
+ this.setIn(source, defaults)
509
+ return this.getIn(source)
510
+ }
511
+ return results
512
+ }
513
+
514
+ static match(pattern: Pattern) {
515
+ const path = Path.parse(pattern)
516
+ const matcher = ((target: Pattern) => {
517
+ return path.match(target)
518
+ }) as MatcherFunction & { [isMatcher]: true }
519
+ matcher[isMatcher] = true
520
+ matcher.path = path
521
+ return matcher
522
+ }
523
+
524
+ static isPathPattern(target: any): target is Pattern {
525
+ return !!(isStr(target) || isArr(target) || isRegExp(target) || isMatcherFunction(target))
526
+ }
527
+
528
+ static transform<T>(pattern: Pattern, regexp: string | RegExp, callback: (...args: string[]) => T): any {
529
+ return Path.parse(pattern).transform(regexp, callback)
530
+ }
531
+
532
+ static parse(path: Pattern = '', base?: Pattern): Path {
533
+ if (path instanceof Path) {
534
+ const found = pathCache.get(path.entire)
535
+ if (found) {
536
+ return found
537
+ } else {
538
+ pathCache.set(path.entire, path)
539
+ return path
540
+ }
541
+ } else if (isMatcherFunction(path)) {
542
+ return Path.parse(path.path)
543
+ } else {
544
+ const key_ = base ? Path.parse(base) : ''
545
+ const key = `${path}:${key_}`
546
+ const found = pathCache.get(key)
547
+ if (found) {
548
+ return found
549
+ } else {
550
+ path = new Path(path, base)
551
+ pathCache.set(key, path)
552
+ return path
553
+ }
554
+ }
555
+ }
556
+
557
+ static getIn = (source: any, pattern: Pattern) => {
558
+ const path = Path.parse(pattern)
559
+ return path.getIn(source)
560
+ }
561
+
562
+ static setIn = (source: any, pattern: Pattern, value: any) => {
563
+ const path = Path.parse(pattern)
564
+ return path.setIn(source, value)
565
+ }
566
+
567
+ static deleteIn = (source: any, pattern: Pattern) => {
568
+ const path = Path.parse(pattern)
569
+ return path.deleteIn(source)
570
+ }
571
+
572
+ static existIn = (source: any, pattern: Pattern, start?: number | Path) => {
573
+ const path = Path.parse(pattern)
574
+ return path.existIn(source, start)
575
+ }
576
+
577
+ static ensureIn = (source: any, pattern: Pattern, defaultValue?: any) => {
578
+ const path = Path.parse(pattern)
579
+ return path.ensureIn(source, defaultValue)
580
+ }
581
+ }
582
+
583
+ export type { Pattern }