@kravc/schema 2.7.6 → 2.8.0-alpha.1
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/README.md +19 -14
- package/dist/CredentialFactory.d.ts +345 -0
- package/dist/CredentialFactory.d.ts.map +1 -0
- package/dist/CredentialFactory.js +381 -0
- package/dist/CredentialFactory.js.map +1 -0
- package/dist/Schema.d.ts +448 -0
- package/dist/Schema.d.ts.map +1 -0
- package/dist/Schema.js +506 -0
- package/dist/Schema.js.map +1 -0
- package/dist/ValidationError.d.ts +70 -0
- package/dist/ValidationError.d.ts.map +1 -0
- package/dist/ValidationError.js +78 -0
- package/dist/ValidationError.js.map +1 -0
- package/dist/Validator.d.ts +483 -0
- package/dist/Validator.d.ts.map +1 -0
- package/dist/Validator.js +570 -0
- package/dist/Validator.js.map +1 -0
- package/dist/helpers/JsonSchema.d.ts +99 -0
- package/dist/helpers/JsonSchema.d.ts.map +1 -0
- package/dist/helpers/JsonSchema.js +3 -0
- package/dist/helpers/JsonSchema.js.map +1 -0
- package/dist/helpers/cleanupAttributes.d.ts +34 -0
- package/dist/helpers/cleanupAttributes.d.ts.map +1 -0
- package/dist/helpers/cleanupAttributes.js +113 -0
- package/dist/helpers/cleanupAttributes.js.map +1 -0
- package/dist/helpers/cleanupNulls.d.ts +27 -0
- package/dist/helpers/cleanupNulls.d.ts.map +1 -0
- package/dist/helpers/cleanupNulls.js +96 -0
- package/dist/helpers/cleanupNulls.js.map +1 -0
- package/dist/helpers/createSchemasMap.d.ts +67 -0
- package/dist/helpers/createSchemasMap.d.ts.map +1 -0
- package/dist/helpers/createSchemasMap.js +200 -0
- package/dist/helpers/createSchemasMap.js.map +1 -0
- package/dist/helpers/getReferenceIds.d.ts +169 -0
- package/dist/helpers/getReferenceIds.d.ts.map +1 -0
- package/dist/helpers/getReferenceIds.js +241 -0
- package/dist/helpers/getReferenceIds.js.map +1 -0
- package/dist/helpers/got.d.ts +60 -0
- package/dist/helpers/got.d.ts.map +1 -0
- package/dist/helpers/got.js +72 -0
- package/dist/helpers/got.js.map +1 -0
- package/dist/helpers/mapObjectProperties.d.ts +150 -0
- package/dist/helpers/mapObjectProperties.d.ts.map +1 -0
- package/dist/helpers/mapObjectProperties.js +229 -0
- package/dist/helpers/mapObjectProperties.js.map +1 -0
- package/dist/helpers/normalizeAttributes.d.ts +213 -0
- package/dist/helpers/normalizeAttributes.d.ts.map +1 -0
- package/dist/helpers/normalizeAttributes.js +243 -0
- package/dist/helpers/normalizeAttributes.js.map +1 -0
- package/dist/helpers/normalizeProperties.d.ts +168 -0
- package/dist/helpers/normalizeProperties.d.ts.map +1 -0
- package/dist/helpers/normalizeProperties.js +223 -0
- package/dist/helpers/normalizeProperties.js.map +1 -0
- package/dist/helpers/normalizeRequired.d.ts +159 -0
- package/dist/helpers/normalizeRequired.d.ts.map +1 -0
- package/dist/helpers/normalizeRequired.js +206 -0
- package/dist/helpers/normalizeRequired.js.map +1 -0
- package/dist/helpers/normalizeType.d.ts +81 -0
- package/dist/helpers/normalizeType.d.ts.map +1 -0
- package/dist/helpers/normalizeType.js +210 -0
- package/dist/helpers/normalizeType.js.map +1 -0
- package/dist/helpers/nullifyEmptyValues.d.ts +139 -0
- package/dist/helpers/nullifyEmptyValues.d.ts.map +1 -0
- package/dist/helpers/nullifyEmptyValues.js +191 -0
- package/dist/helpers/nullifyEmptyValues.js.map +1 -0
- package/dist/helpers/removeRequiredAndDefault.d.ts +106 -0
- package/dist/helpers/removeRequiredAndDefault.d.ts.map +1 -0
- package/dist/helpers/removeRequiredAndDefault.js +138 -0
- package/dist/helpers/removeRequiredAndDefault.js.map +1 -0
- package/dist/helpers/validateId.d.ts +39 -0
- package/dist/helpers/validateId.d.ts.map +1 -0
- package/dist/helpers/validateId.js +51 -0
- package/dist/helpers/validateId.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/ld/documentLoader.d.ts +8 -0
- package/dist/ld/documentLoader.d.ts.map +1 -0
- package/dist/ld/documentLoader.js +24 -0
- package/dist/ld/documentLoader.js.map +1 -0
- package/dist/ld/getLinkedDataAttributeType.d.ts +10 -0
- package/dist/ld/getLinkedDataAttributeType.d.ts.map +1 -0
- package/dist/ld/getLinkedDataAttributeType.js +32 -0
- package/dist/ld/getLinkedDataAttributeType.js.map +1 -0
- package/dist/ld/getLinkedDataContext.d.ts +19 -0
- package/dist/ld/getLinkedDataContext.d.ts.map +1 -0
- package/dist/ld/getLinkedDataContext.js +50 -0
- package/dist/ld/getLinkedDataContext.js.map +1 -0
- package/eslint.config.mjs +32 -52
- package/examples/credentials/createAccountCredential.ts +27 -0
- package/examples/credentials/createMineSweeperScoreCredential.ts +115 -0
- package/examples/index.ts +7 -0
- package/examples/schemas/FavoriteItemSchema.ts +27 -0
- package/examples/{Preferences.yaml → schemas/Preferences.yaml} +2 -0
- package/examples/schemas/PreferencesSchema.ts +29 -0
- package/examples/schemas/ProfileSchema.ts +91 -0
- package/examples/schemas/Status.yaml +3 -0
- package/examples/schemas/StatusSchema.ts +12 -0
- package/jest.config.mjs +5 -0
- package/package.json +27 -20
- package/src/CredentialFactory.ts +392 -0
- package/src/Schema.ts +583 -0
- package/src/ValidationError.ts +90 -0
- package/src/Validator.ts +603 -0
- package/src/__tests__/CredentialFactory.test.ts +588 -0
- package/src/__tests__/Schema.test.ts +371 -0
- package/src/__tests__/ValidationError.test.ts +235 -0
- package/src/__tests__/Validator.test.ts +787 -0
- package/src/helpers/JsonSchema.ts +119 -0
- package/src/helpers/__tests__/cleanupAttributes.test.ts +943 -0
- package/src/helpers/__tests__/cleanupNulls.test.ts +772 -0
- package/src/helpers/__tests__/createSchemasMap.test.ts +238 -0
- package/src/helpers/__tests__/getReferenceIds.test.ts +975 -0
- package/src/helpers/__tests__/got.test.ts +193 -0
- package/src/helpers/__tests__/mapObjectProperties.test.ts +1126 -0
- package/src/helpers/__tests__/normalizeAttributes.test.ts +1435 -0
- package/src/helpers/__tests__/normalizeProperties.test.ts +727 -0
- package/src/helpers/__tests__/normalizeRequired.test.ts +669 -0
- package/src/helpers/__tests__/normalizeType.test.ts +772 -0
- package/src/helpers/__tests__/nullifyEmptyValues.test.ts +735 -0
- package/src/helpers/__tests__/removeRequiredAndDefault.test.ts +734 -0
- package/src/helpers/__tests__/validateId.test.ts +118 -0
- package/src/helpers/cleanupAttributes.ts +151 -0
- package/src/helpers/cleanupNulls.ts +106 -0
- package/src/helpers/createSchemasMap.ts +212 -0
- package/src/helpers/getReferenceIds.ts +273 -0
- package/src/helpers/got.ts +73 -0
- package/src/helpers/mapObjectProperties.ts +272 -0
- package/src/helpers/normalizeAttributes.ts +247 -0
- package/src/helpers/normalizeProperties.ts +249 -0
- package/src/helpers/normalizeRequired.ts +233 -0
- package/src/helpers/normalizeType.ts +235 -0
- package/src/helpers/nullifyEmptyValues.ts +207 -0
- package/src/helpers/removeRequiredAndDefault.ts +151 -0
- package/src/helpers/validateId.ts +53 -0
- package/src/index.ts +17 -0
- package/src/ld/__tests__/documentLoader.test.ts +57 -0
- package/src/ld/__tests__/getLinkedDataAttributeType.test.ts +212 -0
- package/src/ld/__tests__/getLinkedDataContext.test.ts +378 -0
- package/src/ld/documentLoader.ts +28 -0
- package/src/ld/getLinkedDataAttributeType.ts +46 -0
- package/src/ld/getLinkedDataContext.ts +80 -0
- package/tsconfig.json +27 -0
- package/types/credentials-context.d.ts +14 -0
- package/types/security-context.d.ts +6 -0
- package/examples/Status.yaml +0 -3
- package/examples/createAccountCredential.js +0 -27
- package/examples/createMineSweeperScoreCredential.js +0 -63
- package/examples/index.js +0 -9
- package/src/CredentialFactory.js +0 -67
- package/src/CredentialFactory.spec.js +0 -131
- package/src/Schema.js +0 -104
- package/src/Schema.spec.js +0 -172
- package/src/ValidationError.js +0 -31
- package/src/Validator.js +0 -128
- package/src/Validator.spec.js +0 -355
- package/src/helpers/cleanupAttributes.js +0 -71
- package/src/helpers/cleanupNulls.js +0 -42
- package/src/helpers/getReferenceIds.js +0 -71
- package/src/helpers/mapObject.js +0 -65
- package/src/helpers/normalizeAttributes.js +0 -28
- package/src/helpers/normalizeProperties.js +0 -61
- package/src/helpers/normalizeRequired.js +0 -37
- package/src/helpers/normalizeType.js +0 -41
- package/src/helpers/nullifyEmptyValues.js +0 -57
- package/src/helpers/removeRequiredAndDefault.js +0 -30
- package/src/helpers/validateId.js +0 -19
- package/src/index.d.ts +0 -25
- package/src/index.js +0 -8
- package/src/ld/documentLoader.js +0 -25
- package/src/ld/documentLoader.spec.js +0 -12
- package/src/ld/getLinkedDataContext.js +0 -63
- package/src/ld/getLinkedDataType.js +0 -38
- /package/examples/{FavoriteItem.yaml → schemas/FavoriteItem.yaml} +0 -0
- /package/examples/{Profile.yaml → schemas/Profile.yaml} +0 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import validateId from '../validateId';
|
|
2
|
+
|
|
3
|
+
const name = 'testId';
|
|
4
|
+
|
|
5
|
+
describe('validateId(name, value)', () => {
|
|
6
|
+
describe('valid inputs', () => {
|
|
7
|
+
describe('URLs', () => {
|
|
8
|
+
it('should accept HTTP URLs', () => {
|
|
9
|
+
expect(() => validateId(name, 'http://example.com')).not.toThrow();
|
|
10
|
+
expect(() => validateId(name, 'http://example.com/path')).not.toThrow();
|
|
11
|
+
expect(() => validateId(name, 'http://example.com:8080/path?query=value')).not.toThrow();
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('should accept HTTPS URLs', () => {
|
|
15
|
+
expect(() => validateId(name, 'https://example.com')).not.toThrow();
|
|
16
|
+
expect(() => validateId(name, 'https://example.com/path')).not.toThrow();
|
|
17
|
+
expect(() => validateId(name, 'https://example.com:443/path#fragment')).not.toThrow();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('should accept other URL schemes', () => {
|
|
21
|
+
expect(() => validateId(name, 'ftp://example.com')).not.toThrow();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('should accept URLs without protocol', () => {
|
|
25
|
+
expect(() => validateId(name, 'example.com')).not.toThrow();
|
|
26
|
+
expect(() => validateId(name, 'subdomain.example.com')).not.toThrow();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('should accept IP address URLs', () => {
|
|
30
|
+
expect(() => validateId(name, 'http://192.168.1.1')).not.toThrow();
|
|
31
|
+
expect(() => validateId(name, 'https://8.8.8.8')).not.toThrow();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('should accept URLs with special characters', () => {
|
|
35
|
+
expect(() => validateId(name, 'https://example.com/path%20with%20spaces')).not.toThrow();
|
|
36
|
+
expect(() => validateId(name, 'https://example.com/path?key=value&other=123')).not.toThrow();
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe('DIDs', () => {
|
|
41
|
+
it('should accept valid DIDs', () => {
|
|
42
|
+
expect(() => validateId(name, 'did:example:123456789')).not.toThrow();
|
|
43
|
+
expect(() => validateId(name, 'did:web:example.com')).not.toThrow();
|
|
44
|
+
expect(() => validateId(name, 'did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK')).not.toThrow();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('should accept DIDs case-insensitively', () => {
|
|
48
|
+
expect(() => validateId(name, 'DID:example:123456789')).not.toThrow();
|
|
49
|
+
expect(() => validateId(name, 'Did:example:123456789')).not.toThrow();
|
|
50
|
+
expect(() => validateId(name, 'dId:example:123456789')).not.toThrow();
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('should accept DIDs with various methods', () => {
|
|
54
|
+
expect(() => validateId(name, 'did:ethr:0x1234567890abcdef')).not.toThrow();
|
|
55
|
+
expect(() => validateId(name, 'did:ion:EiClkZMDZhPKV7e3j4wUmxLukn6YxvfN8v2F2b3X5r8tQ')).not.toThrow();
|
|
56
|
+
expect(() => validateId(name, 'did:peer:123456789')).not.toThrow();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('should accept bare did: prefix (no method or id)', () => {
|
|
60
|
+
expect(() => validateId(name, 'did:')).not.toThrow();
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('invalid inputs', () => {
|
|
66
|
+
describe('missing value', () => {
|
|
67
|
+
it('should throw when value is empty string', () => {
|
|
68
|
+
expect(() => validateId(name, '')).toThrow('Parameter "testId" is required');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('should throw when value is null', () => {
|
|
72
|
+
expect(() => validateId(name, null)).toThrow('Parameter "testId" is required');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('should throw when value is undefined', () => {
|
|
76
|
+
expect(() => validateId(name, undefined)).toThrow('Parameter "testId" is required');
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe('malformed value', () => {
|
|
81
|
+
it('should throw when value is not a URL or DID', () => {
|
|
82
|
+
expect(() => validateId(name, 'not-a-url-or-did')).toThrow(
|
|
83
|
+
'Parameter "testId" must be a URL, received: "not-a-url-or-did"'
|
|
84
|
+
);
|
|
85
|
+
expect(() => validateId(name, 'just some text')).toThrow(
|
|
86
|
+
'Parameter "testId" must be a URL, received: "just some text"'
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('should throw when value is incomplete DID prefix without colon or method', () => {
|
|
91
|
+
expect(() => validateId(name, 'did')).toThrow(
|
|
92
|
+
'Parameter "testId" must be a URL, received: "did"'
|
|
93
|
+
);
|
|
94
|
+
expect(() => validateId(name, 'did ')).toThrow(
|
|
95
|
+
'Parameter "testId" must be a URL, received: "did "'
|
|
96
|
+
);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('should throw when value is whitespace-only', () => {
|
|
100
|
+
expect(() => validateId(name, ' ')).toThrow(
|
|
101
|
+
'Parameter "testId" must be a URL, received: " "'
|
|
102
|
+
);
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe('error messages', () => {
|
|
108
|
+
it('should include parameter name in required error', () => {
|
|
109
|
+
expect(() => validateId('schemaId', '')).toThrow('Parameter "schemaId" is required');
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('should include parameter name in invalid-format error', () => {
|
|
113
|
+
expect(() => validateId('myParam', 'invalid')).toThrow(
|
|
114
|
+
'Parameter "myParam" must be a URL, received: "invalid"'
|
|
115
|
+
);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { isUndefined } from 'lodash';
|
|
2
|
+
|
|
3
|
+
import got from './got';
|
|
4
|
+
import type {
|
|
5
|
+
JsonSchema,
|
|
6
|
+
EnumSchema,
|
|
7
|
+
TargetObject,
|
|
8
|
+
ObjectSchema,
|
|
9
|
+
JsonSchemasMap,
|
|
10
|
+
ArrayPropertySchema,
|
|
11
|
+
ObjectPropertySchema,
|
|
12
|
+
ReferencePropertySchema
|
|
13
|
+
} from './JsonSchema';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Removes properties from an object that are not defined in the JSON schema.
|
|
17
|
+
*
|
|
18
|
+
* **Intent:**
|
|
19
|
+
* This function ensures that objects conform to their schema definition by removing
|
|
20
|
+
* any properties that are not explicitly defined in the schema. It performs a deep
|
|
21
|
+
* cleanup, recursively processing nested objects, arrays, and schema references.
|
|
22
|
+
*
|
|
23
|
+
* **Use Cases:**
|
|
24
|
+
* - **Third-party API integrations**: When integrating with external services (e.g., Telegram)
|
|
25
|
+
* that may send additional fields you don't want to process, this function allows you
|
|
26
|
+
* to define a minimal schema and automatically strip unwanted properties.
|
|
27
|
+
* - **Data sanitization**: Clean up objects received from external sources or user input
|
|
28
|
+
* before validation or processing, ensuring only expected fields are present.
|
|
29
|
+
* - **Schema enforcement**: Enforce strict schema compliance by removing any properties
|
|
30
|
+
* that don't match the defined schema structure.
|
|
31
|
+
* - **Pre-validation cleanup**: Remove extraneous properties before schema validation to
|
|
32
|
+
* prevent validation errors from unexpected fields.
|
|
33
|
+
*
|
|
34
|
+
* **Behavior:**
|
|
35
|
+
* - Mutates the input object in-place (does not return a new object)
|
|
36
|
+
* - Recursively processes nested objects, arrays, and schema references ($ref)
|
|
37
|
+
* - Skips enum schemas (returns early without modification)
|
|
38
|
+
* - Only processes object values (skips null, undefined, and primitive values)
|
|
39
|
+
* - Handles array items by cleaning each object item according to the array's item schema
|
|
40
|
+
*
|
|
41
|
+
* @param object - The target object to clean up (mutated in-place)
|
|
42
|
+
* @param jsonSchema - The JSON schema defining allowed properties
|
|
43
|
+
* @param schemasMap - Optional map of schema IDs to schema definitions for resolving $ref references
|
|
44
|
+
*/
|
|
45
|
+
const cleanupAttributes = (
|
|
46
|
+
object: TargetObject,
|
|
47
|
+
jsonSchema: JsonSchema,
|
|
48
|
+
schemasMap: JsonSchemasMap = {}
|
|
49
|
+
) => {
|
|
50
|
+
const { enum: enumItems } = (jsonSchema as EnumSchema);
|
|
51
|
+
|
|
52
|
+
const isEnum = !!enumItems;
|
|
53
|
+
|
|
54
|
+
if (isEnum) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const objectSchema = (jsonSchema as ObjectSchema);
|
|
59
|
+
|
|
60
|
+
// Guard against malformed schemas without properties
|
|
61
|
+
if (!objectSchema.properties) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
for (const fieldName in object) {
|
|
66
|
+
const property = objectSchema.properties[fieldName];
|
|
67
|
+
|
|
68
|
+
const isPropertyUndefined = isUndefined(property);
|
|
69
|
+
|
|
70
|
+
if (isPropertyUndefined) {
|
|
71
|
+
// NOTE: Delete object property if it's not defined in the object schema:
|
|
72
|
+
delete object[fieldName];
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const { $ref: refSchemaId } = (property as ReferencePropertySchema);
|
|
77
|
+
|
|
78
|
+
const isReference = !isUndefined(refSchemaId);
|
|
79
|
+
|
|
80
|
+
if (isReference) {
|
|
81
|
+
const referenceSchema = got(schemasMap, refSchemaId, 'Schema "$PATH" not found');
|
|
82
|
+
const fieldValue = object[fieldName];
|
|
83
|
+
|
|
84
|
+
// Only recursively cleanup if the value is an object (not null, undefined, or primitive)
|
|
85
|
+
if (fieldValue && typeof fieldValue === 'object' && !Array.isArray(fieldValue)) {
|
|
86
|
+
cleanupAttributes(fieldValue as TargetObject, referenceSchema, schemasMap);
|
|
87
|
+
}
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const { type } = (property as ObjectPropertySchema | ArrayPropertySchema);
|
|
92
|
+
|
|
93
|
+
const isObject = type === 'object';
|
|
94
|
+
|
|
95
|
+
if (isObject) {
|
|
96
|
+
const { properties = {} } = (property as ObjectPropertySchema);
|
|
97
|
+
|
|
98
|
+
const fieldValue = object[fieldName];
|
|
99
|
+
|
|
100
|
+
const isObjectValue = fieldValue &&
|
|
101
|
+
typeof fieldValue === 'object' &&
|
|
102
|
+
!Array.isArray(fieldValue);
|
|
103
|
+
|
|
104
|
+
if (isObjectValue) {
|
|
105
|
+
const nestedJsonSchema = {
|
|
106
|
+
id: `${objectSchema.id}.${fieldName}.properties`,
|
|
107
|
+
properties
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
cleanupAttributes(fieldValue as TargetObject, nestedJsonSchema, schemasMap);
|
|
111
|
+
}
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const isArray = type === 'array';
|
|
116
|
+
|
|
117
|
+
if (isArray) {
|
|
118
|
+
const { items } = (property as ArrayPropertySchema);
|
|
119
|
+
|
|
120
|
+
const fieldValue = object[fieldName];
|
|
121
|
+
const isArrayValue = Array.isArray(fieldValue);
|
|
122
|
+
|
|
123
|
+
if (isArrayValue && items) {
|
|
124
|
+
const { $ref: itemRefSchemaId } = (items as ReferencePropertySchema);
|
|
125
|
+
|
|
126
|
+
const { properties: itemObjectProperties = {} } = (items as ObjectPropertySchema);
|
|
127
|
+
|
|
128
|
+
const isItemReference = !isUndefined(itemRefSchemaId);
|
|
129
|
+
|
|
130
|
+
const itemSchema = isItemReference
|
|
131
|
+
? got(schemasMap, itemRefSchemaId, 'Schema "$PATH" not found')
|
|
132
|
+
: {
|
|
133
|
+
id: `${objectSchema.id}.${fieldName}.items.properties`,
|
|
134
|
+
properties: itemObjectProperties
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
for (const item of fieldValue) {
|
|
138
|
+
const isObjectItem = item &&
|
|
139
|
+
typeof item === 'object' &&
|
|
140
|
+
!Array.isArray(item);
|
|
141
|
+
|
|
142
|
+
if (isObjectItem) {
|
|
143
|
+
cleanupAttributes(item as TargetObject, itemSchema, schemasMap);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export default cleanupAttributes;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { isObject, cloneDeep } from 'lodash';
|
|
2
|
+
|
|
3
|
+
import { type TargetObject } from './JsonSchema';
|
|
4
|
+
|
|
5
|
+
const { isArray } = Array;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Recursively removes null properties from an object.
|
|
9
|
+
*
|
|
10
|
+
* **Intent:**
|
|
11
|
+
* This function provides a deep cleanup of objects by removing all properties
|
|
12
|
+
* that have `null` values. It's designed to sanitize objects before validation,
|
|
13
|
+
* storage, or transmission by eliminating explicitly null fields.
|
|
14
|
+
*
|
|
15
|
+
* **Use Cases:**
|
|
16
|
+
* - **Pre-validation cleanup**: Remove null values before schema validation to
|
|
17
|
+
* prevent validation errors from optional fields that were explicitly set to null.
|
|
18
|
+
* This is particularly useful when `shouldCleanupNulls` is enabled in the Validator,
|
|
19
|
+
* allowing you to clean objects before `cleanupAttributes` removes undefined properties.
|
|
20
|
+
* - **Data sanitization**: Clean objects received from external sources (APIs, user input,
|
|
21
|
+
* databases) by removing null properties that may have been set during data transformation
|
|
22
|
+
* or migration processes.
|
|
23
|
+
* - **API response normalization**: Prepare objects for API responses by removing null fields,
|
|
24
|
+
* reducing payload size and ensuring consistent data structures across different endpoints.
|
|
25
|
+
* - **Database operations**: Clean objects before database storage or updates, removing
|
|
26
|
+
* null fields that might cause issues with database constraints or indexing.
|
|
27
|
+
* - **JSON serialization optimization**: Reduce JSON payload size by removing null properties
|
|
28
|
+
* before serialization, which is especially beneficial for large objects or high-frequency
|
|
29
|
+
* API calls.
|
|
30
|
+
* - **Optional field handling**: Remove explicitly null optional fields that weren't provided
|
|
31
|
+
* by the user, distinguishing between "field not provided" (undefined) and "field set to null".
|
|
32
|
+
*
|
|
33
|
+
* **Behavior:**
|
|
34
|
+
* - Returns a deep clone of the input object (does not mutate the original)
|
|
35
|
+
* - Recursively processes nested objects and arrays at all depth levels
|
|
36
|
+
* - Only removes properties with `null` values (preserves `undefined`, `0`, `false`, `''`, etc.)
|
|
37
|
+
* - Skips non-object values (returns early for primitives)
|
|
38
|
+
* - Handles arrays by recursively processing each item
|
|
39
|
+
* - Preserves object structure and non-null values exactly as they are
|
|
40
|
+
*
|
|
41
|
+
* @param target - The target object to clean (processed recursively, not mutated)
|
|
42
|
+
*/
|
|
43
|
+
const cleanupNulls = (target: TargetObject) => {
|
|
44
|
+
const shouldSkip = !isObject(target);
|
|
45
|
+
|
|
46
|
+
if (shouldSkip) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
for (const key in target) {
|
|
51
|
+
const value = target[key];
|
|
52
|
+
|
|
53
|
+
if (isArray(value)) {
|
|
54
|
+
for (const item of value) {
|
|
55
|
+
cleanupNulls(item);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (isObject(value)) {
|
|
62
|
+
cleanupNulls(value as Record<string, unknown>);
|
|
63
|
+
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const isNull = value === null;
|
|
68
|
+
|
|
69
|
+
if (isNull) {
|
|
70
|
+
delete target[key];
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Returns a deep copy of the object with all null properties removed.
|
|
77
|
+
*
|
|
78
|
+
* This is the main exported function that creates a clone of the input object
|
|
79
|
+
* and removes all null properties recursively before returning it.
|
|
80
|
+
*
|
|
81
|
+
* @param object - The object to clean (will be cloned, original is not modified)
|
|
82
|
+
* @returns A new object with all null properties removed recursively
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* const dirty = {
|
|
87
|
+
* name: 'John',
|
|
88
|
+
* age: null,
|
|
89
|
+
* address: {
|
|
90
|
+
* street: 'Main St',
|
|
91
|
+
* zip: null
|
|
92
|
+
* }
|
|
93
|
+
* };
|
|
94
|
+
*
|
|
95
|
+
* const clean = cleanupNulls(dirty);
|
|
96
|
+
* // Result: { name: 'John', address: { street: 'Main St' } }
|
|
97
|
+
* // Original 'dirty' object is unchanged
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
export default function (object: Record<string, unknown>) {
|
|
101
|
+
const clone = cloneDeep(object);
|
|
102
|
+
|
|
103
|
+
cleanupNulls(clone);
|
|
104
|
+
|
|
105
|
+
return clone;
|
|
106
|
+
};
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import Schema from '../Schema';
|
|
3
|
+
import { load } from 'js-yaml';
|
|
4
|
+
import { keyBy } from 'lodash';
|
|
5
|
+
import type { EnumSchema, PropertiesSchema } from './JsonSchema';
|
|
6
|
+
import { readFileSync, readdirSync, statSync } from 'fs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Reads schema source from YAML file and returns a Schema instance.
|
|
10
|
+
*
|
|
11
|
+
* **Intent:** Load and parse a single YAML schema file, extracting the schema ID
|
|
12
|
+
* from the filename and creating a Schema instance for use in validation or
|
|
13
|
+
* schema composition.
|
|
14
|
+
*
|
|
15
|
+
* **Use Cases:**
|
|
16
|
+
* - Load individual schema files during application startup
|
|
17
|
+
* - Parse YAML schema definitions into Schema instances
|
|
18
|
+
* - Extract schema identifiers from file paths automatically
|
|
19
|
+
* - Support both enum and properties-based schemas from YAML files
|
|
20
|
+
*
|
|
21
|
+
* @param yamlPath - Absolute or relative path to the YAML schema file
|
|
22
|
+
* @returns A Schema instance with ID extracted from the filename (without .yaml extension)
|
|
23
|
+
*
|
|
24
|
+
* **Example:**
|
|
25
|
+
* ```typescript
|
|
26
|
+
* const schema = loadSync('/path/to/schemas/User.yaml');
|
|
27
|
+
* // schema.id === 'User'
|
|
28
|
+
* // schema.source contains the parsed YAML content
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* **Example - Enum Schema:**
|
|
32
|
+
* ```typescript
|
|
33
|
+
* const statusSchema = loadSync('/path/to/schemas/Status.yaml');
|
|
34
|
+
* // If Status.yaml contains: { enum: ['PENDING', 'ACTIVE'] }
|
|
35
|
+
* // statusSchema.isEnum === true
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
const loadSync = (yamlPath: string) => {
|
|
39
|
+
const schemaId = yamlPath
|
|
40
|
+
.split('/')
|
|
41
|
+
.reverse()[0]
|
|
42
|
+
.split('.yaml')[0];
|
|
43
|
+
|
|
44
|
+
const file = readFileSync(yamlPath);
|
|
45
|
+
const source = load(file.toString()) as EnumSchema | PropertiesSchema;
|
|
46
|
+
|
|
47
|
+
return new Schema(source, schemaId);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Recursively lists all files in a directory and its subdirectories.
|
|
52
|
+
*
|
|
53
|
+
* **Intent:** Traverse a directory tree and collect all file paths, enabling
|
|
54
|
+
* discovery of schema files nested in subdirectories without manual path specification.
|
|
55
|
+
*
|
|
56
|
+
* **Use Cases:**
|
|
57
|
+
* - Find all schema files in a directory structure
|
|
58
|
+
* - Support organized schema layouts with nested folders
|
|
59
|
+
* - Enable schema discovery without hardcoding file paths
|
|
60
|
+
* - Prepare file list for filtering and processing
|
|
61
|
+
*
|
|
62
|
+
* @param servicePath - Path to the directory to traverse
|
|
63
|
+
* @returns Array of absolute file paths found in the directory tree
|
|
64
|
+
*
|
|
65
|
+
* **Example:**
|
|
66
|
+
* ```typescript
|
|
67
|
+
* const files = listFilesSync('/path/to/schemas');
|
|
68
|
+
* // Returns: [
|
|
69
|
+
* // '/path/to/schemas/User.yaml',
|
|
70
|
+
* // '/path/to/schemas/nested/Profile.yaml',
|
|
71
|
+
* // '/path/to/schemas/nested/deep/Status.yaml'
|
|
72
|
+
* // ]
|
|
73
|
+
* ```
|
|
74
|
+
*
|
|
75
|
+
* **Example - Flat Directory:**
|
|
76
|
+
* ```typescript
|
|
77
|
+
* const files = listFilesSync('/path/to/schemas');
|
|
78
|
+
* // Returns: [
|
|
79
|
+
* // '/path/to/schemas/User.yaml',
|
|
80
|
+
* // '/path/to/schemas/Profile.yaml'
|
|
81
|
+
* // ]
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
const listFilesSync = (servicePath: string): string[] =>
|
|
85
|
+
readdirSync(servicePath)
|
|
86
|
+
.reduce(
|
|
87
|
+
(filePaths: string[], fileName: string) =>
|
|
88
|
+
statSync(
|
|
89
|
+
path.join(servicePath, fileName)).isDirectory() ?
|
|
90
|
+
filePaths.concat(listFilesSync(path.join(servicePath, fileName))) :
|
|
91
|
+
filePaths.concat(path.join(servicePath, fileName)
|
|
92
|
+
)
|
|
93
|
+
, []);
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Reads all YAML schema files from a directory and creates Schema instances.
|
|
97
|
+
*
|
|
98
|
+
* **Intent:** Bulk load schema definitions from YAML files in a directory,
|
|
99
|
+
* automatically discovering and parsing all schema files for use in schema
|
|
100
|
+
* registries or validators.
|
|
101
|
+
*
|
|
102
|
+
* **Use Cases:**
|
|
103
|
+
* - Load all schemas from a schemas directory at application startup
|
|
104
|
+
* - Initialize schema registries from file-based definitions
|
|
105
|
+
* - Support schema-as-code workflows where schemas are stored as YAML files
|
|
106
|
+
* - Enable automatic schema discovery without manual registration
|
|
107
|
+
*
|
|
108
|
+
* @param servicePath - Path to the directory containing YAML schema files
|
|
109
|
+
* @returns Array of Schema instances, one for each YAML file found
|
|
110
|
+
*
|
|
111
|
+
* **Example:**
|
|
112
|
+
* ```typescript
|
|
113
|
+
* const schemas = readSchemasSync('/path/to/examples/schemas');
|
|
114
|
+
* // Returns: [
|
|
115
|
+
* // Schema { id: 'FavoriteItem', ... },
|
|
116
|
+
* // Schema { id: 'Profile', ... },
|
|
117
|
+
* // Schema { id: 'Status', ... },
|
|
118
|
+
* // Schema { id: 'Preferences', ... }
|
|
119
|
+
* // ]
|
|
120
|
+
* ```
|
|
121
|
+
*
|
|
122
|
+
* **Example - With Nested Directories:**
|
|
123
|
+
* ```typescript
|
|
124
|
+
* const schemas = readSchemasSync('/path/to/schemas');
|
|
125
|
+
* // Automatically finds schemas in subdirectories:
|
|
126
|
+
* // - /path/to/schemas/User.yaml
|
|
127
|
+
* // - /path/to/schemas/nested/Profile.yaml
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
const readSchemasSync = (servicePath: string) =>
|
|
131
|
+
listFilesSync(servicePath)
|
|
132
|
+
.filter((fileName: string) => fileName.endsWith('.yaml'))
|
|
133
|
+
.map((schemaPath: string) => loadSync(schemaPath));
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Creates a map of schemas by ID, loading from YAML files and merging with programmatic schemas.
|
|
137
|
+
*
|
|
138
|
+
* **Intent:** Build a centralized schema registry that combines file-based YAML schemas
|
|
139
|
+
* with programmatically created Schema instances, providing a unified lookup mechanism
|
|
140
|
+
* by schema ID. This enables hybrid schema management where some schemas are defined
|
|
141
|
+
* in YAML files while others are created dynamically in code.
|
|
142
|
+
*
|
|
143
|
+
* **Use Cases:**
|
|
144
|
+
* - Initialize schema registries for validators from both files and code
|
|
145
|
+
* - Support schema composition where base schemas come from files and extended
|
|
146
|
+
* schemas are created programmatically
|
|
147
|
+
* - Enable schema overriding where programmatic schemas can replace file-based ones
|
|
148
|
+
* - Build schema maps for credential factories or API validation systems
|
|
149
|
+
* - Support development workflows where schemas evolve from YAML to code
|
|
150
|
+
*
|
|
151
|
+
* @param servicePath - Path to directory containing YAML schema files (searched recursively)
|
|
152
|
+
* @param modules - Array of Schema instances or other values (non-Schema values are filtered out)
|
|
153
|
+
* @returns Record mapping schema IDs to Schema instances, with modules schemas overriding YAML schemas
|
|
154
|
+
*
|
|
155
|
+
* **Example - Basic Usage:**
|
|
156
|
+
* ```typescript
|
|
157
|
+
* const schemasMap = createSchemasMap('/path/to/examples/schemas', []);
|
|
158
|
+
* // Returns: {
|
|
159
|
+
* // FavoriteItem: Schema { id: 'FavoriteItem', ... },
|
|
160
|
+
* // Profile: Schema { id: 'Profile', ... },
|
|
161
|
+
* // Status: Schema { id: 'Status', ... },
|
|
162
|
+
* // Preferences: Schema { id: 'Preferences', ... }
|
|
163
|
+
* // }
|
|
164
|
+
* ```
|
|
165
|
+
*
|
|
166
|
+
* **Example - Merging Programmatic Schemas:**
|
|
167
|
+
* ```typescript
|
|
168
|
+
* const customSchema = new Schema(
|
|
169
|
+
* { customField: { type: 'string' } },
|
|
170
|
+
* 'CustomSchema'
|
|
171
|
+
* );
|
|
172
|
+
* const schemasMap = createSchemasMap('/path/to/schemas', [customSchema]);
|
|
173
|
+
* // schemasMap contains both YAML schemas and CustomSchema
|
|
174
|
+
* ```
|
|
175
|
+
*
|
|
176
|
+
* **Example - Overriding YAML Schemas:**
|
|
177
|
+
* ```typescript
|
|
178
|
+
* const updatedProfile = new Schema(
|
|
179
|
+
* { name: { type: 'string' }, newField: { type: 'number' } },
|
|
180
|
+
* 'Profile'
|
|
181
|
+
* );
|
|
182
|
+
* const schemasMap = createSchemasMap('/path/to/schemas', [updatedProfile]);
|
|
183
|
+
* // schemasMap.Profile is the updatedProfile instance, not the YAML version
|
|
184
|
+
* ```
|
|
185
|
+
*
|
|
186
|
+
* **Example - Filtering Non-Schema Values:**
|
|
187
|
+
* ```typescript
|
|
188
|
+
* const schema = new Schema({ field: { type: 'string' } }, 'Test');
|
|
189
|
+
* const schemasMap = createSchemasMap('/path/to/schemas', [
|
|
190
|
+
* schema,
|
|
191
|
+
* 'not a schema',
|
|
192
|
+
* { id: 'fake' },
|
|
193
|
+
* null
|
|
194
|
+
* ]);
|
|
195
|
+
* // Only the Schema instance is included, other values are ignored
|
|
196
|
+
* ```
|
|
197
|
+
*/
|
|
198
|
+
const createSchemasMap = (servicePath: string, modules: unknown[]): Record<string, Schema> => {
|
|
199
|
+
const yamlSchemas = readSchemasSync(servicePath);
|
|
200
|
+
const schemasMap = keyBy(yamlSchemas, 'id');
|
|
201
|
+
|
|
202
|
+
const schemas = modules
|
|
203
|
+
.filter(schema => schema instanceof Schema);
|
|
204
|
+
|
|
205
|
+
for (const schema of schemas) {
|
|
206
|
+
schemasMap[schema.id] = schema;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return schemasMap;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
export default createSchemasMap;
|