deep-guards 1.0.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/.yarn.yml ADDED
@@ -0,0 +1,11 @@
1
+ nodeLinker: node-modules
2
+
3
+ plugins:
4
+ - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
5
+ spec: "@yarnpkg/plugin-workspace-tools"
6
+ - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs
7
+ spec: "@yarnpkg/plugin-typescript"
8
+ - path: .yarn/plugins/@yarnpkg/plugin-version.cjs
9
+ spec: "@yarnpkg/plugin-version"
10
+
11
+ yarnPath: .yarn/releases/yarn-3.8.2.cjs
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,167 @@
1
+ # Deep-Guards
2
+
3
+ This solves the cases where you have a nested JSON data structure, and are wanting to guard the whole structure in one go, rather than doing shallow guards.
4
+
5
+ I was also surprised that there's not too many options for guarding things with type narrowing in the case of discriminated unions. This library also solves that!
6
+
7
+ I have also oriented this library towards making the type tooltips as descriptive as possible.
8
+
9
+ Example use case:
10
+
11
+ ```ts
12
+ const carGuard = isObjectOf({
13
+ type: isExact("car"),
14
+ wheels: isExact(4),
15
+ owner: isString,
16
+ passengers: isArrayOf(
17
+ isObjectOf({
18
+ name: isString,
19
+ })
20
+ ),
21
+ });
22
+
23
+ const bikeGuard = isObjectOf({
24
+ type: isExact("bike"),
25
+ wheels: isExact(2),
26
+ owner: isString,
27
+ storage: isOptional(isArrayOf(isString)),
28
+ });
29
+
30
+ const vehicleGuard = isUnionOf(carGuard, bikeGuard);
31
+
32
+ const value: unknown = { ... };
33
+
34
+ if (vehicleGuard(value)) {
35
+ value.wheels;
36
+
37
+ if (value.type === "car") {
38
+ // value is a Car
39
+ } else {
40
+ // value is a bike
41
+ }
42
+ }
43
+ ```
44
+
45
+ ## Contents
46
+
47
+ 1. [Primitives](#primitives)
48
+ 2. [Compound](#compound)
49
+ 1. [isOptional](#isoptional)
50
+ 2. [isNullable](#isnullable)
51
+ 3. [isNonNullable](#isnonnullable)
52
+ 4. [isNot](#isnot)
53
+ 5. [isOneOf](#isoneof)
54
+ 6. [isUnionOf](#isunionof)
55
+ 7. [isExact](#isexact)
56
+ 3. [Structures](#structures)
57
+ 1. [isAnyArray](#isanyarray)
58
+ 2. [isAnyRecord](#isanyrecord)
59
+ 3. [isArrayOf](#isarrayof)
60
+ 4. [isRecordOf](#isrecordof)
61
+ 5. [isObjectOf](#isobjectof)
62
+
63
+ ## Terminology
64
+
65
+ - Guard:
66
+ - A function which lets you narrow down an incoming `unknown` value type, into a defined type.
67
+ - Simple guard:
68
+ - A variable which is set to a Guard
69
+ - Higher order guard:
70
+ - This is a function which takes in a guard function as a parameter, and then will produce a new guard function as a result.
71
+ - Incoming value:
72
+ - The value being guarded against.
73
+
74
+ ## Primitives
75
+
76
+ There's all the usual suspects for primitives. They are all simple guards.
77
+
78
+ The full list of available primitive guards is below:
79
+
80
+ - isUnknown
81
+ - isNull
82
+ - isUndefined
83
+ - isNumber
84
+ - isInteger
85
+ - isString
86
+ - isSymbol
87
+ - isBoolean
88
+ - isFunction
89
+
90
+ ## Compound
91
+
92
+ There's also compound guards, which do more complex checks than the primitives:
93
+
94
+ ### isOptional
95
+
96
+ Higher order guard. This lets the incoming value to also be equal to `undefined` as well.
97
+
98
+ ### isNullable
99
+
100
+ Higher order guard. This lets the incoming value to also be equal to `null` or `undefined` as well.
101
+
102
+ ### isNonNullable
103
+
104
+ Simple guard. This will extract `null` and `undefined` from the incoming value type.
105
+
106
+ ### isNot
107
+
108
+ Higher order guard. This will do the inverse of the incoming guard.
109
+
110
+ ### isOneOf
111
+
112
+ Has signature:
113
+
114
+ ```ts
115
+ function isOneOf<
116
+ const T extends (string | number | boolean | symbol | null | undefined)[]
117
+ >(...values: T): Guard<(typeof values)[number]>;
118
+ ```
119
+
120
+ It's very useful for enumerations, where you only have a few specific values, e.g. a status enum with a guard: `isOneOf("active", "inactive", "away")`. When using the enum, it will then be narrowed down to those specific values, so in the case of the example, a value will be narrowed down to the type: `"active" | "inactive" | "away"`.
121
+
122
+ ### isUnionOf
123
+
124
+ Higher order guard. This takes in any amount of guards as arguments, and then produces a guard which does a union over all the incoming guards.
125
+
126
+ ### isExact
127
+
128
+ Has signature:
129
+
130
+ ```ts
131
+ function isExact<const T>(expected: T, deep: boolean = true): Guard<T>;
132
+ ```
133
+
134
+ This will pass if the incoming value exactly matches the `expected` parameter, optionally computing a deep equality.
135
+
136
+ ## Structures
137
+
138
+ Finally there's structure guards, which guard against things like objects/arrays/records.
139
+
140
+ ### isAnyArray
141
+
142
+ Simple guard. Passes if the incoming value is an array.
143
+
144
+ ### isAnyRecord
145
+
146
+ Simple guard. Passes if the incoming value is an object/record, but **not** if it's an array.
147
+
148
+ ### isArrayOf
149
+
150
+ Higher order guard. This will pass if the incoming value is an array which contains elements which are of the type of the passed in guard function.
151
+
152
+ NOTE: This passes for empty arrays
153
+
154
+ ### isRecordOf
155
+
156
+ Higher order guard. It has two guard parameters, where the first is the key guard, and then the second is a value guard which is optional. If you don't pass in a value guard, the returned guard function has `unknown`s as the value type.
157
+
158
+ NOTE: This passes for empty records
159
+
160
+ ### isObjectOf
161
+
162
+ This is a function which takes in a structured object, containing keys of type `string | number | symbol`, and then values which are guard functions.
163
+
164
+ As seen in the example at the start of this readme, you can do all sorts of complex nesting, as this produces a guard in the end.
165
+
166
+ NOTE: This throws an error if you give it an empty object.\
167
+ It will also accept an object which contains keys which are not specified.
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ presets: [
3
+ ["@babel/preset-env", { targets: { node: "current" } }],
4
+ "@babel/preset-typescript",
5
+ ],
6
+ };
@@ -0,0 +1,8 @@
1
+ import { Guard, GuardSchemaOf } from "./types.js";
2
+ export declare function isOptional<T>(guard: Guard<T>): Guard<T | undefined>;
3
+ export declare function isNullable<T>(guard: Guard<T>): Guard<T | null | undefined>;
4
+ export declare function isNonNullable<T>(value: T | null | undefined): value is T;
5
+ export declare function isNot<const N>(guard: Guard<N>): <const T>(value: T | N) => value is T;
6
+ export declare function isOneOf<const T extends (string | number | boolean | symbol | null | undefined)[]>(...values: T): Guard<(typeof values)[number]>;
7
+ export declare function isUnionOf<T extends readonly unknown[]>(...guards: GuardSchemaOf<T>): Guard<T[number]>;
8
+ export declare function isExact<const T>(expected: T, deep?: boolean): Guard<T>;
@@ -0,0 +1,48 @@
1
+ export function isOptional(guard) {
2
+ if (typeof guard !== "function") {
3
+ throw new TypeError(`isOptional expects a guard parameter. Got instead: ${guard}`);
4
+ }
5
+ return ((value) => value === undefined || guard(value));
6
+ }
7
+ export function isNullable(guard) {
8
+ if (typeof guard !== "function") {
9
+ throw new TypeError(`isNullable expects a guard parameter. Got instead: ${guard}`);
10
+ }
11
+ return (value) => value == null || guard(value);
12
+ }
13
+ export function isNonNullable(value) {
14
+ return value != null;
15
+ }
16
+ export function isNot(guard) {
17
+ if (typeof guard !== "function") {
18
+ throw new TypeError(`isNot expects a guard parameter. Got instead: ${guard}`);
19
+ }
20
+ return (value) => !guard(value);
21
+ }
22
+ export function isOneOf(...values) {
23
+ const valueSet = new Set(values);
24
+ return (value) => valueSet.has(value);
25
+ }
26
+ export function isUnionOf(...guards) {
27
+ if (guards.every((guard) => typeof guard !== "function")) {
28
+ throw new TypeError(`isUnionOf expects N guard parameters. Got instead: ${guards}`);
29
+ }
30
+ return (value) => guards.some((guard) => guard(value));
31
+ }
32
+ function isEqual(a, b) {
33
+ return (a === b ||
34
+ (a != null &&
35
+ b != null &&
36
+ typeof a === "object" &&
37
+ typeof b === "object" &&
38
+ (Array.isArray(a)
39
+ ? Array.isArray(b) &&
40
+ a.length === b.length &&
41
+ a.every((v, i) => isEqual(v, b[i]))
42
+ : Object.keys(a).length === Object.keys(b).length &&
43
+ Object.entries(a).every(([k, v]) => k in b && isEqual(v, b[k])))));
44
+ }
45
+ export function isExact(expected, deep = true) {
46
+ return (value) => deep ? isEqual(expected, value) : expected === value;
47
+ }
48
+ //# sourceMappingURL=compound.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compound.js","sourceRoot":"src/","sources":["compound.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,UAAU,CAAI,KAAe;IAC3C,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CACjB,sDAAsD,KAAK,EAAE,CAC9D,CAAC;IACJ,CAAC;IAED,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,KAAK,CAAC,CAErD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,UAAU,CAAI,KAAe;IAC3C,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CACjB,sDAAsD,KAAK,EAAE,CAC9D,CAAC;IACJ,CAAC;IAED,OAAO,CAAC,KAAc,EAAiC,EAAE,CACvD,KAAK,IAAI,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,UAAU,aAAa,CAAI,KAA2B;IAC1D,OAAO,KAAK,IAAI,IAAI,CAAC;AACvB,CAAC;AAED,MAAM,UAAU,KAAK,CAAU,KAAe;IAC5C,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CACjB,iDAAiD,KAAK,EAAE,CACzD,CAAC;IACJ,CAAC;IAED,OAAO,CAAU,KAAY,EAAc,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,OAAO,CAErB,GAAG,MAAS;IACZ,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;IACjC,OAAO,CAAC,KAAc,EAAsB,EAAE,CAC5C,QAAQ,CAAC,GAAG,CAAC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AC;AAED,MAAM,UAAU,OAAO,CAAU,QAAW,EAAE,OAAgB,IAAI;IAChE,OAAO,CAAC,KAAK,EAAc,EAAE,CAC3B,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,KAAK,KAAK,CAAC;AACzD,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { Guard } from "./types.js";
2
+ export declare class GuardError extends Error {
3
+ name: string;
4
+ }
5
+ export declare function guardOrThrow<T>(value: unknown, guard: Guard<T>, hint?: string): T;
package/dist/errors.js ADDED
@@ -0,0 +1,12 @@
1
+ export class GuardError extends Error {
2
+ name = "GuardError";
3
+ }
4
+ export function guardOrThrow(value, guard, hint) {
5
+ if (guard(value)) {
6
+ return value;
7
+ }
8
+ else {
9
+ throw new GuardError(hint ?? "Guard error");
10
+ }
11
+ }
12
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"src/","sources":["errors.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,UAAW,SAAQ,KAAK;IACnC,IAAI,GAAG,YAAY,CAAC;CACrB;AAED,MAAM,UAAU,YAAY,CAC1B,KAAc,EACd,KAAe,EACf,IAAa;IAEb,IAAI,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,KAAK,CAAC;IACf,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,UAAU,CAAC,IAAI,IAAI,aAAa,CAAC,CAAC;IAC9C,CAAC;AACH,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from "./compound.js";
2
+ export * from "./errors.js";
3
+ export * from "./primitives.js";
4
+ export * from "./structures.js";
5
+ export * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./compound.js";
2
+ export * from "./errors.js";
3
+ export * from "./primitives.js";
4
+ export * from "./structures.js";
5
+ export * from "./types.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { Guard } from "./types.js";
2
+ export declare const isUnknown: Guard<unknown>;
3
+ export declare const isNull: Guard<null>;
4
+ export declare const isUndefined: Guard<undefined>;
5
+ export declare const isNumber: Guard<number>;
6
+ export declare const isInteger: Guard<number>;
7
+ export declare const isString: Guard<string>;
8
+ export declare const isSymbol: Guard<symbol>;
9
+ export declare const isBoolean: Guard<boolean>;
10
+ export declare const isFunction: Guard<(...args: unknown[]) => unknown>;
@@ -0,0 +1,10 @@
1
+ export const isUnknown = (_value) => true;
2
+ export const isNull = (value) => value === null;
3
+ export const isUndefined = (value) => value === undefined;
4
+ export const isNumber = (value) => typeof value === "number";
5
+ export const isInteger = (value) => Number.isInteger(value);
6
+ export const isString = (value) => typeof value === "string";
7
+ export const isSymbol = (value) => typeof value === "symbol";
8
+ export const isBoolean = (value) => value === true || value === false;
9
+ export const isFunction = (value) => typeof value === "function";
10
+ //# sourceMappingURL=primitives.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primitives.js","sourceRoot":"src/","sources":["primitives.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,SAAS,GAAmB,CAAC,MAAM,EAAqB,EAAE,CAAC,IAAI,CAAC;AAE7E,MAAM,CAAC,MAAM,MAAM,GAAgB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC;AAE7D,MAAM,CAAC,MAAM,WAAW,GAAqB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC;AAE5E,MAAM,CAAC,MAAM,QAAQ,GAAkB,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;AAE5E,MAAM,CAAC,MAAM,SAAS,GAAkB,CAAC,KAAK,EAAmB,EAAE,CACjE,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAE1B,MAAM,CAAC,MAAM,QAAQ,GAAkB,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;AAE5E,MAAM,CAAC,MAAM,QAAQ,GAAkB,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;AAE5E,MAAM,CAAC,MAAM,SAAS,GAAmB,CAAC,KAAK,EAAE,EAAE,CACjD,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC;AAEpC,MAAM,CAAC,MAAM,UAAU,GAA2C,CAChE,KAAK,EACqC,EAAE,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { Guard, GuardSchemaOf } from "./types.js";
2
+ type ObjectKey = string | number | symbol;
3
+ export declare const isAnyArray: Guard<unknown[]>;
4
+ export declare const isAnyRecord: Guard<Record<ObjectKey, unknown>>;
5
+ export declare function isArrayOf<T>(guard: Guard<T>): Guard<T[]>;
6
+ export declare function isRecordOf<K extends ObjectKey>(keyGuard: Guard<K>): Guard<Record<K, unknown>>;
7
+ export declare function isRecordOf<K extends ObjectKey, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<Record<K, V>>;
8
+ export declare function isObjectOf<O extends object>(schema: GuardSchemaOf<O>): O extends unknown[] ? never : Guard<O>;
9
+ export {};
@@ -0,0 +1,41 @@
1
+ function objectKeys(obj) {
2
+ return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
3
+ }
4
+ export const isAnyArray = value => Array.isArray(value);
5
+ export const isAnyRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
6
+ export function isArrayOf(guard) {
7
+ if (typeof guard !== "function") {
8
+ throw new TypeError(`isArrayOf expects a guard parameter. Got instead: ${guard}`);
9
+ }
10
+ return (value) => Array.isArray(value) && value.every(guard);
11
+ }
12
+ export function isRecordOf(keyGuard, valueGuard) {
13
+ if (typeof keyGuard !== "function") {
14
+ throw new TypeError(`isRecordOf keyGuard expects a guard parameter. Got instead: ${keyGuard}`);
15
+ }
16
+ else if (valueGuard != null && typeof valueGuard !== "function") {
17
+ throw new TypeError(`isRecordOf valueGuard expects an optional guard parameter. Got instead: ${valueGuard}`);
18
+ }
19
+ return (value) => value != null &&
20
+ typeof value === "object" &&
21
+ !Array.isArray(value) &&
22
+ objectKeys(value).every(key => keyGuard(key) && (valueGuard?.(value[key]) ?? true));
23
+ }
24
+ export function isObjectOf(schema) {
25
+ const schemaKeys = objectKeys(schema);
26
+ const schemaUnknown = schema;
27
+ if (schemaKeys.length === 0) {
28
+ throw new Error("isObjectOf received an empty schema");
29
+ }
30
+ else if (schemaUnknown == null ||
31
+ typeof schemaUnknown !== "object" ||
32
+ Array.isArray(schemaUnknown) ||
33
+ schemaKeys.some(key => typeof schemaUnknown[key] !== "function")) {
34
+ throw new TypeError(`isObjectOf expects a guard schema. Got instead: ${schemaUnknown}`);
35
+ }
36
+ return ((value) => value != null &&
37
+ typeof value === "object" &&
38
+ !Array.isArray(value) &&
39
+ schemaKeys.every(key => key in value && schema[key](value[key])));
40
+ }
41
+ //# sourceMappingURL=structures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structures.js","sourceRoot":"src/","sources":["structures.ts"],"names":[],"mappings":"AAIA,SAAS,UAAU,CAAsB,GAAuB;IAC9D,OAAQ,MAAM,CAAC,mBAAmB,CAAC,GAAG,CAAS,CAAC,MAAM,CACpD,MAAM,CAAC,qBAAqB,CAAC,GAAG,CAAQ,CACzC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAqB,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAE1E,MAAM,CAAC,MAAM,WAAW,GAAsC,CAC5D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AAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;SAAM,IACL,aAAa,IAAI,IAAI;QACrB,OAAO,aAAa,KAAK,QAAQ;QACjC,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC;QAC5B,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,OAAQ,aAAmB,CAAC,GAAG,CAAC,KAAK,UAAU,CAAC,EACvE,CAAC;QACD,MAAM,IAAI,SAAS,CACjB,mDAAmD,aAAa,EAAE,CACnE,CAAC;IACJ,CAAC;IAED,OAAO,CAAC,CAAC,KAAK,EAAc,EAAE,CAC5B,KAAK,IAAI,IAAI;QACb,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACrB,UAAU,CAAC,KAAK,CACd,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,KAAK,IAAI,MAAM,CAAC,GAAG,CAAC,CAAE,KAAW,CAAC,GAAG,CAAC,CAAC,CACtD,CAA2C,CAAC;AACjD,CAAC"}
@@ -0,0 +1,4 @@
1
+ export type Guard<T> = (value: unknown) => value is T;
2
+ export type GuardSchemaOf<O extends object> = {
3
+ [K in keyof O]: Guard<O[K]>;
4
+ };
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"src/","sources":["types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,51 @@
1
+ import typescriptParser from "@typescript-eslint/parser";
2
+ import jslint from "@eslint/js";
3
+ import tslint from "typescript-eslint";
4
+ import tsPlugin from "@typescript-eslint/eslint-plugin";
5
+
6
+ export default tslint.config(
7
+ jslint.configs.recommended,
8
+ ...tslint.configs.recommended,
9
+ ...tslint.configs.recommendedTypeChecked,
10
+ ...tslint.configs.strictTypeChecked,
11
+ {
12
+ languageOptions: {
13
+ parser: typescriptParser,
14
+ parserOptions: { project: "./tsconfig.json" },
15
+ },
16
+
17
+ plugins: { tsPlugin },
18
+
19
+ rules: {
20
+ // CORE
21
+ // According to https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/indent.md
22
+ // the default indentation rule can cause eslint to report erroneous style errors.
23
+ indent: "off",
24
+ "no-console": "off",
25
+ eqeqeq: ["warn", "smart"],
26
+ "require-yield": "off",
27
+ "prettier/prettier": "off",
28
+ // "eslint-comments/disable-enable-pair": ["warn", { allowWholeFile: true }],
29
+ // TYPESCRIPT
30
+ "@typescript-eslint/prefer-reduce-type-parameter": "off",
31
+ // We use ts-ignore because we want to suppress type errors... don't warn us about it, please
32
+ "@typescript-eslint/ban-ts-comment": "off",
33
+ // We don't want to specify the return type everywhere as we get the type safety without it
34
+ "@typescript-eslint/explicit-function-return-type": "off",
35
+ // We don't want to have to specify accessibility modifiers on every method, but they are part of
36
+ // the "recommended" config. This turns it off. Rational: https://github.com/typescript-eslint/typescript-eslint/issues/201
37
+ "@typescript-eslint/explicit-member-accessibility": "off",
38
+ "@typescript-eslint/restrict-template-expressions": "off",
39
+ // Use prettier for indentation, not typescript-eslint:
40
+ "@typescript-eslint/indent": "off",
41
+ // We want to only warn about empty interfaces as they might just be placeholders for the future
42
+ "@typescript-eslint/no-empty-interface": "off",
43
+ "@typescript-eslint/no-empty-function": "warn",
44
+ "@typescript-eslint/no-inferrable-types": "off",
45
+ "@typescript-eslint/no-unused-vars": [
46
+ "warn",
47
+ { varsIgnorePattern: "^_", argsIgnorePattern: "^_" },
48
+ ],
49
+ },
50
+ }
51
+ );