@alexify/metaschema 0.0.0-stage → 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/CHANGELOG.md +452 -0
- package/LICENSE +22 -0
- package/README.md +178 -2
- package/SECURITY.md +60 -0
- package/browser.js +4 -0
- package/index.d.ts +226 -0
- package/index.js +1 -0
- package/package.json +90 -3
- package/src/errors.js +28 -0
- package/src/index.js +23 -0
- package/src/kinds.js +68 -0
- package/src/metadata.js +168 -0
- package/src/metautil.js +23 -0
- package/src/model.js +92 -0
- package/src/preprocessor.js +110 -0
- package/src/prototypes/abstract.js +84 -0
- package/src/prototypes/collections.js +98 -0
- package/src/prototypes/json.js +15 -0
- package/src/prototypes/reference.js +42 -0
- package/src/prototypes/scalars.js +44 -0
- package/src/prototypes/schema.js +31 -0
- package/src/prototypes/tuple.js +45 -0
- package/src/runtime/browser.js +6 -0
- package/src/runtime/node.js +5 -0
- package/src/schema.js +187 -0
- package/src/struct.js +63 -0
- package/src/types.js +127 -0
- package/src/util.js +97 -0
package/SECURITY.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Security Policy
|
|
2
|
+
|
|
3
|
+
## Supported versions
|
|
4
|
+
|
|
5
|
+
Only the latest published version receives fixes.
|
|
6
|
+
|
|
7
|
+
| Version | Supported |
|
|
8
|
+
|---|---|
|
|
9
|
+
| 1.x | ✅ |
|
|
10
|
+
| `metaschema` (metarhia) 2.x | ❌ (report upstream) |
|
|
11
|
+
|
|
12
|
+
## Reporting a vulnerability
|
|
13
|
+
|
|
14
|
+
**Please do not open a public issue for a security problem.**
|
|
15
|
+
|
|
16
|
+
Report it privately through
|
|
17
|
+
[GitHub's private vulnerability reporting](https://github.com/Alexis-Technologies/metaschema/security/advisories/new),
|
|
18
|
+
or by email to <dolid.sasha@gmail.com>.
|
|
19
|
+
|
|
20
|
+
Include, as far as you can:
|
|
21
|
+
|
|
22
|
+
- what an attacker can do, and what they need in order to do it;
|
|
23
|
+
- the affected version and Node.js version (or browser);
|
|
24
|
+
- a minimal reproduction.
|
|
25
|
+
|
|
26
|
+
You can expect an acknowledgement within a few days, and an assessment of severity and a fix
|
|
27
|
+
timeline once the report is confirmed.
|
|
28
|
+
|
|
29
|
+
## Threat model
|
|
30
|
+
|
|
31
|
+
Some things work as intended and are not vulnerabilities:
|
|
32
|
+
|
|
33
|
+
- **Schemas are code.** A schema is a JavaScript value supplied by the application. Field and
|
|
34
|
+
schema `validate` functions, custom types' `construct` / `checkType`, and calculated fields are
|
|
35
|
+
live functions that run with the privileges of your process. Build schemas only from definitions
|
|
36
|
+
you trust, the same as any other module you `require`.
|
|
37
|
+
- **metaschema never loads or evaluates code.** Since 1.0 it has no loader: it does not read schema
|
|
38
|
+
files, evaluate source strings or run a sandbox. Turning untrusted input into a schema definition
|
|
39
|
+
is the application's decision and responsibility.
|
|
40
|
+
- **Input shape is checked strictly.** Every key that is not in the schema is reported as
|
|
41
|
+
`is not expected`, including `constructor`, `__proto__` and `toString`. Fields live in a
|
|
42
|
+
null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
|
|
43
|
+
metaschema never writes to the value it checks.
|
|
44
|
+
- **Validation errors are data.** `check` collects problems as strings instead of throwing on bad
|
|
45
|
+
input. The messages contain field paths (which can include key names taken from the input,
|
|
46
|
+
truncated to 100 characters) and, for `enum`, the allowed values; they never contain the
|
|
47
|
+
rejected values themselves. A message
|
|
48
|
+
from a custom `validate` function, or from an exception it throws, is passed through as written.
|
|
49
|
+
- **Type registration is process-wide.** Custom types registered by one `Model` are visible to
|
|
50
|
+
every schema in the process. Register them once, from trusted code.
|
|
51
|
+
- **`saveTypes` writes where it is told.** The output path is the caller's argument; metaschema
|
|
52
|
+
does not sanitize it.
|
|
53
|
+
- **Bundled and minified builds validate exactly like the source.** Internal identity checks use a
|
|
54
|
+
global symbol brand, not class names, and `tests/unit/bundle.test.js` validates through esbuild
|
|
55
|
+
bundles of both entry points, minified and not. A build in which `check` accepts invalid data is a
|
|
56
|
+
bug; please report it.
|
|
57
|
+
|
|
58
|
+
Things that *are* in scope: input data that makes `check` throw, hang or consume unbounded
|
|
59
|
+
resources (a circular value is reported as `is a circular reference`, not recursed into); input
|
|
60
|
+
data that changes a schema or the type registry; and a message that leaks a value it should not.
|
package/browser.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Intentionally mirrors index.js: bundlers resolve this file through the
|
|
2
|
+
// package.json `browser` field and `exports` condition, and the same map swaps
|
|
3
|
+
// src/runtime/node.js for src/runtime/browser.js. Do not deduplicate.
|
|
4
|
+
module.exports = require('./src/index.js');
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
export type Scope = 'global' | 'local' | 'application';
|
|
2
|
+
|
|
3
|
+
export type Allow = 'read' | 'write' | 'append';
|
|
4
|
+
|
|
5
|
+
export type Store = 'persistent' | 'memory';
|
|
6
|
+
|
|
7
|
+
export type KnownKind =
|
|
8
|
+
| 'dictionary'
|
|
9
|
+
| 'registry'
|
|
10
|
+
| 'entity'
|
|
11
|
+
| 'details'
|
|
12
|
+
| 'relation'
|
|
13
|
+
| 'form'
|
|
14
|
+
| 'view'
|
|
15
|
+
| 'projection'
|
|
16
|
+
| 'journal'
|
|
17
|
+
| 'struct'
|
|
18
|
+
| 'scalar';
|
|
19
|
+
|
|
20
|
+
// A capitalized first key that is not a known kind is a custom kind; the
|
|
21
|
+
// intersection keeps the known names in completions.
|
|
22
|
+
export type Kind = KnownKind | (string & {});
|
|
23
|
+
|
|
24
|
+
export type Cardinality = 'one-to-many' | 'many-to-one';
|
|
25
|
+
|
|
26
|
+
export interface Relation {
|
|
27
|
+
to: string;
|
|
28
|
+
type: Cardinality;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Codes of the issues the library produces; a validator may use its own.
|
|
32
|
+
export type IssueCode =
|
|
33
|
+
| 'required'
|
|
34
|
+
| 'type'
|
|
35
|
+
| 'unexpected'
|
|
36
|
+
| 'enum'
|
|
37
|
+
| 'length'
|
|
38
|
+
| 'reference'
|
|
39
|
+
| 'circular'
|
|
40
|
+
| 'exception'
|
|
41
|
+
| 'custom';
|
|
42
|
+
|
|
43
|
+
export interface ValidationIssue {
|
|
44
|
+
code: IssueCode | (string & {});
|
|
45
|
+
path: string;
|
|
46
|
+
message: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// What a validator may return: an issue of its own needs only a message.
|
|
50
|
+
export interface IssueInput {
|
|
51
|
+
code?: string;
|
|
52
|
+
path?: string;
|
|
53
|
+
message: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type ValidationReturn =
|
|
57
|
+
| boolean
|
|
58
|
+
| string
|
|
59
|
+
| IssueInput
|
|
60
|
+
| Array<string | IssueInput>
|
|
61
|
+
| ValidationResult
|
|
62
|
+
| null
|
|
63
|
+
| undefined
|
|
64
|
+
| void;
|
|
65
|
+
|
|
66
|
+
export interface CheckOptions {
|
|
67
|
+
// Stop collecting after this many messages (at least 1).
|
|
68
|
+
maxErrors?: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class ValidationResult {
|
|
72
|
+
valid: boolean;
|
|
73
|
+
errors: string[];
|
|
74
|
+
issues: ValidationIssue[];
|
|
75
|
+
constructor(path?: string);
|
|
76
|
+
add(error: ValidationReturn, code?: IssueCode): this;
|
|
77
|
+
static issuesOf(error: ValidationReturn, path?: string, code?: IssueCode): ValidationIssue[];
|
|
78
|
+
static format(error: ValidationReturn, path?: string): string[] | null;
|
|
79
|
+
static isInstance(error: unknown): boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type Validator = (value: any, path: string) => ValidationReturn;
|
|
83
|
+
|
|
84
|
+
export type CalculatedField = (value: any) => unknown;
|
|
85
|
+
|
|
86
|
+
// A field of a struct: an instance of the type's class. Keys of the
|
|
87
|
+
// definition the type does not use (`unique`, `default`, ...) are kept on it.
|
|
88
|
+
export interface FieldType {
|
|
89
|
+
readonly type: string;
|
|
90
|
+
required: boolean;
|
|
91
|
+
validate?: Validator;
|
|
92
|
+
check(value: unknown, path: string): ValidationResult;
|
|
93
|
+
toJSON(): object;
|
|
94
|
+
[key: string]: unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type Fields = Record<string, FieldType | CalculatedField>;
|
|
98
|
+
|
|
99
|
+
export interface TypeConstructor {
|
|
100
|
+
readonly type: string;
|
|
101
|
+
readonly kind: 'scalar' | 'struct';
|
|
102
|
+
metadata: Record<string, unknown>;
|
|
103
|
+
new (def: object, preprocessor: object): FieldType;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type TypeTable = Record<string, TypeConstructor>;
|
|
107
|
+
|
|
108
|
+
// An entry of the table passed to Model: metadata for a built-in, an alias
|
|
109
|
+
// (`js`), or a prototype with its own `construct` and `checkType`.
|
|
110
|
+
export interface TypeEntry {
|
|
111
|
+
js?: string;
|
|
112
|
+
metadata?: Record<string, unknown>;
|
|
113
|
+
kind?: 'scalar' | 'struct';
|
|
114
|
+
rules?: string[];
|
|
115
|
+
construct?(def: object, preprocessor: object): void;
|
|
116
|
+
checkType?(value: any, path: string): ValidationReturn;
|
|
117
|
+
[key: string]: unknown;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface ModelOptions {
|
|
121
|
+
// 'shared' (the default) registers the types into the process-wide registry;
|
|
122
|
+
// 'isolated' gives the model its own copy of the built-in types to register into.
|
|
123
|
+
registry?: 'shared' | 'isolated';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface KindMetadata {
|
|
127
|
+
kind: Kind;
|
|
128
|
+
scope: Scope;
|
|
129
|
+
store: Store;
|
|
130
|
+
allow: Allow;
|
|
131
|
+
parent?: string;
|
|
132
|
+
[key: string]: unknown;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface SchemaOptions {
|
|
136
|
+
validate: Validator | null;
|
|
137
|
+
format: ((value: any) => unknown) | null;
|
|
138
|
+
parse: ((value: any) => unknown) | null;
|
|
139
|
+
serialize: ((value: any) => unknown) | null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export type DefinitionErrorCode =
|
|
143
|
+
| 'ERR_INVALID_DEFINITION'
|
|
144
|
+
| 'ERR_UNKNOWN_TYPE'
|
|
145
|
+
| 'ERR_MISSING_SCHEMA'
|
|
146
|
+
| 'ERR_INVALID_TUPLE'
|
|
147
|
+
| 'ERR_PROJECTION'
|
|
148
|
+
| 'ERR_INVALID_CUSTOM_TYPE'
|
|
149
|
+
| 'ERR_INVALID_ENUM'
|
|
150
|
+
| 'ERR_INVALID_LENGTH'
|
|
151
|
+
| 'ERR_INVALID_REFERENCE'
|
|
152
|
+
| 'ERR_RESERVED_KEY'
|
|
153
|
+
| 'ERR_TYPE_REGISTERED'
|
|
154
|
+
| 'ERR_UNKNOWN_JS_TYPE'
|
|
155
|
+
| 'ERR_INVALID_OPTIONS';
|
|
156
|
+
|
|
157
|
+
export class SchemaDefinitionError extends TypeError {
|
|
158
|
+
code: DefinitionErrorCode;
|
|
159
|
+
schema: string;
|
|
160
|
+
field: string;
|
|
161
|
+
constructor(code: DefinitionErrorCode, reason: string);
|
|
162
|
+
locate(schema: string, field: string): this;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export const KIND: Array<string>;
|
|
166
|
+
export const KIND_STORED: Array<string>;
|
|
167
|
+
export const KIND_MEMORY: Array<string>;
|
|
168
|
+
export const SCOPE: Array<string>;
|
|
169
|
+
export const STORE: Array<string>;
|
|
170
|
+
export const ALLOW: Array<string>;
|
|
171
|
+
|
|
172
|
+
export function getKindMetadata(
|
|
173
|
+
kind: Kind,
|
|
174
|
+
meta?: Record<string, unknown>,
|
|
175
|
+
root?: Schema,
|
|
176
|
+
): { defs: Record<string, unknown>; metadata: KindMetadata };
|
|
177
|
+
export function saveTypes(outputFile: string, model: Model): Promise<void>;
|
|
178
|
+
|
|
179
|
+
export class Schema {
|
|
180
|
+
static from(raw: string | object, namespaces?: Array<Model>): Schema;
|
|
181
|
+
static extractSchema(def: object): Schema | null;
|
|
182
|
+
|
|
183
|
+
kind: Kind;
|
|
184
|
+
scope: Scope;
|
|
185
|
+
store: Store;
|
|
186
|
+
allow: Allow;
|
|
187
|
+
parent: string;
|
|
188
|
+
indexes: Record<string, object>;
|
|
189
|
+
options: SchemaOptions;
|
|
190
|
+
custom: Record<string, unknown>;
|
|
191
|
+
// For a schema whose definition is a single type (`Schema.from('string')`,
|
|
192
|
+
// `Schema.from({ array: 'number' })`) this is that FieldType itself.
|
|
193
|
+
fields: Fields;
|
|
194
|
+
name: string;
|
|
195
|
+
namespaces: Set<Model>;
|
|
196
|
+
references: Set<string>;
|
|
197
|
+
relations: Set<Relation>;
|
|
198
|
+
|
|
199
|
+
constructor(name: string, raw: string | object, namespaces?: Array<Model>);
|
|
200
|
+
get types(): TypeTable;
|
|
201
|
+
checkConsistency(): Array<string>;
|
|
202
|
+
findReference(name: string): Schema | null;
|
|
203
|
+
check(value: unknown, path?: string, options?: CheckOptions): ValidationResult;
|
|
204
|
+
toInterface(): string;
|
|
205
|
+
attach(...namespaces: Array<Model>): void;
|
|
206
|
+
detach(...namespaces: Array<Model>): void;
|
|
207
|
+
toString(): string;
|
|
208
|
+
toJSON(): object;
|
|
209
|
+
validate(value: unknown, path: string): ValidationResult | null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export class Model {
|
|
213
|
+
types: TypeTable;
|
|
214
|
+
entities: Map<string, Schema>;
|
|
215
|
+
database: Record<string, unknown> | null;
|
|
216
|
+
order: Set<string>;
|
|
217
|
+
warnings: Array<string>;
|
|
218
|
+
|
|
219
|
+
constructor(
|
|
220
|
+
types: Record<string, TypeEntry>,
|
|
221
|
+
entities: Iterable<readonly [string, object]>,
|
|
222
|
+
database?: Record<string, unknown> | null,
|
|
223
|
+
options?: ModelOptions,
|
|
224
|
+
);
|
|
225
|
+
get dts(): string;
|
|
226
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./src/index.js');
|
package/package.json
CHANGED
|
@@ -1,6 +1,93 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexify/metaschema",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — data validation, domain models and TypeScript generation",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Alex Dolid <dolid.sasha@gmail.com>",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Alexis-Technologies/metaschema.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://metaschema.vercel.app/",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/Alexis-Technologies/metaschema/issues"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18.0.0"
|
|
17
|
+
},
|
|
18
|
+
"main": "index.js",
|
|
19
|
+
"browser": {
|
|
20
|
+
"./index.js": "./browser.js",
|
|
21
|
+
"./src/runtime/node.js": "./src/runtime/browser.js"
|
|
22
|
+
},
|
|
23
|
+
"types": "index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./index.d.ts",
|
|
27
|
+
"browser": "./browser.js",
|
|
28
|
+
"default": "./index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"directories": {
|
|
32
|
+
"test": "tests"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"index.js",
|
|
36
|
+
"index.d.ts",
|
|
37
|
+
"browser.js",
|
|
38
|
+
"src",
|
|
39
|
+
"README.md",
|
|
40
|
+
"CHANGELOG.md",
|
|
41
|
+
"LICENSE",
|
|
42
|
+
"SECURITY.md"
|
|
43
|
+
],
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"tsd": {
|
|
48
|
+
"directory": "tests/types"
|
|
49
|
+
},
|
|
50
|
+
"keywords": [
|
|
51
|
+
"schema",
|
|
52
|
+
"metaschema",
|
|
53
|
+
"metadata",
|
|
54
|
+
"idl",
|
|
55
|
+
"interface-definition-language",
|
|
56
|
+
"dsl",
|
|
57
|
+
"validation",
|
|
58
|
+
"data-validation",
|
|
59
|
+
"domain-model",
|
|
60
|
+
"model",
|
|
61
|
+
"typescript",
|
|
62
|
+
"typescript-definitions",
|
|
63
|
+
"zero-dependency",
|
|
64
|
+
"browser",
|
|
65
|
+
"metarhia"
|
|
66
|
+
],
|
|
67
|
+
"devDependencies": {
|
|
68
|
+
"@vercel/analytics": "^2.0.1",
|
|
69
|
+
"@vercel/speed-insights": "^2.0.0",
|
|
70
|
+
"c8": "^12.0.0",
|
|
71
|
+
"esbuild": "^0.28.2",
|
|
72
|
+
"oxfmt": "^0.72.0",
|
|
73
|
+
"oxlint": "^1.75.0",
|
|
74
|
+
"tsd": "^0.33.0",
|
|
75
|
+
"typescript": "^7.0.2",
|
|
76
|
+
"vitepress": "^1.6.4"
|
|
77
|
+
},
|
|
78
|
+
"scripts": {
|
|
79
|
+
"test": "node --test tests/unit/*.test.js",
|
|
80
|
+
"test:coverage": "c8 --all --include 'src/**' --check-coverage --lines 98 --statements 98 --branches 90 --functions 100 --reporter text --reporter lcov node --test tests/unit/*.test.js",
|
|
81
|
+
"test:types": "tsd",
|
|
82
|
+
"check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts",
|
|
83
|
+
"lint": "oxlint src tests scripts bench",
|
|
84
|
+
"format": "oxfmt src tests scripts bench",
|
|
85
|
+
"format:check": "oxfmt --check src tests scripts bench",
|
|
86
|
+
"size": "node scripts/size.js",
|
|
87
|
+
"bench": "node bench/bench.js",
|
|
88
|
+
"docs:dev": "vitepress dev docs",
|
|
89
|
+
"docs:build": "vitepress build docs",
|
|
90
|
+
"docs:preview": "vitepress preview docs",
|
|
91
|
+
"release": "pnpm publish"
|
|
92
|
+
}
|
|
6
93
|
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// A broken definition is a programming error, so it throws instead of being
|
|
2
|
+
// collected like a validation error. The throw sites (type parsing, custom type
|
|
3
|
+
// registration, projections) rarely know which entity and field they are
|
|
4
|
+
// parsing; the struct that owns the field does, and calls `locate` on the way
|
|
5
|
+
// up, so the message ends with `in "Entity.field"`.
|
|
6
|
+
class SchemaDefinitionError extends TypeError {
|
|
7
|
+
#reason;
|
|
8
|
+
|
|
9
|
+
constructor(code, reason) {
|
|
10
|
+
super(reason);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.schema = '';
|
|
13
|
+
this.field = '';
|
|
14
|
+
this.#reason = reason;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
locate(schema, field) {
|
|
18
|
+
this.schema = schema;
|
|
19
|
+
this.field = this.field ? `${field}.${this.field}` : field;
|
|
20
|
+
const location = schema ? `${schema}.${this.field}` : this.field;
|
|
21
|
+
this.message = `${this.#reason} in "${location}"`;
|
|
22
|
+
return this;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
SchemaDefinitionError.prototype.name = 'SchemaDefinitionError';
|
|
27
|
+
|
|
28
|
+
module.exports = { SchemaDefinitionError };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const { constants, getKindMetadata } = require('./kinds.js');
|
|
2
|
+
const { saveTypes } = require('./runtime/node.js');
|
|
3
|
+
const { Schema } = require('./schema.js');
|
|
4
|
+
const { Model } = require('./model.js');
|
|
5
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
|
+
const { ValidationResult } = require('./metadata.js');
|
|
7
|
+
|
|
8
|
+
const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
|
|
9
|
+
|
|
10
|
+
module.exports = {
|
|
11
|
+
KIND,
|
|
12
|
+
KIND_STORED,
|
|
13
|
+
KIND_MEMORY,
|
|
14
|
+
SCOPE,
|
|
15
|
+
STORE,
|
|
16
|
+
ALLOW,
|
|
17
|
+
getKindMetadata,
|
|
18
|
+
saveTypes,
|
|
19
|
+
Schema,
|
|
20
|
+
Model,
|
|
21
|
+
SchemaDefinitionError,
|
|
22
|
+
ValidationResult,
|
|
23
|
+
};
|
package/src/kinds.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const { toLowerCamel } = require('./metautil.js');
|
|
2
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
3
|
+
|
|
4
|
+
const projectionError = (name, reason) =>
|
|
5
|
+
new SchemaDefinitionError('ERR_PROJECTION', `Projection "${name}" ${reason}`);
|
|
6
|
+
|
|
7
|
+
const KIND_ENT = ['entity', 'registry', 'dictionary'];
|
|
8
|
+
const KIND_AUX = ['journal', 'details', 'relation', 'view'];
|
|
9
|
+
const KIND_STORED = [...KIND_ENT, ...KIND_AUX];
|
|
10
|
+
const KIND_MEMORY = ['struct', 'scalar', 'form', 'projection'];
|
|
11
|
+
const KIND = [...KIND_MEMORY, ...KIND_STORED];
|
|
12
|
+
|
|
13
|
+
const SCOPE = ['application', 'global', 'local'];
|
|
14
|
+
const STORE = ['persistent', 'memory'];
|
|
15
|
+
const ALLOW = ['write', 'append', 'read'];
|
|
16
|
+
|
|
17
|
+
const projection = (kind, meta, root) => {
|
|
18
|
+
const { scope = 'local', store = 'memory', allow = 'write' } = meta;
|
|
19
|
+
const { schema, fields } = meta;
|
|
20
|
+
if (typeof schema !== 'string' || !Array.isArray(fields)) {
|
|
21
|
+
throw projectionError(root.name, 'needs { schema, fields }');
|
|
22
|
+
}
|
|
23
|
+
const parent = schema;
|
|
24
|
+
const metadata = { ...meta, kind, scope, store, allow, parent };
|
|
25
|
+
const entity = root.findReference(schema);
|
|
26
|
+
if (!entity) throw projectionError(root.name, `parent "${schema}" is not found`);
|
|
27
|
+
const defs = Object.create(null);
|
|
28
|
+
for (const key of fields) {
|
|
29
|
+
const field = entity.fields[key];
|
|
30
|
+
if (!field) throw projectionError(root.name, `field "${key}" is not in "${schema}"`);
|
|
31
|
+
defs[key] = field;
|
|
32
|
+
}
|
|
33
|
+
return { defs, metadata };
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const kindStored = (kind, meta, root) => {
|
|
37
|
+
const { scope = 'application', store = 'persistent', allow = 'write' } = meta;
|
|
38
|
+
const metadata = { ...meta, kind, scope, store, allow };
|
|
39
|
+
const id = root.name ? `${toLowerCamel(root.name)}Id` : 'id';
|
|
40
|
+
const defs = Object.create(null);
|
|
41
|
+
defs[id] = '?string';
|
|
42
|
+
return { defs, metadata };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const kindMemory = (kind, meta) => {
|
|
46
|
+
const { scope = 'local', store = 'memory', allow = 'write' } = meta;
|
|
47
|
+
const metadata = { ...meta, kind, scope, store, allow };
|
|
48
|
+
const defs = Object.create(null);
|
|
49
|
+
return { defs, metadata };
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const KIND_METADATA = Object.create(null);
|
|
53
|
+
for (const kind of KIND_MEMORY) {
|
|
54
|
+
KIND_METADATA[kind] = kindMemory;
|
|
55
|
+
}
|
|
56
|
+
for (const kind of KIND_STORED) {
|
|
57
|
+
KIND_METADATA[kind] = kindStored;
|
|
58
|
+
}
|
|
59
|
+
KIND_METADATA.projection = projection;
|
|
60
|
+
|
|
61
|
+
const getKindMetadata = (kind, meta = {}, root) => {
|
|
62
|
+
const handler = KIND_METADATA[kind] || kindMemory;
|
|
63
|
+
return handler(kind, meta, root);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
|
|
67
|
+
|
|
68
|
+
module.exports = { constants, getKindMetadata };
|
package/src/metadata.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
const { getKindMetadata } = require('./kinds.js');
|
|
2
|
+
const { BRAND, hasBrand, limits, issue } = require('./util.js');
|
|
3
|
+
|
|
4
|
+
const ERR_PREFIX = 'Field';
|
|
5
|
+
|
|
6
|
+
const prefixed = (message, path) =>
|
|
7
|
+
message.startsWith(ERR_PREFIX) ? message : `${ERR_PREFIX} "${path}" ${message}`;
|
|
8
|
+
|
|
9
|
+
// Anything with a message is taken as an issue: the library's own, or a
|
|
10
|
+
// { code, message } object returned by a custom validator.
|
|
11
|
+
const isIssue = (error) =>
|
|
12
|
+
error !== null && typeof error === 'object' && typeof error.message === 'string';
|
|
13
|
+
const OPTIONS = ['validate', 'parse', 'serialize', 'format'];
|
|
14
|
+
const METADATA_COLLECTIONS = ['indexes', 'options'];
|
|
15
|
+
|
|
16
|
+
class ValidationResult {
|
|
17
|
+
#path;
|
|
18
|
+
|
|
19
|
+
constructor(path = '') {
|
|
20
|
+
this.#path = path;
|
|
21
|
+
this.errors = [];
|
|
22
|
+
this.issues = [];
|
|
23
|
+
this.valid = true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// True once the maxErrors of the current check is reached; loops stop early.
|
|
27
|
+
get full() {
|
|
28
|
+
return this.errors.length >= limits.maxErrors;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
add(error, code = 'custom') {
|
|
32
|
+
const issues = ValidationResult.isInstance(error)
|
|
33
|
+
? error.issues
|
|
34
|
+
: ValidationResult.issuesOf(error, this.#path, code);
|
|
35
|
+
// One by one: a spread call has an argument limit, and a validator may
|
|
36
|
+
// legitimately return more messages than that.
|
|
37
|
+
for (const entry of issues) {
|
|
38
|
+
if (this.full) break;
|
|
39
|
+
this.issues.push(entry);
|
|
40
|
+
this.errors.push(entry.message);
|
|
41
|
+
}
|
|
42
|
+
this.valid = this.errors.length === 0;
|
|
43
|
+
return this;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Everything a check or validator may return, as issues: true, null and
|
|
47
|
+
// undefined are nothing; false is a generic error; a string is a message;
|
|
48
|
+
// an array holds any of these; an object with a message is an issue.
|
|
49
|
+
static issuesOf(error, path = '', code = 'custom') {
|
|
50
|
+
if (error === true || error === null || error === undefined) return [];
|
|
51
|
+
if (ValidationResult.isInstance(error)) return error.issues;
|
|
52
|
+
if (error === false) return [issue(code, path, 'validation error')];
|
|
53
|
+
if (Array.isArray(error)) {
|
|
54
|
+
const issues = [];
|
|
55
|
+
for (const item of error) issues.push(...ValidationResult.issuesOf(item, path, code));
|
|
56
|
+
return issues;
|
|
57
|
+
}
|
|
58
|
+
if (isIssue(error)) {
|
|
59
|
+
const found = { code: error.code || code, path: error.path || path };
|
|
60
|
+
return [{ ...found, message: prefixed(error.message, path) }];
|
|
61
|
+
}
|
|
62
|
+
return [{ code, path, message: prefixed(String(error), path) }];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
static format(error, path = '') {
|
|
66
|
+
const issues = ValidationResult.issuesOf(error, path);
|
|
67
|
+
if (issues.length === 0) return null;
|
|
68
|
+
return issues.map((entry) => entry.message);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static isInstance(error) {
|
|
72
|
+
return hasBrand(error, 'ValidationResult');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
ValidationResult.prototype[BRAND] = 'ValidationResult';
|
|
77
|
+
|
|
78
|
+
class Options {
|
|
79
|
+
constructor() {
|
|
80
|
+
this.validate = null;
|
|
81
|
+
this.format = null;
|
|
82
|
+
this.parse = null;
|
|
83
|
+
this.serialize = null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
extract(key, field) {
|
|
87
|
+
const isFn = typeof field === 'function';
|
|
88
|
+
const isOption = OPTIONS.includes(key) && isFn;
|
|
89
|
+
if (isOption) this[key] = field;
|
|
90
|
+
return isOption;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
class Indexes {
|
|
95
|
+
// Index definitions (`index`, `primary`, `unique` arrays) are taken out of the
|
|
96
|
+
// fields; a `many` relation is recorded here as well but stays a field, so
|
|
97
|
+
// the method reports only whether the entry was taken.
|
|
98
|
+
extract(key, field) {
|
|
99
|
+
if (field === null || typeof field !== 'object') return false;
|
|
100
|
+
const { index, primary, unique, many } = field;
|
|
101
|
+
const isIndex = Array.isArray(index || primary || unique);
|
|
102
|
+
if (isIndex || many) this[key] = field;
|
|
103
|
+
return isIndex;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
class SchemaMetadata {
|
|
108
|
+
constructor() {
|
|
109
|
+
this.kind = 'struct';
|
|
110
|
+
this.scope = 'local';
|
|
111
|
+
this.store = 'memory';
|
|
112
|
+
this.allow = 'write';
|
|
113
|
+
this.parent = '';
|
|
114
|
+
this.indexes = new Indexes();
|
|
115
|
+
this.options = new Options();
|
|
116
|
+
this.custom = {};
|
|
117
|
+
this.references = new Set();
|
|
118
|
+
this.relations = new Set();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
#setMany(values) {
|
|
122
|
+
const { kind, scope, store, allow, parent, ...custom } = values;
|
|
123
|
+
this.kind = kind || this.kind;
|
|
124
|
+
this.scope = scope || this.scope;
|
|
125
|
+
this.store = store || this.store;
|
|
126
|
+
this.allow = allow || this.allow;
|
|
127
|
+
this.parent = parent || this.parent;
|
|
128
|
+
this.custom = custom;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
updateFromSchema({ references = [], relations = [] }) {
|
|
132
|
+
for (const ref of references) this.references.add(ref);
|
|
133
|
+
for (const rel of relations) this.relations.add(rel);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
updateFromKind({ kind, meta, root }) {
|
|
137
|
+
const { defs, metadata } = getKindMetadata(kind, meta, root);
|
|
138
|
+
this.#setMany(metadata);
|
|
139
|
+
return defs;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
extractMetadata(defs) {
|
|
143
|
+
const fields = Object.create(null);
|
|
144
|
+
for (const pair of Object.entries(defs)) {
|
|
145
|
+
const key = pair[0];
|
|
146
|
+
const field = pair[1];
|
|
147
|
+
let extracted = false;
|
|
148
|
+
for (const collection of METADATA_COLLECTIONS) {
|
|
149
|
+
const taken = this[collection].extract(key, field);
|
|
150
|
+
if (taken) extracted = true;
|
|
151
|
+
}
|
|
152
|
+
if (!extracted) fields[key] = field;
|
|
153
|
+
}
|
|
154
|
+
return fields;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
validate(value, path) {
|
|
158
|
+
if (!this.options.validate) return null;
|
|
159
|
+
const result = new ValidationResult(path);
|
|
160
|
+
try {
|
|
161
|
+
return result.add(this.options.validate(value, path));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
return result.add(issue('exception', path, `validation failed ${error}`));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
module.exports = { ValidationResult, SchemaMetadata };
|