@nice2dev/ui-graphics 1.0.4 → 1.0.5

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.
Files changed (183) hide show
  1. package/dist/cjs/animation/AnimationEditor.js +1 -1
  2. package/dist/cjs/animation/Audience.js +1 -1
  3. package/dist/cjs/core/LocalUI.js +1 -1
  4. package/dist/cjs/core/yjsCollaboration.js +2 -2
  5. package/dist/cjs/core/yjsCollaboration.js.map +1 -1
  6. package/dist/cjs/game/GameAsset2dEditor.js +1 -1
  7. package/dist/cjs/node_modules/lib0/array.js +103 -0
  8. package/dist/cjs/node_modules/lib0/array.js.map +1 -0
  9. package/dist/cjs/node_modules/lib0/binary.js +42 -0
  10. package/dist/cjs/node_modules/lib0/binary.js.map +1 -0
  11. package/dist/cjs/node_modules/lib0/broadcastchannel.js +121 -0
  12. package/dist/cjs/node_modules/lib0/broadcastchannel.js.map +1 -0
  13. package/dist/cjs/node_modules/lib0/buffer.js +103 -0
  14. package/dist/cjs/node_modules/lib0/buffer.js.map +1 -0
  15. package/dist/cjs/node_modules/lib0/conditions.js +18 -0
  16. package/dist/cjs/node_modules/lib0/conditions.js.map +1 -0
  17. package/dist/cjs/node_modules/lib0/decoding.js +460 -0
  18. package/dist/cjs/node_modules/lib0/decoding.js.map +1 -0
  19. package/dist/cjs/node_modules/lib0/dom.js +55 -0
  20. package/dist/cjs/node_modules/lib0/dom.js.map +1 -0
  21. package/dist/cjs/node_modules/lib0/encoding.js +688 -0
  22. package/dist/cjs/node_modules/lib0/encoding.js.map +1 -0
  23. package/dist/cjs/node_modules/lib0/environment.js +129 -0
  24. package/dist/cjs/node_modules/lib0/environment.js.map +1 -0
  25. package/dist/cjs/node_modules/lib0/error.js +37 -0
  26. package/dist/cjs/node_modules/lib0/error.js.map +1 -0
  27. package/dist/cjs/node_modules/lib0/function.js +135 -0
  28. package/dist/cjs/node_modules/lib0/function.js.map +1 -0
  29. package/dist/cjs/node_modules/lib0/iterator.js +52 -0
  30. package/dist/cjs/node_modules/lib0/iterator.js.map +1 -0
  31. package/dist/cjs/node_modules/lib0/logging.common.js +63 -0
  32. package/dist/cjs/node_modules/lib0/logging.common.js.map +1 -0
  33. package/dist/cjs/node_modules/lib0/logging.js +128 -0
  34. package/dist/cjs/node_modules/lib0/logging.js.map +1 -0
  35. package/dist/cjs/node_modules/lib0/map.js +108 -0
  36. package/dist/cjs/node_modules/lib0/map.js.map +1 -0
  37. package/dist/cjs/node_modules/lib0/math.js +44 -0
  38. package/dist/cjs/node_modules/lib0/math.js.map +1 -0
  39. package/dist/cjs/node_modules/lib0/number.js +21 -0
  40. package/dist/cjs/node_modules/lib0/number.js.map +1 -0
  41. package/dist/cjs/node_modules/lib0/object.js +132 -0
  42. package/dist/cjs/node_modules/lib0/object.js.map +1 -0
  43. package/dist/cjs/node_modules/lib0/observable.js +168 -0
  44. package/dist/cjs/node_modules/lib0/observable.js.map +1 -0
  45. package/dist/cjs/node_modules/lib0/pair.js +33 -0
  46. package/dist/cjs/node_modules/lib0/pair.js.map +1 -0
  47. package/dist/cjs/node_modules/lib0/prng.js +95 -0
  48. package/dist/cjs/node_modules/lib0/prng.js.map +1 -0
  49. package/dist/cjs/node_modules/lib0/promise.js +33 -0
  50. package/dist/cjs/node_modules/lib0/promise.js.map +1 -0
  51. package/dist/cjs/node_modules/lib0/random.js +28 -0
  52. package/dist/cjs/node_modules/lib0/random.js.map +1 -0
  53. package/dist/cjs/node_modules/lib0/schema.js +1168 -0
  54. package/dist/cjs/node_modules/lib0/schema.js.map +1 -0
  55. package/dist/cjs/node_modules/lib0/set.js +12 -0
  56. package/dist/cjs/node_modules/lib0/set.js.map +1 -0
  57. package/dist/cjs/node_modules/lib0/storage.js +79 -0
  58. package/dist/cjs/node_modules/lib0/storage.js.map +1 -0
  59. package/dist/cjs/node_modules/lib0/string.js +94 -0
  60. package/dist/cjs/node_modules/lib0/string.js.map +1 -0
  61. package/dist/cjs/node_modules/lib0/symbol.js +15 -0
  62. package/dist/cjs/node_modules/lib0/symbol.js.map +1 -0
  63. package/dist/cjs/node_modules/lib0/time.js +18 -0
  64. package/dist/cjs/node_modules/lib0/time.js.map +1 -0
  65. package/dist/cjs/node_modules/lib0/trait/equality.js +32 -0
  66. package/dist/cjs/node_modules/lib0/trait/equality.js.map +1 -0
  67. package/dist/cjs/node_modules/lib0/url.js +20 -0
  68. package/dist/cjs/node_modules/lib0/url.js.map +1 -0
  69. package/dist/cjs/node_modules/lib0/webcrypto.js +8 -0
  70. package/dist/cjs/node_modules/lib0/webcrypto.js.map +1 -0
  71. package/dist/cjs/node_modules/y-protocols/auth.js +27 -0
  72. package/dist/cjs/node_modules/y-protocols/auth.js.map +1 -0
  73. package/dist/cjs/node_modules/y-protocols/awareness.js +277 -0
  74. package/dist/cjs/node_modules/y-protocols/awareness.js.map +1 -0
  75. package/dist/cjs/node_modules/y-protocols/sync.js +149 -0
  76. package/dist/cjs/node_modules/y-protocols/sync.js.map +1 -0
  77. package/dist/cjs/node_modules/y-websocket/src/y-websocket.js +521 -0
  78. package/dist/cjs/node_modules/y-websocket/src/y-websocket.js.map +1 -0
  79. package/dist/cjs/node_modules/yjs/dist/yjs.js +10399 -0
  80. package/dist/cjs/node_modules/yjs/dist/yjs.js.map +1 -0
  81. package/dist/cjs/packages/ui/dist/index.js +65997 -0
  82. package/dist/cjs/packages/ui/dist/index.js.map +1 -0
  83. package/dist/cjs/pixel/PixelEditor.js +1 -1
  84. package/dist/cjs/pixel/PixelEditorMenuBar.js +1 -1
  85. package/dist/cjs/pixel/PixelEditorRightPanel.js +1 -1
  86. package/dist/cjs/pixel/PixelEditorTimeline.js +1 -1
  87. package/dist/cjs/pixel/PixelEditorToolbar.js +1 -1
  88. package/dist/cjs/pixel/SpriteGeneratorPanel.js +1 -1
  89. package/dist/cjs/vector/VectorEditor.js +1 -1
  90. package/dist/cjs/vector/VectorEditorMenuBar.js +1 -1
  91. package/dist/cjs/vector/VectorEditorRightPanel.js +1 -1
  92. package/dist/esm/animation/AnimationEditor.js +5 -5
  93. package/dist/esm/animation/Audience.js +2 -2
  94. package/dist/esm/core/LocalUI.js +4 -4
  95. package/dist/esm/core/yjsCollaboration.js +2 -2
  96. package/dist/esm/core/yjsCollaboration.js.map +1 -1
  97. package/dist/esm/game/GameAsset2dEditor.js +19 -19
  98. package/dist/esm/node_modules/lib0/array.js +95 -0
  99. package/dist/esm/node_modules/lib0/array.js.map +1 -0
  100. package/dist/esm/node_modules/lib0/binary.js +30 -0
  101. package/dist/esm/node_modules/lib0/binary.js.map +1 -0
  102. package/dist/esm/node_modules/lib0/broadcastchannel.js +117 -0
  103. package/dist/esm/node_modules/lib0/broadcastchannel.js.map +1 -0
  104. package/dist/esm/node_modules/lib0/buffer.js +96 -0
  105. package/dist/esm/node_modules/lib0/buffer.js.map +1 -0
  106. package/dist/esm/node_modules/lib0/conditions.js +16 -0
  107. package/dist/esm/node_modules/lib0/conditions.js.map +1 -0
  108. package/dist/esm/node_modules/lib0/decoding.js +439 -0
  109. package/dist/esm/node_modules/lib0/decoding.js.map +1 -0
  110. package/dist/esm/node_modules/lib0/dom.js +48 -0
  111. package/dist/esm/node_modules/lib0/dom.js.map +1 -0
  112. package/dist/esm/node_modules/lib0/encoding.js +663 -0
  113. package/dist/esm/node_modules/lib0/encoding.js.map +1 -0
  114. package/dist/esm/node_modules/lib0/environment.js +121 -0
  115. package/dist/esm/node_modules/lib0/environment.js.map +1 -0
  116. package/dist/esm/node_modules/lib0/error.js +33 -0
  117. package/dist/esm/node_modules/lib0/error.js.map +1 -0
  118. package/dist/esm/node_modules/lib0/function.js +130 -0
  119. package/dist/esm/node_modules/lib0/function.js.map +1 -0
  120. package/dist/esm/node_modules/lib0/iterator.js +48 -0
  121. package/dist/esm/node_modules/lib0/iterator.js.map +1 -0
  122. package/dist/esm/node_modules/lib0/logging.common.js +52 -0
  123. package/dist/esm/node_modules/lib0/logging.common.js.map +1 -0
  124. package/dist/esm/node_modules/lib0/logging.js +115 -0
  125. package/dist/esm/node_modules/lib0/logging.js.map +1 -0
  126. package/dist/esm/node_modules/lib0/map.js +102 -0
  127. package/dist/esm/node_modules/lib0/map.js.map +1 -0
  128. package/dist/esm/node_modules/lib0/math.js +37 -0
  129. package/dist/esm/node_modules/lib0/math.js.map +1 -0
  130. package/dist/esm/node_modules/lib0/number.js +17 -0
  131. package/dist/esm/node_modules/lib0/number.js.map +1 -0
  132. package/dist/esm/node_modules/lib0/object.js +119 -0
  133. package/dist/esm/node_modules/lib0/object.js.map +1 -0
  134. package/dist/esm/node_modules/lib0/observable.js +165 -0
  135. package/dist/esm/node_modules/lib0/observable.js.map +1 -0
  136. package/dist/esm/node_modules/lib0/pair.js +30 -0
  137. package/dist/esm/node_modules/lib0/pair.js.map +1 -0
  138. package/dist/esm/node_modules/lib0/prng.js +87 -0
  139. package/dist/esm/node_modules/lib0/prng.js.map +1 -0
  140. package/dist/esm/node_modules/lib0/promise.js +31 -0
  141. package/dist/esm/node_modules/lib0/promise.js.map +1 -0
  142. package/dist/esm/node_modules/lib0/random.js +25 -0
  143. package/dist/esm/node_modules/lib0/random.js.map +1 -0
  144. package/dist/esm/node_modules/lib0/schema.js +1113 -0
  145. package/dist/esm/node_modules/lib0/schema.js.map +1 -0
  146. package/dist/esm/node_modules/lib0/set.js +10 -0
  147. package/dist/esm/node_modules/lib0/set.js.map +1 -0
  148. package/dist/esm/node_modules/lib0/storage.js +75 -0
  149. package/dist/esm/node_modules/lib0/storage.js.map +1 -0
  150. package/dist/esm/node_modules/lib0/string.js +85 -0
  151. package/dist/esm/node_modules/lib0/string.js.map +1 -0
  152. package/dist/esm/node_modules/lib0/symbol.js +13 -0
  153. package/dist/esm/node_modules/lib0/symbol.js.map +1 -0
  154. package/dist/esm/node_modules/lib0/time.js +16 -0
  155. package/dist/esm/node_modules/lib0/time.js.map +1 -0
  156. package/dist/esm/node_modules/lib0/trait/equality.js +29 -0
  157. package/dist/esm/node_modules/lib0/trait/equality.js.map +1 -0
  158. package/dist/esm/node_modules/lib0/url.js +18 -0
  159. package/dist/esm/node_modules/lib0/url.js.map +1 -0
  160. package/dist/esm/node_modules/lib0/webcrypto.js +6 -0
  161. package/dist/esm/node_modules/lib0/webcrypto.js.map +1 -0
  162. package/dist/esm/node_modules/y-protocols/auth.js +24 -0
  163. package/dist/esm/node_modules/y-protocols/auth.js.map +1 -0
  164. package/dist/esm/node_modules/y-protocols/awareness.js +271 -0
  165. package/dist/esm/node_modules/y-protocols/awareness.js.map +1 -0
  166. package/dist/esm/node_modules/y-protocols/sync.js +138 -0
  167. package/dist/esm/node_modules/y-protocols/sync.js.map +1 -0
  168. package/dist/esm/node_modules/y-websocket/src/y-websocket.js +515 -0
  169. package/dist/esm/node_modules/y-websocket/src/y-websocket.js.map +1 -0
  170. package/dist/esm/node_modules/yjs/dist/yjs.js +10295 -0
  171. package/dist/esm/node_modules/yjs/dist/yjs.js.map +1 -0
  172. package/dist/esm/packages/ui/dist/index.js +65571 -0
  173. package/dist/esm/packages/ui/dist/index.js.map +1 -0
  174. package/dist/esm/pixel/PixelEditor.js +3 -3
  175. package/dist/esm/pixel/PixelEditorMenuBar.js +2 -2
  176. package/dist/esm/pixel/PixelEditorRightPanel.js +3 -3
  177. package/dist/esm/pixel/PixelEditorTimeline.js +2 -2
  178. package/dist/esm/pixel/PixelEditorToolbar.js +2 -2
  179. package/dist/esm/pixel/SpriteGeneratorPanel.js +8 -8
  180. package/dist/esm/vector/VectorEditor.js +3 -3
  181. package/dist/esm/vector/VectorEditorMenuBar.js +3 -3
  182. package/dist/esm/vector/VectorEditorRightPanel.js +13 -13
  183. package/package.json +1 -1
@@ -0,0 +1,1168 @@
1
+ 'use strict';
2
+
3
+ var object = require('./object.js');
4
+ var array = require('./array.js');
5
+ var error = require('./error.js');
6
+ var environment = require('./environment.js');
7
+ var equality = require('./trait/equality.js');
8
+ var _function = require('./function.js');
9
+ var string = require('./string.js');
10
+ var prng = require('./prng.js');
11
+ var number = require('./number.js');
12
+
13
+ /**
14
+ * @experimental WIP
15
+ *
16
+ * Simple & efficient schemas for your data.
17
+ */
18
+
19
+
20
+ /**
21
+ * @typedef {string|number|bigint|boolean|null|undefined|symbol} Primitive
22
+ */
23
+
24
+ /**
25
+ * @typedef {{ [k:string|number|symbol]: any }} AnyObject
26
+ */
27
+
28
+ /**
29
+ * @template T
30
+ * @typedef {T extends Schema<infer X> ? X : T} Unwrap
31
+ */
32
+
33
+ /**
34
+ * @template T
35
+ * @typedef {T extends Schema<infer X> ? X : T} TypeOf
36
+ */
37
+
38
+ /**
39
+ * @template {readonly unknown[]} T
40
+ * @typedef {T extends readonly [Schema<infer First>, ...infer Rest] ? [First, ...UnwrapArray<Rest>] : [] } UnwrapArray
41
+ */
42
+
43
+ /**
44
+ * @template T
45
+ * @typedef {T extends Schema<infer S> ? Schema<S> : never} CastToSchema
46
+ */
47
+
48
+ /**
49
+ * @template {unknown[]} Arr
50
+ * @typedef {Arr extends [...unknown[], infer L] ? L : never} TupleLast
51
+ */
52
+
53
+ /**
54
+ * @template {unknown[]} Arr
55
+ * @typedef {Arr extends [...infer Fs, unknown] ? Fs : never} TuplePop
56
+ */
57
+
58
+ /**
59
+ * @template {readonly unknown[]} T
60
+ * @typedef {T extends []
61
+ * ? {}
62
+ * : T extends [infer First]
63
+ * ? First
64
+ * : T extends [infer First, ...infer Rest]
65
+ * ? First & Intersect<Rest>
66
+ * : never
67
+ * } Intersect
68
+ */
69
+
70
+ const schemaSymbol = Symbol('0schema');
71
+
72
+ class ValidationError {
73
+ constructor () {
74
+ /**
75
+ * Reverse errors
76
+ * @type {Array<{ path: string?, expected: string, has: string, message: string? }>}
77
+ */
78
+ this._rerrs = [];
79
+ }
80
+
81
+ /**
82
+ * @param {string?} path
83
+ * @param {string} expected
84
+ * @param {string} has
85
+ * @param {string?} message
86
+ */
87
+ extend (path, expected, has, message = null) {
88
+ this._rerrs.push({ path, expected, has, message });
89
+ }
90
+
91
+ toString () {
92
+ const s = [];
93
+ for (let i = this._rerrs.length - 1; i > 0; i--) {
94
+ const r = this._rerrs[i];
95
+ /* c8 ignore next */
96
+ s.push(string.repeat(' ', (this._rerrs.length - i) * 2) + `${r.path != null ? `[${r.path}] ` : ''}${r.has} doesn't match ${r.expected}. ${r.message}`);
97
+ }
98
+ return s.join('\n')
99
+ }
100
+ }
101
+
102
+ /**
103
+ * @param {any} a
104
+ * @param {any} b
105
+ * @return {boolean}
106
+ */
107
+ const shapeExtends = (a, b) => {
108
+ if (a === b) return true
109
+ if (a == null || b == null || a.constructor !== b.constructor) return false
110
+ if (a[equality.EqualityTraitSymbol]) return equality.equals(a, b) // last resort: check equality (do this before array and obj check which don't implement the equality trait)
111
+ if (array.isArray(a)) {
112
+ return array.every(a, aitem =>
113
+ array.some(b, bitem => shapeExtends(aitem, bitem))
114
+ )
115
+ } else if (object.isObject(a)) {
116
+ return object.every(a, (aitem, akey) =>
117
+ shapeExtends(aitem, b[akey])
118
+ )
119
+ }
120
+ /* c8 ignore next */
121
+ return false
122
+ };
123
+
124
+ /**
125
+ * @template T
126
+ * @implements {equalityTraits.EqualityTrait}
127
+ */
128
+ class Schema {
129
+ // this.shape must not be defined on Schema. Otherwise typecheck on metatypes (e.g. $$object) won't work as expected anymore
130
+ /**
131
+ * If true, the more things are added to the shape the more objects this schema will accept (e.g.
132
+ * union). By default, the more objects are added, the the fewer objects this schema will accept.
133
+ * @protected
134
+ */
135
+ static _dilutes = false
136
+
137
+ /**
138
+ * @param {Schema<any>} other
139
+ */
140
+ extends (other) {
141
+ let [a, b] = [/** @type {any} */(this).shape, /** @type {any} */ (other).shape];
142
+ if (/** @type {typeof Schema<any>} */ (this.constructor)._dilutes) [b, a] = [a, b];
143
+ return shapeExtends(a, b)
144
+ }
145
+
146
+ /**
147
+ * Overwrite this when necessary. By default, we only check the `shape` property which every shape
148
+ * should have.
149
+ * @param {Schema<any>} other
150
+ */
151
+ equals (other) {
152
+ // @ts-ignore
153
+ return this.constructor === other.constructor && _function.equalityDeep(this.shape, other.shape)
154
+ }
155
+
156
+ [schemaSymbol] () { return true }
157
+
158
+ /**
159
+ * @param {object} other
160
+ */
161
+ [equality.EqualityTraitSymbol] (other) {
162
+ return this.equals(/** @type {any} */ (other))
163
+ }
164
+
165
+ /**
166
+ * Use `schema.validate(obj)` with a typed parameter that is already of typed to be an instance of
167
+ * Schema. Validate will check the structure of the parameter and return true iff the instance
168
+ * really is an instance of Schema.
169
+ *
170
+ * @param {T} o
171
+ * @return {boolean}
172
+ */
173
+ validate (o) {
174
+ return this.check(o)
175
+ }
176
+
177
+ /* c8 ignore start */
178
+ /**
179
+ * Similar to validate, but this method accepts untyped parameters.
180
+ *
181
+ * @param {any} _o
182
+ * @param {ValidationError} [_err]
183
+ * @return {_o is T}
184
+ */
185
+ check (_o, _err) {
186
+ error.methodUnimplemented();
187
+ }
188
+ /* c8 ignore stop */
189
+
190
+ /**
191
+ * @type {Schema<T?>}
192
+ */
193
+ get nullable () {
194
+ // @ts-ignore
195
+ return $union(this, $null)
196
+ }
197
+
198
+ /**
199
+ * @type {$Optional<Schema<T>>}
200
+ */
201
+ get optional () {
202
+ return new $Optional(/** @type {Schema<T>} */ (this))
203
+ }
204
+
205
+ /**
206
+ * Cast a variable to a specific type. Returns the casted value, or throws an exception otherwise.
207
+ * Use this if you know that the type is of a specific type and you just want to convince the type
208
+ * system.
209
+ *
210
+ * **Do not rely on these error messages!**
211
+ * Performs an assertion check only if not in a production environment.
212
+ *
213
+ * @template OO
214
+ * @param {OO} o
215
+ * @return {Extract<OO, T> extends never ? T : (OO extends Array<never> ? T : Extract<OO,T>)}
216
+ */
217
+ cast (o) {
218
+ assert(o, this);
219
+ return /** @type {any} */ (o)
220
+ }
221
+
222
+ /**
223
+ * EXPECTO PATRONUM!! 🪄
224
+ * This function protects against type errors. Though it may not work in the real world.
225
+ *
226
+ * "After all this time?"
227
+ * "Always." - Snape, talking about type safety
228
+ *
229
+ * Ensures that a variable is a a specific type. Returns the value, or throws an exception if the assertion check failed.
230
+ * Use this if you know that the type is of a specific type and you just want to convince the type
231
+ * system.
232
+ *
233
+ * Can be useful when defining lambdas: `s.lambda(s.$number, s.$void).expect((n) => n + 1)`
234
+ *
235
+ * **Do not rely on these error messages!**
236
+ * Performs an assertion check if not in a production environment.
237
+ *
238
+ * @param {T} o
239
+ * @return {o extends T ? T : never}
240
+ */
241
+ expect (o) {
242
+ assert(o, this);
243
+ return o
244
+ }
245
+ }
246
+
247
+ /**
248
+ * @template {(new (...args:any[]) => any) | ((...args:any[]) => any)} Constr
249
+ * @typedef {Constr extends ((...args:any[]) => infer T) ? T : (Constr extends (new (...args:any[]) => any) ? InstanceType<Constr> : never)} Instance
250
+ */
251
+
252
+ /**
253
+ * @template {(new (...args:any[]) => any) | ((...args:any[]) => any)} C
254
+ * @extends {Schema<Instance<C>>}
255
+ */
256
+ class $ConstructedBy extends Schema {
257
+ /**
258
+ * @param {C} c
259
+ * @param {((o:Instance<C>)=>boolean)|null} check
260
+ */
261
+ constructor (c, check) {
262
+ super();
263
+ this.shape = c;
264
+ this._c = check;
265
+ }
266
+
267
+ /**
268
+ * @param {any} o
269
+ * @param {ValidationError} [err]
270
+ * @return {o is C extends ((...args:any[]) => infer T) ? T : (C extends (new (...args:any[]) => any) ? InstanceType<C> : never)} o
271
+ */
272
+ check (o, err = undefined) {
273
+ const c = o?.constructor === this.shape && (this._c == null || this._c(o));
274
+ /* c8 ignore next */
275
+ !c && err?.extend(null, this.shape.name, o?.constructor.name, o?.constructor !== this.shape ? 'Constructor match failed' : 'Check failed');
276
+ return c
277
+ }
278
+ }
279
+
280
+ /**
281
+ * @template {(new (...args:any[]) => any) | ((...args:any[]) => any)} C
282
+ * @param {C} c
283
+ * @param {((o:Instance<C>) => boolean)|null} check
284
+ * @return {CastToSchema<$ConstructedBy<C>>}
285
+ */
286
+ const $constructedBy = (c, check = null) => new $ConstructedBy(c, check);
287
+ $constructedBy($ConstructedBy);
288
+
289
+ /**
290
+ * Check custom properties on any object. You may want to overwrite the generated Schema<any>.
291
+ *
292
+ * @extends {Schema<any>}
293
+ */
294
+ class $Custom extends Schema {
295
+ /**
296
+ * @param {(o:any) => boolean} check
297
+ */
298
+ constructor (check) {
299
+ super();
300
+ /**
301
+ * @type {(o:any) => boolean}
302
+ */
303
+ this.shape = check;
304
+ }
305
+
306
+ /**
307
+ * @param {any} o
308
+ * @param {ValidationError} err
309
+ * @return {o is any}
310
+ */
311
+ check (o, err) {
312
+ const c = this.shape(o);
313
+ /* c8 ignore next */
314
+ !c && err?.extend(null, 'custom prop', o?.constructor.name, 'failed to check custom prop');
315
+ return c
316
+ }
317
+ }
318
+
319
+ /**
320
+ * @param {(o:any) => boolean} check
321
+ * @return {Schema<any>}
322
+ */
323
+ const $custom = (check) => new $Custom(check);
324
+ $constructedBy($Custom);
325
+
326
+ /**
327
+ * @template {Primitive} T
328
+ * @extends {Schema<T>}
329
+ */
330
+ class $Literal extends Schema {
331
+ /**
332
+ * @param {Array<T>} literals
333
+ */
334
+ constructor (literals) {
335
+ super();
336
+ this.shape = literals;
337
+ }
338
+
339
+ /**
340
+ *
341
+ * @param {any} o
342
+ * @param {ValidationError} [err]
343
+ * @return {o is T}
344
+ */
345
+ check (o, err) {
346
+ const c = this.shape.some(a => a === o);
347
+ /* c8 ignore next */
348
+ !c && err?.extend(null, this.shape.join(' | '), o.toString());
349
+ return c
350
+ }
351
+ }
352
+
353
+ /**
354
+ * @template {Primitive[]} T
355
+ * @param {T} literals
356
+ * @return {CastToSchema<$Literal<T[number]>>}
357
+ */
358
+ const $literal = (...literals) => new $Literal(literals);
359
+ const $$literal = $constructedBy($Literal);
360
+
361
+ /**
362
+ * @template {Array<string|Schema<string|number>>} Ts
363
+ * @typedef {Ts extends [] ? `` : (Ts extends [infer T] ? (Unwrap<T> extends (string|number) ? Unwrap<T> : never) : (Ts extends [infer T1, ...infer Rest] ? `${Unwrap<T1> extends (string|number) ? Unwrap<T1> : never}${Rest extends Array<string|Schema<string|number>> ? CastStringTemplateArgsToTemplate<Rest> : never}` : never))} CastStringTemplateArgsToTemplate
364
+ */
365
+
366
+ /**
367
+ * @param {string} str
368
+ * @return {string}
369
+ */
370
+ const _regexEscape = /** @type {any} */ (RegExp).escape || /** @type {(str:string) => string} */ (str =>
371
+ str.replace(/[().|&,$^[\]]/g, s => '\\' + s)
372
+ );
373
+
374
+ /**
375
+ * @param {string|Schema<any>} s
376
+ * @return {string[]}
377
+ */
378
+ const _schemaStringTemplateToRegex = s => {
379
+ if ($string.check(s)) {
380
+ return [_regexEscape(s)]
381
+ }
382
+ if ($$literal.check(s)) {
383
+ return /** @type {Array<string|number>} */ (s.shape).map(v => v + '')
384
+ }
385
+ if ($$number.check(s)) {
386
+ return ['[+-]?\\d+.?\\d*']
387
+ }
388
+ if ($$string.check(s)) {
389
+ return ['.*']
390
+ }
391
+ if ($$union.check(s)) {
392
+ return s.shape.map(_schemaStringTemplateToRegex).flat(1)
393
+ }
394
+ /* c8 ignore next 2 */
395
+ // unexpected schema structure (only supports unions and string in literal types)
396
+ error.unexpectedCase();
397
+ };
398
+
399
+ /**
400
+ * @template {Array<string|Schema<string|number>>} T
401
+ * @extends {Schema<CastStringTemplateArgsToTemplate<T>>}
402
+ */
403
+ class $StringTemplate extends Schema {
404
+ /**
405
+ * @param {T} shape
406
+ */
407
+ constructor (shape) {
408
+ super();
409
+ this.shape = shape;
410
+ this._r = new RegExp('^' + shape.map(_schemaStringTemplateToRegex).map(opts => `(${opts.join('|')})`).join('') + '$');
411
+ }
412
+
413
+ /**
414
+ * @param {any} o
415
+ * @param {ValidationError} [err]
416
+ * @return {o is CastStringTemplateArgsToTemplate<T>}
417
+ */
418
+ check (o, err) {
419
+ const c = this._r.exec(o) != null;
420
+ /* c8 ignore next */
421
+ !c && err?.extend(null, this._r.toString(), o.toString(), 'String doesn\'t match string template.');
422
+ return c
423
+ }
424
+ }
425
+ $constructedBy($StringTemplate);
426
+
427
+ const isOptionalSymbol = Symbol('optional');
428
+ /**
429
+ * @template {Schema<any>} S
430
+ * @extends Schema<Unwrap<S>|undefined>
431
+ */
432
+ class $Optional extends Schema {
433
+ /**
434
+ * @param {S} shape
435
+ */
436
+ constructor (shape) {
437
+ super();
438
+ this.shape = shape;
439
+ }
440
+
441
+ /**
442
+ * @param {any} o
443
+ * @param {ValidationError} [err]
444
+ * @return {o is (Unwrap<S>|undefined)}
445
+ */
446
+ check (o, err) {
447
+ const c = o === undefined || this.shape.check(o);
448
+ /* c8 ignore next */
449
+ !c && err?.extend(null, 'undefined (optional)', '()');
450
+ return c
451
+ }
452
+
453
+ get [isOptionalSymbol] () { return true }
454
+ }
455
+ const $$optional = $constructedBy($Optional);
456
+
457
+ /**
458
+ * @extends Schema<never>
459
+ */
460
+ class $Never extends Schema {
461
+ /**
462
+ * @param {any} _o
463
+ * @param {ValidationError} [err]
464
+ * @return {_o is never}
465
+ */
466
+ check (_o, err) {
467
+ /* c8 ignore next */
468
+ err?.extend(null, 'never', typeof _o);
469
+ return false
470
+ }
471
+ }
472
+ $constructedBy($Never);
473
+
474
+ /**
475
+ * @template {{ [key: string|symbol|number]: Schema<any> }} S
476
+ * @typedef {{ [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? Key : never]?: S[Key] extends $Optional<Schema<infer Type>> ? Type : never } & { [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? never : Key]: S[Key] extends Schema<infer Type> ? Type : never }} $ObjectToType
477
+ */
478
+
479
+ /**
480
+ * @template {{[key:string|symbol|number]: Schema<any>}} S
481
+ * @extends {Schema<$ObjectToType<S>>}
482
+ */
483
+ class $Object extends Schema {
484
+ /**
485
+ * @param {S} shape
486
+ * @param {boolean} partial
487
+ */
488
+ constructor (shape, partial = false) {
489
+ super();
490
+ /**
491
+ * @type {S}
492
+ */
493
+ this.shape = shape;
494
+ this._isPartial = partial;
495
+ }
496
+
497
+ static _dilutes = true
498
+
499
+ /**
500
+ * @type {Schema<Partial<$ObjectToType<S>>>}
501
+ */
502
+ get partial () {
503
+ return new $Object(this.shape, true)
504
+ }
505
+
506
+ /**
507
+ * @param {any} o
508
+ * @param {ValidationError} err
509
+ * @return {o is $ObjectToType<S>}
510
+ */
511
+ check (o, err) {
512
+ if (o == null) {
513
+ /* c8 ignore next */
514
+ err?.extend(null, 'object', 'null');
515
+ return false
516
+ }
517
+ return object.every(this.shape, (vv, vk) => {
518
+ const c = (this._isPartial && !object.hasProperty(o, vk)) || vv.check(o[vk], err);
519
+ !c && err?.extend(vk.toString(), vv.toString(), typeof o[vk], 'Object property does not match');
520
+ return c
521
+ })
522
+ }
523
+ }
524
+
525
+ /**
526
+ * @template S
527
+ * @typedef {Schema<{ [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? Key : never]?: S[Key] extends $Optional<Schema<infer Type>> ? Type : never } & { [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? never : Key]: S[Key] extends Schema<infer Type> ? Type : never }>} _ObjectDefToSchema
528
+ */
529
+
530
+ // I used an explicit type annotation instead of $ObjectToType, so that the user doesn't see the
531
+ // weird type definitions when inspecting type definions.
532
+ /**
533
+ * @template {{ [key:string|symbol|number]: Schema<any> }} S
534
+ * @param {S} def
535
+ * @return {_ObjectDefToSchema<S> extends Schema<infer S> ? Schema<{ [K in keyof S]: S[K] }> : never}
536
+ */
537
+ const $object = def => /** @type {any} */ (new $Object(def));
538
+ const $$object = $constructedBy($Object);
539
+ /**
540
+ * @type {Schema<{[key:string]: any}>}
541
+ */
542
+ const $objectAny = $custom(o => o != null && (o.constructor === Object || o.constructor == null));
543
+
544
+ /**
545
+ * @template {Schema<string|number|symbol>} Keys
546
+ * @template {Schema<any>} Values
547
+ * @extends {Schema<{ [key in Unwrap<Keys>]: Unwrap<Values> }>}
548
+ */
549
+ class $Record extends Schema {
550
+ /**
551
+ * @param {Keys} keys
552
+ * @param {Values} values
553
+ */
554
+ constructor (keys, values) {
555
+ super();
556
+ this.shape = {
557
+ keys, values
558
+ };
559
+ }
560
+
561
+ /**
562
+ * @param {any} o
563
+ * @param {ValidationError} err
564
+ * @return {o is { [key in Unwrap<Keys>]: Unwrap<Values> }}
565
+ */
566
+ check (o, err) {
567
+ return o != null && object.every(o, (vv, vk) => {
568
+ const ck = this.shape.keys.check(vk, err);
569
+ /* c8 ignore next */
570
+ !ck && err?.extend(vk + '', 'Record', typeof o, ck ? 'Key doesn\'t match schema' : 'Value doesn\'t match value');
571
+ return ck && this.shape.values.check(vv, err)
572
+ })
573
+ }
574
+ }
575
+
576
+ /**
577
+ * @template {Schema<string|number|symbol>} Keys
578
+ * @template {Schema<any>} Values
579
+ * @param {Keys} keys
580
+ * @param {Values} values
581
+ * @return {CastToSchema<$Record<Keys,Values>>}
582
+ */
583
+ const $record = (keys, values) => new $Record(keys, values);
584
+ const $$record = $constructedBy($Record);
585
+
586
+ /**
587
+ * @template {Schema<any>[]} S
588
+ * @extends {Schema<{ [Key in keyof S]: S[Key] extends Schema<infer Type> ? Type : never }>}
589
+ */
590
+ class $Tuple extends Schema {
591
+ /**
592
+ * @param {S} shape
593
+ */
594
+ constructor (shape) {
595
+ super();
596
+ this.shape = shape;
597
+ }
598
+
599
+ /**
600
+ * @param {any} o
601
+ * @param {ValidationError} err
602
+ * @return {o is { [K in keyof S]: S[K] extends Schema<infer Type> ? Type : never }}
603
+ */
604
+ check (o, err) {
605
+ return o != null && object.every(this.shape, (vv, vk) => {
606
+ const c = /** @type {Schema<any>} */ (vv).check(o[vk], err);
607
+ /* c8 ignore next */
608
+ !c && err?.extend(vk.toString(), 'Tuple', typeof vv);
609
+ return c
610
+ })
611
+ }
612
+ }
613
+
614
+ /**
615
+ * @template {Array<Schema<any>>} T
616
+ * @param {T} def
617
+ * @return {CastToSchema<$Tuple<T>>}
618
+ */
619
+ const $tuple = (...def) => new $Tuple(def);
620
+ $constructedBy($Tuple);
621
+
622
+ /**
623
+ * @template {Schema<any>} S
624
+ * @extends {Schema<Array<S extends Schema<infer T> ? T : never>>}
625
+ */
626
+ class $Array extends Schema {
627
+ /**
628
+ * @param {Array<S>} v
629
+ */
630
+ constructor (v) {
631
+ super();
632
+ /**
633
+ * @type {Schema<S extends Schema<infer T> ? T : never>}
634
+ */
635
+ this.shape = v.length === 1 ? v[0] : new $Union(v);
636
+ }
637
+
638
+ /**
639
+ * @param {any} o
640
+ * @param {ValidationError} [err]
641
+ * @return {o is Array<S extends Schema<infer T> ? T : never>} o
642
+ */
643
+ check (o, err) {
644
+ const c = array.isArray(o) && array.every(o, oi => this.shape.check(oi));
645
+ /* c8 ignore next */
646
+ !c && err?.extend(null, 'Array', '');
647
+ return c
648
+ }
649
+ }
650
+
651
+ /**
652
+ * @template {Array<Schema<any>>} T
653
+ * @param {T} def
654
+ * @return {Schema<Array<T extends Array<Schema<infer S>> ? S : never>>}
655
+ */
656
+ const $array = (...def) => new $Array(def);
657
+ const $$array = $constructedBy($Array);
658
+ /**
659
+ * @type {Schema<Array<any>>}
660
+ */
661
+ const $arrayAny = $custom(o => array.isArray(o));
662
+
663
+ /**
664
+ * @template T
665
+ * @extends {Schema<T>}
666
+ */
667
+ class $InstanceOf extends Schema {
668
+ /**
669
+ * @param {new (...args:any) => T} constructor
670
+ * @param {((o:T) => boolean)|null} check
671
+ */
672
+ constructor (constructor, check) {
673
+ super();
674
+ this.shape = constructor;
675
+ this._c = check;
676
+ }
677
+
678
+ /**
679
+ * @param {any} o
680
+ * @param {ValidationError} err
681
+ * @return {o is T}
682
+ */
683
+ check (o, err) {
684
+ const c = o instanceof this.shape && (this._c == null || this._c(o));
685
+ /* c8 ignore next */
686
+ !c && err?.extend(null, this.shape.name, o?.constructor.name);
687
+ return c
688
+ }
689
+ }
690
+
691
+ /**
692
+ * @template T
693
+ * @param {new (...args:any) => T} c
694
+ * @param {((o:T) => boolean)|null} check
695
+ * @return {Schema<T>}
696
+ */
697
+ const $instanceOf = (c, check = null) => new $InstanceOf(c, check);
698
+ $constructedBy($InstanceOf);
699
+
700
+ const $$schema = $instanceOf(Schema);
701
+
702
+ /**
703
+ * @template {Schema<any>[]} Args
704
+ * @typedef {(...args:UnwrapArray<TuplePop<Args>>)=>Unwrap<TupleLast<Args>>} _LArgsToLambdaDef
705
+ */
706
+
707
+ /**
708
+ * @template {Array<Schema<any>>} Args
709
+ * @extends {Schema<_LArgsToLambdaDef<Args>>}
710
+ */
711
+ class $Lambda extends Schema {
712
+ /**
713
+ * @param {Args} args
714
+ */
715
+ constructor (args) {
716
+ super();
717
+ this.len = args.length - 1;
718
+ this.args = $tuple(...args.slice(-1));
719
+ this.res = args[this.len];
720
+ }
721
+
722
+ /**
723
+ * @param {any} f
724
+ * @param {ValidationError} err
725
+ * @return {f is _LArgsToLambdaDef<Args>}
726
+ */
727
+ check (f, err) {
728
+ const c = f.constructor === Function && f.length <= this.len;
729
+ /* c8 ignore next */
730
+ !c && err?.extend(null, 'function', typeof f);
731
+ return c
732
+ }
733
+ }
734
+ const $$lambda = $constructedBy($Lambda);
735
+
736
+ /**
737
+ * @type {Schema<Function>}
738
+ */
739
+ const $function = $custom(o => typeof o === 'function');
740
+
741
+ /**
742
+ * @template {Array<Schema<any>>} T
743
+ * @extends {Schema<Intersect<UnwrapArray<T>>>}
744
+ */
745
+ class $Intersection extends Schema {
746
+ /**
747
+ * @param {T} v
748
+ */
749
+ constructor (v) {
750
+ super();
751
+ /**
752
+ * @type {T}
753
+ */
754
+ this.shape = v;
755
+ }
756
+
757
+ /**
758
+ * @param {any} o
759
+ * @param {ValidationError} [err]
760
+ * @return {o is Intersect<UnwrapArray<T>>}
761
+ */
762
+ check (o, err) {
763
+ // @ts-ignore
764
+ const c = array.every(this.shape, check => check.check(o, err));
765
+ /* c8 ignore next */
766
+ !c && err?.extend(null, 'Intersectinon', typeof o);
767
+ return c
768
+ }
769
+ }
770
+ $constructedBy($Intersection, o => o.shape.length > 0); // Intersection with length=0 is considered "any"
771
+
772
+ /**
773
+ * @template S
774
+ * @extends {Schema<S>}
775
+ */
776
+ class $Union extends Schema {
777
+ static _dilutes = true
778
+
779
+ /**
780
+ * @param {Array<Schema<S>>} v
781
+ */
782
+ constructor (v) {
783
+ super();
784
+ this.shape = v;
785
+ }
786
+
787
+ /**
788
+ * @param {any} o
789
+ * @param {ValidationError} [err]
790
+ * @return {o is S}
791
+ */
792
+ check (o, err) {
793
+ const c = array.some(this.shape, (vv) => vv.check(o, err));
794
+ err?.extend(null, 'Union', typeof o);
795
+ return c
796
+ }
797
+ }
798
+
799
+ /**
800
+ * @template {Array<any>} T
801
+ * @param {T} schemas
802
+ * @return {CastToSchema<$Union<Unwrap<ReadSchema<T>>>>}
803
+ */
804
+ const $union = (...schemas) => schemas.findIndex($s => $$union.check($s)) >= 0
805
+ ? $union(...schemas.map($s => $($s)).map($s => $$union.check($s) ? $s.shape : [$s]).flat(1))
806
+ : (schemas.length === 1
807
+ ? schemas[0]
808
+ : new $Union(schemas));
809
+ const $$union = /** @type {Schema<$Union<any>>} */ ($constructedBy($Union));
810
+
811
+ const _t = () => true;
812
+ /**
813
+ * @type {Schema<any>}
814
+ */
815
+ const $any = $custom(_t);
816
+ const $$any = /** @type {Schema<Schema<any>>} */ ($constructedBy($Custom, o => o.shape === _t));
817
+
818
+ /**
819
+ * @type {Schema<bigint>}
820
+ */
821
+ const $bigint = $custom(o => typeof o === 'bigint');
822
+ const $$bigint = /** @type {Schema<Schema<BigInt>>} */ ($custom(o => o === $bigint));
823
+
824
+ /**
825
+ * @type {Schema<symbol>}
826
+ */
827
+ const $symbol = $custom(o => typeof o === 'symbol');
828
+ /** @type {Schema<Schema<Symbol>>} */ ($custom(o => o === $symbol));
829
+
830
+ /**
831
+ * @type {Schema<number>}
832
+ */
833
+ const $number = $custom(o => typeof o === 'number');
834
+ const $$number = /** @type {Schema<Schema<number>>} */ ($custom(o => o === $number));
835
+
836
+ /**
837
+ * @type {Schema<string>}
838
+ */
839
+ const $string = $custom(o => typeof o === 'string');
840
+ const $$string = /** @type {Schema<Schema<string>>} */ ($custom(o => o === $string));
841
+
842
+ /**
843
+ * @type {Schema<boolean>}
844
+ */
845
+ const $boolean = $custom(o => typeof o === 'boolean');
846
+ const $$boolean = /** @type {Schema<Schema<Boolean>>} */ ($custom(o => o === $boolean));
847
+
848
+ /**
849
+ * @type {Schema<undefined>}
850
+ */
851
+ const $undefined = $literal(undefined);
852
+ /** @type {Schema<Schema<undefined>>} */ ($constructedBy($Literal, o => o.shape.length === 1 && o.shape[0] === undefined));
853
+
854
+ /**
855
+ * @type {Schema<void>}
856
+ */
857
+ $literal(undefined);
858
+
859
+ const $null = $literal(null);
860
+ const $$null = /** @type {Schema<Schema<null>>} */ ($constructedBy($Literal, o => o.shape.length === 1 && o.shape[0] === null));
861
+
862
+ $constructedBy(Uint8Array);
863
+ /** @type {Schema<Schema<Uint8Array>>} */ ($constructedBy($ConstructedBy, o => o.shape === Uint8Array));
864
+
865
+ /**
866
+ * @type {Schema<Primitive>}
867
+ */
868
+ const $primitive = $union($number, $string, $null, $undefined, $bigint, $boolean, $symbol);
869
+
870
+ /**
871
+ * @typedef {JSON[]} JSONArray
872
+ */
873
+ /**
874
+ * @typedef {Primitive|JSONArray|{ [key:string]:JSON }} JSON
875
+ */
876
+ /**
877
+ * @type {Schema<null|number|string|boolean|JSON[]|{[key:string]:JSON}>}
878
+ */
879
+ (() => {
880
+ const $jsonArr = /** @type {$Array<$any>} */ ($array($any));
881
+ const $jsonRecord = /** @type {$Record<$string,$any>} */ ($record($string, $any));
882
+ const $json = $union($number, $string, $null, $boolean, $jsonArr, $jsonRecord);
883
+ $jsonArr.shape = $json;
884
+ $jsonRecord.shape.values = $json;
885
+ return $json
886
+ })();
887
+
888
+ /**
889
+ * @template {any} IN
890
+ * @typedef {IN extends Schema<any> ? IN
891
+ * : (IN extends string|number|boolean|null ? Schema<IN>
892
+ * : (IN extends new (...args:any[])=>any ? Schema<InstanceType<IN>>
893
+ * : (IN extends any[] ? Schema<{ [K in keyof IN]: Unwrap<ReadSchema<IN[K]>> }[number]>
894
+ * : (IN extends object ? (_ObjectDefToSchema<{[K in keyof IN]:ReadSchema<IN[K]>}> extends Schema<infer S> ? Schema<{ [K in keyof S]: S[K] }> : never)
895
+ * : never)
896
+ * )
897
+ * )
898
+ * )
899
+ * } ReadSchemaOld
900
+ */
901
+
902
+ /**
903
+ * @template {any} IN
904
+ * @typedef {[Extract<IN,Schema<any>>,Extract<IN,string|number|boolean|null>,Extract<IN,new (...args:any[])=>any>,Extract<IN,any[]>,Extract<Exclude<IN,Schema<any>|string|number|boolean|null|(new (...args:any[])=>any)|any[]>,object>] extends [infer Schemas, infer Primitives, infer Constructors, infer Arrs, infer Obj]
905
+ * ? Schema<
906
+ * (Schemas extends Schema<infer S> ? S : never)
907
+ * | Primitives
908
+ * | (Constructors extends new (...args:any[])=>any ? InstanceType<Constructors> : never)
909
+ * | (Arrs extends any[] ? { [K in keyof Arrs]: Unwrap<ReadSchema<Arrs[K]>> }[number] : never)
910
+ * | (Obj extends object ? Unwrap<(_ObjectDefToSchema<{[K in keyof Obj]:ReadSchema<Obj[K]>}> extends Schema<infer S> ? Schema<{ [K in keyof S]: S[K] }> : never)> : never)>
911
+ * : never
912
+ * } ReadSchema
913
+ */
914
+
915
+ /**
916
+ * @typedef {ReadSchema<{x:42}|{y:99}|Schema<string>|[1,2,{}]>} Q
917
+ */
918
+
919
+ /**
920
+ * @template IN
921
+ * @param {IN} o
922
+ * @return {ReadSchema<IN>}
923
+ */
924
+ const $ = o => {
925
+ if ($$schema.check(o)) {
926
+ return /** @type {any} */ (o)
927
+ } else if ($objectAny.check(o)) {
928
+ /**
929
+ * @type {any}
930
+ */
931
+ const o2 = {};
932
+ for (const k in o) {
933
+ o2[k] = $(o[k]);
934
+ }
935
+ return /** @type {any} */ ($object(o2))
936
+ } else if ($arrayAny.check(o)) {
937
+ return /** @type {any} */ ($union(...o.map($)))
938
+ } else if ($primitive.check(o)) {
939
+ return /** @type {any} */ ($literal(o))
940
+ } else if ($function.check(o)) {
941
+ return /** @type {any} */ ($constructedBy(/** @type {any} */ (o)))
942
+ }
943
+ /* c8 ignore next */
944
+ error.unexpectedCase();
945
+ };
946
+
947
+ /* c8 ignore start */
948
+ /**
949
+ * Assert that a variable is of this specific type.
950
+ * The assertion check is only performed in non-production environments.
951
+ *
952
+ * @type {<T>(o:any,schema:Schema<T>) => asserts o is T}
953
+ */
954
+ const assert = environment.production
955
+ ? () => {}
956
+ : (o, schema) => {
957
+ const err = new ValidationError();
958
+ if (!schema.check(o, err)) {
959
+ throw error.create(`Expected value to be of type ${schema.constructor.name}.\n${err.toString()}`)
960
+ }
961
+ };
962
+ /* c8 ignore end */
963
+
964
+ /**
965
+ * @template In
966
+ * @template Out
967
+ * @typedef {{ if: Schema<In>, h: (o:In,state?:any)=>Out }} Pattern
968
+ */
969
+
970
+ /**
971
+ * @template {Pattern<any,any>} P
972
+ * @template In
973
+ * @typedef {ReturnType<Extract<P,Pattern<In extends number ? number : (In extends string ? string : In),any>>['h']>} PatternMatchResult
974
+ */
975
+
976
+ /**
977
+ * @todo move this to separate library
978
+ * @template {any} [State=undefined]
979
+ * @template {Pattern<any,any>} [Patterns=never]
980
+ */
981
+ class PatternMatcher {
982
+ /**
983
+ * @param {Schema<State>} [$state]
984
+ */
985
+ constructor ($state) {
986
+ /**
987
+ * @type {Array<Patterns>}
988
+ */
989
+ this.patterns = [];
990
+ this.$state = $state;
991
+ }
992
+
993
+ /**
994
+ * @template P
995
+ * @template R
996
+ * @param {P} pattern
997
+ * @param {(o:NoInfer<Unwrap<ReadSchema<P>>>,s:State)=>R} handler
998
+ * @return {PatternMatcher<State,Patterns|Pattern<Unwrap<ReadSchema<P>>,R>>}
999
+ */
1000
+ if (pattern, handler) {
1001
+ // @ts-ignore
1002
+ this.patterns.push({ if: $(pattern), h: handler });
1003
+ // @ts-ignore
1004
+ return this
1005
+ }
1006
+
1007
+ /**
1008
+ * @template R
1009
+ * @param {(o:any,s:State)=>R} h
1010
+ */
1011
+ else (h) {
1012
+ return this.if($any, h)
1013
+ }
1014
+
1015
+ /**
1016
+ * @return {State extends undefined
1017
+ * ? <In extends Unwrap<Patterns['if']>>(o:In,state?:undefined)=>PatternMatchResult<Patterns,In>
1018
+ * : <In extends Unwrap<Patterns['if']>>(o:In,state:State)=>PatternMatchResult<Patterns,In>}
1019
+ */
1020
+ done () {
1021
+ // @ts-ignore
1022
+ return /** @type {any} */ (o, s) => {
1023
+ for (let i = 0; i < this.patterns.length; i++) {
1024
+ const p = this.patterns[i];
1025
+ if (p.if.check(o)) {
1026
+ // @ts-ignore
1027
+ return p.h(o, s)
1028
+ }
1029
+ }
1030
+ throw error.create('Unhandled pattern')
1031
+ }
1032
+ }
1033
+ }
1034
+
1035
+ /**
1036
+ * @template [State=undefined]
1037
+ * @param {State} [state]
1038
+ * @return {PatternMatcher<State extends undefined ? undefined : Unwrap<ReadSchema<State>>>}
1039
+ */
1040
+ const match = state => new PatternMatcher(/** @type {any} */ (state));
1041
+
1042
+ /**
1043
+ * Helper function to generate a (non-exhaustive) sample set from a gives schema.
1044
+ *
1045
+ * @type {<T>(o:T,gen:prng.PRNG)=>T}
1046
+ */
1047
+ const _random = /** @type {any} */ (match(/** @type {Schema<prng.PRNG>} */ ($any))
1048
+ .if($$number, (_o, gen) => prng.int53(gen, number.MIN_SAFE_INTEGER, number.MAX_SAFE_INTEGER))
1049
+ .if($$string, (_o, gen) => prng.word(gen))
1050
+ .if($$boolean, (_o, gen) => prng.bool(gen))
1051
+ .if($$bigint, (_o, gen) => BigInt(prng.int53(gen, number.MIN_SAFE_INTEGER, number.MAX_SAFE_INTEGER)))
1052
+ .if($$union, (o, gen) => random(gen, prng.oneOf(gen, o.shape)))
1053
+ .if($$object, (o, gen) => {
1054
+ /**
1055
+ * @type {any}
1056
+ */
1057
+ const res = {};
1058
+ for (const k in o.shape) {
1059
+ let prop = o.shape[k];
1060
+ if ($$optional.check(prop)) {
1061
+ if (prng.bool(gen)) { continue }
1062
+ prop = prop.shape;
1063
+ }
1064
+ res[k] = _random(prop, gen);
1065
+ }
1066
+ return res
1067
+ })
1068
+ .if($$array, (o, gen) => {
1069
+ const arr = [];
1070
+ const n = prng.int32(gen, 0, 42);
1071
+ for (let i = 0; i < n; i++) {
1072
+ arr.push(random(gen, o.shape));
1073
+ }
1074
+ return arr
1075
+ })
1076
+ .if($$literal, (o, gen) => {
1077
+ return prng.oneOf(gen, o.shape)
1078
+ })
1079
+ .if($$null, (o, gen) => {
1080
+ return null
1081
+ })
1082
+ .if($$lambda, (o, gen) => {
1083
+ const res = random(gen, o.res);
1084
+ return () => res
1085
+ })
1086
+ .if($$any, (o, gen) => random(gen, prng.oneOf(gen, [
1087
+ $number, $string, $null, $undefined, $bigint, $boolean,
1088
+ $array($number),
1089
+ $record($union('a', 'b', 'c'), $number)
1090
+ ])))
1091
+ .if($$record, (o, gen) => {
1092
+ /**
1093
+ * @type {any}
1094
+ */
1095
+ const res = {};
1096
+ const keysN = prng.int53(gen, 0, 3);
1097
+ for (let i = 0; i < keysN; i++) {
1098
+ const key = random(gen, o.shape.keys);
1099
+ const val = random(gen, o.shape.values);
1100
+ res[key] = val;
1101
+ }
1102
+ return res
1103
+ })
1104
+ .done());
1105
+
1106
+ /**
1107
+ * @template S
1108
+ * @param {prng.PRNG} gen
1109
+ * @param {S} schema
1110
+ * @return {Unwrap<ReadSchema<S>>}
1111
+ */
1112
+ const random = (gen, schema) => /** @type {any} */ (_random($(schema), gen));
1113
+
1114
+ exports.$ = $;
1115
+ exports.$$any = $$any;
1116
+ exports.$$array = $$array;
1117
+ exports.$$bigint = $$bigint;
1118
+ exports.$$boolean = $$boolean;
1119
+ exports.$$lambda = $$lambda;
1120
+ exports.$$literal = $$literal;
1121
+ exports.$$null = $$null;
1122
+ exports.$$number = $$number;
1123
+ exports.$$object = $$object;
1124
+ exports.$$optional = $$optional;
1125
+ exports.$$record = $$record;
1126
+ exports.$$schema = $$schema;
1127
+ exports.$$string = $$string;
1128
+ exports.$$union = $$union;
1129
+ exports.$Array = $Array;
1130
+ exports.$ConstructedBy = $ConstructedBy;
1131
+ exports.$Custom = $Custom;
1132
+ exports.$InstanceOf = $InstanceOf;
1133
+ exports.$Intersection = $Intersection;
1134
+ exports.$Lambda = $Lambda;
1135
+ exports.$Literal = $Literal;
1136
+ exports.$Object = $Object;
1137
+ exports.$Record = $Record;
1138
+ exports.$StringTemplate = $StringTemplate;
1139
+ exports.$Tuple = $Tuple;
1140
+ exports.$Union = $Union;
1141
+ exports.$any = $any;
1142
+ exports.$array = $array;
1143
+ exports.$arrayAny = $arrayAny;
1144
+ exports.$bigint = $bigint;
1145
+ exports.$boolean = $boolean;
1146
+ exports.$constructedBy = $constructedBy;
1147
+ exports.$custom = $custom;
1148
+ exports.$function = $function;
1149
+ exports.$instanceOf = $instanceOf;
1150
+ exports.$literal = $literal;
1151
+ exports.$null = $null;
1152
+ exports.$number = $number;
1153
+ exports.$object = $object;
1154
+ exports.$objectAny = $objectAny;
1155
+ exports.$primitive = $primitive;
1156
+ exports.$record = $record;
1157
+ exports.$string = $string;
1158
+ exports.$symbol = $symbol;
1159
+ exports.$tuple = $tuple;
1160
+ exports.$undefined = $undefined;
1161
+ exports.$union = $union;
1162
+ exports.PatternMatcher = PatternMatcher;
1163
+ exports.Schema = Schema;
1164
+ exports.ValidationError = ValidationError;
1165
+ exports.assert = assert;
1166
+ exports.match = match;
1167
+ exports.random = random;
1168
+ //# sourceMappingURL=schema.js.map