-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypeAssert.js
388 lines (347 loc) · 11.2 KB
/
typeAssert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
'use strict'
/* eslint-disable no-extend-native, no-use-before-define, func-names, no-shadow, no-throw-literal */
export const TypeStrings = {
String: typeof '',
Symbol: typeof Symbol(''),
Number: typeof 0,
Object: typeof {},
Boolean: typeof true,
Function: typeof (() => {}),
Undefined: typeof undefined,
Array: Array.prototype.constructor.name,
Date: Date.prototype.constructor.name,
RegExp: RegExp.prototype.constructor.name
}
const removeTail = (srcText) => {
const tail = srcText.slice(-1)
if (tail === '?') {
return [srcText.slice(0, -1), true]
}
return [srcText, false]
}
const typeAssertError = (path, message) => {
const errMsg = `Type assertion failed: "${path}": ${message}`
throw new Error(errMsg)
}
const assertEquals = (path, expected, got) => {
if (expected !== got) {
typeAssertError(path, `expected value "${expected}", got "${got}"`)
}
}
const assertTypeEqImpl = (path, expected, got) => {
if (expected !== got) {
typeAssertError(path, `expected type "${expected}", got "${got}"`)
}
}
const assertTypeEqImpl2 = (path, expectedCtor, gotCtor, expected) => {
if (expectedCtor !== gotCtor) {
typeAssertError(
path,
`expected type "${expected}", checking using ctor "${expectedCtor.name}", got "${gotCtor.name}"`
)
}
}
const formatSumTypeError = (errors) => {
let ret = 'sum type check failure:\n'
for (const [idx, error] of Object.entries(errors)) {
ret = `${ret} - branch ${idx} failed for: { ${error} }\n`
}
return ret
}
const typeAssertImpl = (path, object, assertion) => {
const assertionType = typeof assertion
if (assertion === null || assertion === 'undefined') {
if (object !== null && object !== undefined) {
typeAssertError(path, `expected "null" or "undefined" value, got "${typeof object}"`)
}
} else if (assertionType === TypeStrings.String) {
const [type, nullable] = removeTail(assertion)
if (nullable) {
if (type === TypeStrings.Undefined) {
typeAssertError(path, '"undefined" type cannot be nullable')
}
if (object === null || object === undefined) {
return
}
}
if (object === null) {
typeAssertError(path, 'unexpected "null" value')
}
if (object !== undefined) {
switch (type) {
case TypeStrings.Array:
assertTypeEqImpl2(path, Array.prototype.constructor, object.constructor, type)
return
case TypeStrings.Date:
assertTypeEqImpl2(path, Date.prototype.constructor, object.constructor, type)
return
case TypeStrings.RegExp:
assertTypeEqImpl2(path, RegExp.prototype.constructor, object.constructor, type)
return
default:
// fall through
}
}
assertTypeEqImpl(path, type, typeof object)
} else if (assertionType === TypeStrings.Function) {
const assertResult = assertion(object)
if (assertResult !== true) {
typeAssertError(path, assertResult)
}
} else if (assertion.constructor === NullableType.prototype.constructor) {
if (object === null || object === undefined) {
return
}
typeAssertImpl(path, object, assertion.origin)
} else if (assertion.constructor === SumType.prototype.constructor) {
const failures = []
for (const type of assertion.types) {
try {
typeAssertImpl(path, object, type, true)
} catch (error) {
failures.push(error)
continue
}
return
}
typeAssertError(path, formatSumTypeError(failures))
} else if (assertion.constructor === ChainType.prototype.constructor) {
// eslint-disable-next-line guard-for-in
for (const partIdx in assertion.types) {
typeAssertImpl(`${path}:<${partIdx}>`, object, assertion.types[partIdx])
}
} else if (assertion.constructor === ValueAssertion.prototype.constructor) {
assertEquals(`${path}:value`, assertion.value, object)
} else if (assertion.constructor === ObjectValueAssertion.prototype.constructor) {
typeAssertImpl(path, object, {})
for (const [key, value] of Object.entries(object)) {
typeAssertImpl(`${path}.${key}`, value, assertion.valueAssertion)
}
} else if (object === undefined) {
typeAssertError(path, 'unexpected "undefined" value')
} else if (object === null) {
typeAssertError(path, 'unexpected "null" value')
} else if (assertion.constructor === Array.prototype.constructor) {
assertTypeEqImpl2(path, Array.prototype.constructor, object.constructor, TypeStrings.Array)
if (assertion.length === 0) {
// fallthrough
} else if (assertion.length === 1) {
for (const [idx, element] of Object.entries(object)) {
typeAssertImpl(`${path}[${idx}]`, element, assertion[0])
}
} else {
typeAssertError(path, '"array" type assertion should only have one element')
}
} else if (assertionType === TypeStrings.Object
&& assertion.constructor === Object.prototype.constructor) {
for (const [field, fieldAssertion] of Object.entries(assertion)) {
typeAssertImpl(`${path}.${field}`, object[field], fieldAssertion)
}
} else {
typeAssertError(path, 'invalid assertion')
}
}
export const typeAssert = (object, assertion) => typeAssertImpl('object', object, assertion, false)
export const NullableType = (function () {
function NullableType(origin) {
this.origin = origin
}
return NullableType
}())
export const SumType = (function () {
function SumType(types) {
this.types = types
}
return SumType
}())
export const ChainType = (function () {
function ChainType(types) {
this.types = types
}
return ChainType
}())
export const ValueAssertion = (function() {
function ValueAssertion(value) {
this.value = value
}
return ValueAssertion
}())
export const ObjectValueAssertion = (function() {
function ObjectValueAssertion(valueAssertion) {
this.valueAssertion = valueAssertion
}
return ObjectValueAssertion
}())
export const enableChainAPI = methodNames => {
let orNullName = 'orNull'
let sumWithName = 'sumWith'
let chainWithName = 'chainWith'
let assertValueName = 'assertValue'
let assertObjectValueName = 'assertObjectValue'
if (methodNames) {
const { orNull, sumWith, chainWith, assertValue, assertObjectValue } = methodNames
orNullName = orNull || orNullName
sumWithName = sumWith || sumWithName
chainWithName = chainWith || chainWithName
assertValueName = assertValue || assertValueName
assertObjectValueName = assertObjectValue || assertObjectValueName
}
const checkChainNotEndedByValueAssertion = types => {
if (types[types.length - 1].constructor === ValueAssertion.prototype.constructor) {
typeAssertError('<onbuild> ChainType.prototype.orNull', `should append any assertion after ${assertValueName}`)
}
}
Object.defineProperty(Object.prototype, orNullName, {
enumerable: false,
configurable: false,
writable: false,
value() {
if (this.constructor === NullableType.prototype.constructor) {
typeAssertError('<onbuild> Object.prototype.orNull', 'trying to nest nullable modification')
}
return new NullableType(this)
}
})
Object.defineProperty(String.prototype, orNullName, {
enumerable: false,
configurable: false,
writable: false,
value() {
if (`${this}` === TypeStrings.Undefined) {
typeAssertError('<onbuild> String.prototype.orNull', '"undefined" type cannot be nullable')
} else if (`${this}`.endsWith('?')) {
typeAssertError('<onbuild> String.prototype.orNull', 'trying to nest nullable modification')
}
return `${this}?`
}
})
Object.defineProperty(SumType.prototype, sumWithName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
if (that.constructor === SumType.prototype.constructor) {
return new SumType([...this.types, ...that.types])
} else {
return new SumType([...this.types, that])
}
}
})
Object.defineProperty(Object.prototype, sumWithName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
return (new SumType([this]))[sumWithName](that)
}
})
Object.defineProperty(String.prototype, sumWithName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
return (new SumType([`${this}`]))[sumWithName](that)
}
})
Object.defineProperty(ChainType.prototype, chainWithName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
checkChainNotEndedByValueAssertion(this.types)
if (that.constructor === ChainType.prototype.constructor) {
return new ChainType([...this.types, ...that.types])
} else {
return new ChainType([...this.types, that])
}
}
})
Object.defineProperty(Object.prototype, chainWithName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
let self = this
let nullable = false
if (self.constructor === NullableType.prototype.constructor) {
nullable = true
self = self.origin
return new NullableType(self[chainWithName](that))
}
return (new ChainType([self]))[chainWithName](that)
}
})
Object.defineProperty(String.prototype, chainWithName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
let nullable = false
let self = `${this}`
if (self.endsWith('?')) {
nullable = true
self = self.slice(0, -1)
}
let ret = (new ChainType([self]))[chainWithName](that)
if (nullable) {
ret = new NullableType(ret)
}
return ret
}
})
Object.defineProperty(Object.prototype, assertValueName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
return new ChainType([this, new ValueAssertion(that)])
}
})
Object.defineProperty(ChainType.prototype, assertValueName, {
enumerable: false,
configurable: false,
writable: false,
value(that) {
checkChainNotEndedByValueAssertion(this.types)
return new ChainType([...this.types, new ValueAssertion(that)])
}
})
Object.defineProperty(Object.prototype, assertObjectValueName, {
enumerable: false,
configurable: false,
writable: false,
value(valueAssertion) {
if (this.constructor !== Object.prototype.constructor) {
typeAssertError(
'<onbuild> Object.prototype.assertObjectValue',
`cannot assert object values of "${this.constructor.name}"`
)
}
return new ObjectValueAssertion(valueAssertion)
}
})
Object.defineProperty(String.prototype, assertObjectValueName, {
enumerable: false,
configurable: false,
writable: false,
value(valueAssertion) {
let nullable = false
let self = `${this}`
if (self.endsWith('?')) {
nullable = true
self = self.slice(0, -1)
}
if (self !== 'object') {
typeAssertError(
'<onbuild> String.prototype.assertObjectValue',
`cannot assert object values of "${self}"`
)
}
let ret = new ObjectValueAssertion(valueAssertion)
if (nullable) {
ret = new NullableType(ret)
}
return ret
}
})
}