@kravc/schema 2.7.6 → 2.8.0-alpha.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.
Files changed (170) hide show
  1. package/README.md +19 -14
  2. package/dist/CredentialFactory.d.ts +345 -0
  3. package/dist/CredentialFactory.d.ts.map +1 -0
  4. package/dist/CredentialFactory.js +381 -0
  5. package/dist/CredentialFactory.js.map +1 -0
  6. package/dist/Schema.d.ts +448 -0
  7. package/dist/Schema.d.ts.map +1 -0
  8. package/dist/Schema.js +506 -0
  9. package/dist/Schema.js.map +1 -0
  10. package/dist/ValidationError.d.ts +70 -0
  11. package/dist/ValidationError.d.ts.map +1 -0
  12. package/dist/ValidationError.js +78 -0
  13. package/dist/ValidationError.js.map +1 -0
  14. package/dist/Validator.d.ts +483 -0
  15. package/dist/Validator.d.ts.map +1 -0
  16. package/dist/Validator.js +570 -0
  17. package/dist/Validator.js.map +1 -0
  18. package/dist/helpers/JsonSchema.d.ts +99 -0
  19. package/dist/helpers/JsonSchema.d.ts.map +1 -0
  20. package/dist/helpers/JsonSchema.js +3 -0
  21. package/dist/helpers/JsonSchema.js.map +1 -0
  22. package/dist/helpers/cleanupAttributes.d.ts +34 -0
  23. package/dist/helpers/cleanupAttributes.d.ts.map +1 -0
  24. package/dist/helpers/cleanupAttributes.js +113 -0
  25. package/dist/helpers/cleanupAttributes.js.map +1 -0
  26. package/dist/helpers/cleanupNulls.d.ts +27 -0
  27. package/dist/helpers/cleanupNulls.d.ts.map +1 -0
  28. package/dist/helpers/cleanupNulls.js +96 -0
  29. package/dist/helpers/cleanupNulls.js.map +1 -0
  30. package/dist/helpers/getReferenceIds.d.ts +169 -0
  31. package/dist/helpers/getReferenceIds.d.ts.map +1 -0
  32. package/dist/helpers/getReferenceIds.js +241 -0
  33. package/dist/helpers/getReferenceIds.js.map +1 -0
  34. package/dist/helpers/got.d.ts +60 -0
  35. package/dist/helpers/got.d.ts.map +1 -0
  36. package/dist/helpers/got.js +72 -0
  37. package/dist/helpers/got.js.map +1 -0
  38. package/dist/helpers/mapObjectProperties.d.ts +150 -0
  39. package/dist/helpers/mapObjectProperties.d.ts.map +1 -0
  40. package/dist/helpers/mapObjectProperties.js +229 -0
  41. package/dist/helpers/mapObjectProperties.js.map +1 -0
  42. package/dist/helpers/normalizeAttributes.d.ts +213 -0
  43. package/dist/helpers/normalizeAttributes.d.ts.map +1 -0
  44. package/dist/helpers/normalizeAttributes.js +243 -0
  45. package/dist/helpers/normalizeAttributes.js.map +1 -0
  46. package/dist/helpers/normalizeProperties.d.ts +168 -0
  47. package/dist/helpers/normalizeProperties.d.ts.map +1 -0
  48. package/dist/helpers/normalizeProperties.js +223 -0
  49. package/dist/helpers/normalizeProperties.js.map +1 -0
  50. package/dist/helpers/normalizeRequired.d.ts +159 -0
  51. package/dist/helpers/normalizeRequired.d.ts.map +1 -0
  52. package/dist/helpers/normalizeRequired.js +206 -0
  53. package/dist/helpers/normalizeRequired.js.map +1 -0
  54. package/dist/helpers/normalizeType.d.ts +81 -0
  55. package/dist/helpers/normalizeType.d.ts.map +1 -0
  56. package/dist/helpers/normalizeType.js +210 -0
  57. package/dist/helpers/normalizeType.js.map +1 -0
  58. package/dist/helpers/nullifyEmptyValues.d.ts +139 -0
  59. package/dist/helpers/nullifyEmptyValues.d.ts.map +1 -0
  60. package/dist/helpers/nullifyEmptyValues.js +191 -0
  61. package/dist/helpers/nullifyEmptyValues.js.map +1 -0
  62. package/dist/helpers/removeRequiredAndDefault.d.ts +106 -0
  63. package/dist/helpers/removeRequiredAndDefault.d.ts.map +1 -0
  64. package/dist/helpers/removeRequiredAndDefault.js +138 -0
  65. package/dist/helpers/removeRequiredAndDefault.js.map +1 -0
  66. package/dist/helpers/validateId.d.ts +39 -0
  67. package/dist/helpers/validateId.d.ts.map +1 -0
  68. package/dist/helpers/validateId.js +51 -0
  69. package/dist/helpers/validateId.js.map +1 -0
  70. package/dist/index.d.ts +7 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +17 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/ld/documentLoader.d.ts +8 -0
  75. package/dist/ld/documentLoader.d.ts.map +1 -0
  76. package/dist/ld/documentLoader.js +24 -0
  77. package/dist/ld/documentLoader.js.map +1 -0
  78. package/dist/ld/getLinkedDataAttributeType.d.ts +10 -0
  79. package/dist/ld/getLinkedDataAttributeType.d.ts.map +1 -0
  80. package/dist/ld/getLinkedDataAttributeType.js +32 -0
  81. package/dist/ld/getLinkedDataAttributeType.js.map +1 -0
  82. package/dist/ld/getLinkedDataContext.d.ts +19 -0
  83. package/dist/ld/getLinkedDataContext.d.ts.map +1 -0
  84. package/dist/ld/getLinkedDataContext.js +50 -0
  85. package/dist/ld/getLinkedDataContext.js.map +1 -0
  86. package/eslint.config.mjs +32 -52
  87. package/examples/credentials/createAccountCredential.ts +27 -0
  88. package/examples/credentials/createMineSweeperScoreCredential.ts +115 -0
  89. package/examples/index.ts +7 -0
  90. package/examples/schemas/FavoriteItemSchema.ts +27 -0
  91. package/examples/{Preferences.yaml → schemas/Preferences.yaml} +2 -0
  92. package/examples/schemas/PreferencesSchema.ts +29 -0
  93. package/examples/schemas/ProfileSchema.ts +91 -0
  94. package/examples/schemas/Status.yaml +3 -0
  95. package/examples/schemas/StatusSchema.ts +12 -0
  96. package/jest.config.mjs +5 -0
  97. package/package.json +27 -20
  98. package/src/CredentialFactory.ts +392 -0
  99. package/src/Schema.ts +583 -0
  100. package/src/ValidationError.ts +90 -0
  101. package/src/Validator.ts +603 -0
  102. package/src/__tests__/CredentialFactory.test.ts +588 -0
  103. package/src/__tests__/Schema.test.ts +371 -0
  104. package/src/__tests__/ValidationError.test.ts +235 -0
  105. package/src/__tests__/Validator.test.ts +787 -0
  106. package/src/helpers/JsonSchema.ts +119 -0
  107. package/src/helpers/__tests__/cleanupAttributes.test.ts +943 -0
  108. package/src/helpers/__tests__/cleanupNulls.test.ts +772 -0
  109. package/src/helpers/__tests__/getReferenceIds.test.ts +975 -0
  110. package/src/helpers/__tests__/got.test.ts +193 -0
  111. package/src/helpers/__tests__/mapObjectProperties.test.ts +1126 -0
  112. package/src/helpers/__tests__/normalizeAttributes.test.ts +1435 -0
  113. package/src/helpers/__tests__/normalizeProperties.test.ts +727 -0
  114. package/src/helpers/__tests__/normalizeRequired.test.ts +669 -0
  115. package/src/helpers/__tests__/normalizeType.test.ts +772 -0
  116. package/src/helpers/__tests__/nullifyEmptyValues.test.ts +735 -0
  117. package/src/helpers/__tests__/removeRequiredAndDefault.test.ts +734 -0
  118. package/src/helpers/__tests__/validateId.test.ts +118 -0
  119. package/src/helpers/cleanupAttributes.ts +151 -0
  120. package/src/helpers/cleanupNulls.ts +106 -0
  121. package/src/helpers/getReferenceIds.ts +273 -0
  122. package/src/helpers/got.ts +73 -0
  123. package/src/helpers/mapObjectProperties.ts +272 -0
  124. package/src/helpers/normalizeAttributes.ts +247 -0
  125. package/src/helpers/normalizeProperties.ts +249 -0
  126. package/src/helpers/normalizeRequired.ts +233 -0
  127. package/src/helpers/normalizeType.ts +235 -0
  128. package/src/helpers/nullifyEmptyValues.ts +207 -0
  129. package/src/helpers/removeRequiredAndDefault.ts +151 -0
  130. package/src/helpers/validateId.ts +53 -0
  131. package/src/index.ts +13 -0
  132. package/src/ld/__tests__/documentLoader.test.ts +57 -0
  133. package/src/ld/__tests__/getLinkedDataAttributeType.test.ts +212 -0
  134. package/src/ld/__tests__/getLinkedDataContext.test.ts +378 -0
  135. package/src/ld/documentLoader.ts +28 -0
  136. package/src/ld/getLinkedDataAttributeType.ts +46 -0
  137. package/src/ld/getLinkedDataContext.ts +80 -0
  138. package/tsconfig.json +27 -0
  139. package/types/credentials-context.d.ts +14 -0
  140. package/types/security-context.d.ts +6 -0
  141. package/examples/Status.yaml +0 -3
  142. package/examples/createAccountCredential.js +0 -27
  143. package/examples/createMineSweeperScoreCredential.js +0 -63
  144. package/examples/index.js +0 -9
  145. package/src/CredentialFactory.js +0 -67
  146. package/src/CredentialFactory.spec.js +0 -131
  147. package/src/Schema.js +0 -104
  148. package/src/Schema.spec.js +0 -172
  149. package/src/ValidationError.js +0 -31
  150. package/src/Validator.js +0 -128
  151. package/src/Validator.spec.js +0 -355
  152. package/src/helpers/cleanupAttributes.js +0 -71
  153. package/src/helpers/cleanupNulls.js +0 -42
  154. package/src/helpers/getReferenceIds.js +0 -71
  155. package/src/helpers/mapObject.js +0 -65
  156. package/src/helpers/normalizeAttributes.js +0 -28
  157. package/src/helpers/normalizeProperties.js +0 -61
  158. package/src/helpers/normalizeRequired.js +0 -37
  159. package/src/helpers/normalizeType.js +0 -41
  160. package/src/helpers/nullifyEmptyValues.js +0 -57
  161. package/src/helpers/removeRequiredAndDefault.js +0 -30
  162. package/src/helpers/validateId.js +0 -19
  163. package/src/index.d.ts +0 -25
  164. package/src/index.js +0 -8
  165. package/src/ld/documentLoader.js +0 -25
  166. package/src/ld/documentLoader.spec.js +0 -12
  167. package/src/ld/getLinkedDataContext.js +0 -63
  168. package/src/ld/getLinkedDataType.js +0 -38
  169. /package/examples/{FavoriteItem.yaml → schemas/FavoriteItem.yaml} +0 -0
  170. /package/examples/{Profile.yaml → schemas/Profile.yaml} +0 -0
package/src/Schema.ts ADDED
@@ -0,0 +1,583 @@
1
+ import { pick, cloneDeep } from 'lodash';
2
+
3
+ import validateId from './helpers/validateId';
4
+ import normalizeRequired from './helpers/normalizeRequired';
5
+ import normalizeProperties from './helpers/normalizeProperties';
6
+ import getLinkedDataContext from './ld/getLinkedDataContext';
7
+ import removeRequiredAndDefault from './helpers/removeRequiredAndDefault';
8
+ import type { LinkedDataContext } from './ld/getLinkedDataContext';
9
+ import type {
10
+ JsonSchema,
11
+ EnumSchema,
12
+ PropertiesSchema,
13
+ ObjectSchema
14
+ } from './helpers/JsonSchema';
15
+
16
+ const UNDEFINED_SCHEMA_ID = 'UNDEFINED_SCHEMA_ID';
17
+
18
+ /**
19
+ * JSON-LD linked data type structure for semantic web integration.
20
+ *
21
+ * **Intent:** Provide a standardized format for representing schemas in the
22
+ * semantic web, enabling integration with Linked Data and Verifiable Credentials.
23
+ *
24
+ * **Use Cases:**
25
+ * - Generate Verifiable Credentials with proper semantic context
26
+ * - Create JSON-LD documents compatible with schema.org and other vocabularies
27
+ * - Enable semantic interoperability between different systems
28
+ * - Support decentralized identity and credential systems
29
+ *
30
+ * **Structure:**
31
+ * - `@id`: The unique identifier (URI) for the schema type
32
+ * - `@context`: The JSON-LD context mapping properties to semantic types
33
+ *
34
+ * **Example:**
35
+ * ```typescript
36
+ * const schema = new Schema(
37
+ * { name: { type: 'string' }, email: { type: 'string', format: 'email' } },
38
+ * 'Person',
39
+ * 'https://schema.org/'
40
+ * );
41
+ *
42
+ * const linkedData = schema.linkedDataType;
43
+ * // {
44
+ * // '@id': 'https://schema.org/Person',
45
+ * // '@context': {
46
+ * // '@vocab': 'https://schema.org/',
47
+ * // 'name': 'https://schema.org/name',
48
+ * // 'email': 'https://schema.org/email'
49
+ * // }
50
+ * // }
51
+ * ```
52
+ */
53
+ export type LinkedDataType = {
54
+ '@id': string;
55
+ '@context': LinkedDataContext;
56
+ }
57
+
58
+ /**
59
+ * Schema class for defining and manipulating JSON schemas for object validation.
60
+ *
61
+ * This class provides a flexible API for creating, transforming, and composing JSON schemas.
62
+ * It supports both property-based schemas (for objects) and enum schemas (for value sets).
63
+ *
64
+ * **Use Cases:**
65
+ * - Define validation schemas for API request/response objects
66
+ * - Create reusable schema components that can be extended or composed
67
+ * - Generate JSON-LD linked data types for semantic web applications
68
+ * - Transform schemas for different use cases (e.g., create update schemas from create schemas)
69
+ *
70
+ * **Example - Basic Usage:**
71
+ * ```typescript
72
+ * const userSchema = new Schema({
73
+ * firstName: { type: 'string', required: true },
74
+ * lastName: { type: 'string', required: true },
75
+ * email: { type: 'string', format: 'email', required: true }
76
+ * }, 'User');
77
+ * ```
78
+ *
79
+ * **Example - Schema Composition:**
80
+ * ```typescript
81
+ * const baseSchema = new Schema({ name: { required: true } }, 'Base');
82
+ * const extendedSchema = baseSchema.extend({ status: { enum: ['Active', 'Inactive'] } }, 'Extended');
83
+ * ```
84
+ *
85
+ * **Example - Linked Data Types:**
86
+ * ```typescript
87
+ * const schema = new Schema(
88
+ * { id: { type: 'string' }, name: { type: 'string' } },
89
+ * 'Person',
90
+ * 'https://schema.org/'
91
+ * );
92
+ * // schema.linkedDataType will contain JSON-LD context
93
+ * ```
94
+ */
95
+ class Schema {
96
+ private _id: string;
97
+ private _url?: string;
98
+ private _source: PropertiesSchema | EnumSchema;
99
+ private _linkedDataType?: LinkedDataType;
100
+
101
+ /**
102
+ * Creates a new Schema instance.
103
+ *
104
+ * **Intent:** Initialize a schema with properties, enum values, or clone from another schema.
105
+ * Automatically normalizes properties, infers types, and optionally creates JSON-LD linked data types.
106
+ *
107
+ * **Use Cases:**
108
+ * - Create a new schema from scratch with property definitions
109
+ * - Create an enum schema for value validation
110
+ * - Clone an existing schema with a new ID
111
+ * - Create a schema with JSON-LD context for semantic web applications
112
+ *
113
+ * @param propertiesOrSchema - Property definitions, enum schema, or existing Schema instance to clone
114
+ * @param id - Unique identifier for the schema (defaults to 'UNDEFINED_SCHEMA_ID' if not provided)
115
+ * @param url - Optional URL for generating JSON-LD linked data types (only for property schemas, not enums)
116
+ *
117
+ * **Example - Property Schema:**
118
+ * ```typescript
119
+ * const schema = new Schema({
120
+ * name: { type: 'string', required: true },
121
+ * age: { type: 'number', minimum: 0 }
122
+ * }, 'Person');
123
+ * ```
124
+ *
125
+ * **Example - Enum Schema:**
126
+ * ```typescript
127
+ * const sizeSchema = new Schema({ enum: ['S', 'M', 'L'], type: 'string' }, 'Size');
128
+ * ```
129
+ *
130
+ * **Example - Clone Schema:**
131
+ * ```typescript
132
+ * const original = new Schema({ name: { type: 'string' } }, 'Original');
133
+ * const cloned = new Schema(original, 'Cloned');
134
+ * ```
135
+ *
136
+ * **Example - With Linked Data URL:**
137
+ * ```typescript
138
+ * const schema = new Schema(
139
+ * { name: { type: 'string' } },
140
+ * 'Person',
141
+ * 'https://schema.org/'
142
+ * );
143
+ * // Automatically creates linkedDataType with @id and @context
144
+ * ```
145
+ */
146
+ constructor(propertiesOrSchema: EnumSchema | PropertiesSchema | Schema, id?: string, url?: string) {
147
+ this._id = id || UNDEFINED_SCHEMA_ID;
148
+
149
+ this._url = url;
150
+
151
+ const isSchema = propertiesOrSchema instanceof Schema;
152
+
153
+ this._source = isSchema
154
+ ? propertiesOrSchema.source
155
+ : propertiesOrSchema;
156
+
157
+ const isLinkedDataType = !!url && !this._source.enum;
158
+
159
+ if (isLinkedDataType) {
160
+ validateId('url', url);
161
+
162
+ const source = this._source as PropertiesSchema;
163
+
164
+ source.type = {
165
+ type: 'string',
166
+ default: id,
167
+ required: true,
168
+ };
169
+
170
+ if (source.id) {
171
+ source.id = {
172
+ type: 'string',
173
+ format: 'url',
174
+ required: true,
175
+ };
176
+ }
177
+
178
+ const uri = (url.endsWith('/') || url.endsWith('#'))
179
+ ? `${url}${id}`
180
+ : `${url}#${id}`;
181
+
182
+ this._linkedDataType = {
183
+ '@id': uri,
184
+ '@context': getLinkedDataContext(source, url)
185
+ };
186
+ }
187
+
188
+ normalizeProperties(this._source);
189
+ }
190
+
191
+ /**
192
+ * Returns the unique identifier for this schema.
193
+ *
194
+ * **Intent:** Provide a way to reference and identify schemas in collections or validators.
195
+ *
196
+ * **Use Cases:**
197
+ * - Reference schemas in Validator instances
198
+ * - Track schema lineage when cloning/extending
199
+ * - Generate schema identifiers for JSON Schema output
200
+ *
201
+ * @returns The schema ID, or 'UNDEFINED_SCHEMA_ID' if not specified during construction
202
+ *
203
+ * **Example:**
204
+ * ```typescript
205
+ * const schema = new Schema({ name: { type: 'string' } }, 'User');
206
+ * console.log(schema.id); // 'User'
207
+ * ```
208
+ */
209
+ get id() {
210
+ return this._id;
211
+ }
212
+
213
+ /**
214
+ * Returns the URL associated with this schema for JSON-LD linked data generation.
215
+ *
216
+ * **Intent:** Provide access to the base URL used for generating semantic web identifiers.
217
+ *
218
+ * **Use Cases:**
219
+ * - Check if a schema has linked data support
220
+ * - Access the base URL for constructing related URIs
221
+ * - Debug linked data type generation
222
+ *
223
+ * @returns The schema URL if provided during construction, undefined otherwise
224
+ *
225
+ * **Example:**
226
+ * ```typescript
227
+ * const schema = new Schema({ name: { type: 'string' } }, 'Person', 'https://schema.org/');
228
+ * console.log(schema.url); // 'https://schema.org/'
229
+ * ```
230
+ */
231
+ get url() {
232
+ return this._url;
233
+ }
234
+
235
+ /**
236
+ * Returns a deep clone of the schema's source properties or enum definition.
237
+ *
238
+ * **Intent:** Provide immutable access to schema definitions to prevent accidental mutations.
239
+ *
240
+ * **Use Cases:**
241
+ * - Inspect schema structure without modifying the original
242
+ * - Clone schemas manually for custom transformations
243
+ * - Debug schema definitions
244
+ * - Pass schema definitions to other functions safely
245
+ *
246
+ * @returns A deep copy of the schema source (PropertiesSchema or EnumSchema)
247
+ *
248
+ * **Example:**
249
+ * ```typescript
250
+ * const schema = new Schema({ name: { type: 'string', required: true } }, 'User');
251
+ * const source = schema.source;
252
+ * // source is a clone, modifying it won't affect the original schema
253
+ * ```
254
+ */
255
+ get source() {
256
+ return cloneDeep(this._source);
257
+ }
258
+
259
+ /**
260
+ * Checks if this schema is an enum schema (defines a set of allowed values).
261
+ *
262
+ * **Intent:** Enable type-safe branching logic based on schema type.
263
+ *
264
+ * **Use Cases:**
265
+ * - Conditionally apply methods that only work on property schemas
266
+ * - Validate schema type before operations
267
+ * - Implement different serialization logic for enums vs objects
268
+ *
269
+ * @returns true if the schema is an enum schema, false if it's a properties schema
270
+ *
271
+ * **Example:**
272
+ * ```typescript
273
+ * const enumSchema = new Schema({ enum: ['A', 'B', 'C'] }, 'Letters');
274
+ * const propSchema = new Schema({ name: { type: 'string' } }, 'Person');
275
+ *
276
+ * console.log(enumSchema.isEnum); // true
277
+ * console.log(propSchema.isEnum); // false
278
+ * ```
279
+ */
280
+ get isEnum() {
281
+ return !!this._source.enum;
282
+ }
283
+
284
+ /**
285
+ * Returns a normalized JSON Schema representation of this schema.
286
+ *
287
+ * **Intent:** Convert the internal schema representation to standard JSON Schema format
288
+ * with normalized required arrays and proper structure for validation libraries.
289
+ *
290
+ * **Use Cases:**
291
+ * - Export schemas for use with JSON Schema validators (e.g., z-schema)
292
+ * - Generate API documentation from schemas
293
+ * - Serialize schemas to JSON for storage or transmission
294
+ * - Integrate with tools that expect standard JSON Schema format
295
+ *
296
+ * @returns A JsonSchema object (ObjectSchema for property schemas, EnumSchema for enum schemas)
297
+ *
298
+ * **Example - Property Schema:**
299
+ * ```typescript
300
+ * const schema = new Schema({
301
+ * name: { type: 'string', required: true },
302
+ * age: { type: 'number' }
303
+ * }, 'Person');
304
+ *
305
+ * const jsonSchema = schema.jsonSchema;
306
+ * // {
307
+ * // id: 'Person',
308
+ * // type: 'object',
309
+ * // properties: { name: {...}, age: {...} },
310
+ * // required: ['name']
311
+ * // }
312
+ * ```
313
+ *
314
+ * **Example - Enum Schema:**
315
+ * ```typescript
316
+ * const enumSchema = new Schema({ enum: ['S', 'M', 'L'], type: 'string' }, 'Size');
317
+ * const jsonSchema = enumSchema.jsonSchema;
318
+ * // { id: 'Size', enum: ['S', 'M', 'L'], type: 'string' }
319
+ * ```
320
+ */
321
+ get jsonSchema(): JsonSchema {
322
+ if (this.isEnum) {
323
+ return {
324
+ id: this._id,
325
+ ...this.source
326
+ } as EnumSchema;
327
+ }
328
+
329
+ const jsonSchema = {
330
+ id: this._id,
331
+ type: 'object',
332
+ properties: this.source
333
+ } as ObjectSchema;
334
+
335
+ normalizeRequired(jsonSchema);
336
+
337
+ return jsonSchema;
338
+ }
339
+
340
+ /**
341
+ * Returns the JSON-LD linked data type if a URL was provided during construction.
342
+ *
343
+ * **Intent:** Provide semantic web identifiers and context for schemas, enabling
344
+ * integration with Linked Data and Verifiable Credentials standards.
345
+ *
346
+ * **Use Cases:**
347
+ * - Generate Verifiable Credentials with proper semantic context
348
+ * - Create JSON-LD documents with schema.org or custom vocabularies
349
+ * - Enable semantic interoperability between systems
350
+ * - Support decentralized identity and credential systems
351
+ *
352
+ * @returns LinkedDataType object with @id and @context, or undefined if no URL was provided
353
+ *
354
+ * **Example:**
355
+ * ```typescript
356
+ * const schema = new Schema(
357
+ * { name: { type: 'string' }, email: { type: 'string', format: 'email' } },
358
+ * 'Person',
359
+ * 'https://schema.org/'
360
+ * );
361
+ *
362
+ * const linkedData = schema.linkedDataType;
363
+ * // {
364
+ * // '@id': 'https://schema.org/Person',
365
+ * // '@context': { ... } // Generated context mapping types to schema.org
366
+ * // }
367
+ * ```
368
+ *
369
+ * **Note:** Linked data types are only generated for property schemas, not enum schemas.
370
+ */
371
+ get linkedDataType() {
372
+ return this._linkedDataType;
373
+ }
374
+
375
+ /**
376
+ * Creates a complete clone of the schema with a new identifier.
377
+ *
378
+ * **Intent:** Duplicate a schema while maintaining all properties and structure,
379
+ * useful for creating variations or versioning schemas.
380
+ *
381
+ * **Use Cases:**
382
+ * - Create schema versions (e.g., 'UserV1', 'UserV2')
383
+ * - Duplicate schemas for different contexts
384
+ * - Create base schemas that can be independently extended
385
+ * - Maintain schema history or branching
386
+ *
387
+ * @param id - The new unique identifier for the cloned schema
388
+ * @returns A new Schema instance with identical structure but different ID
389
+ *
390
+ * **Example:**
391
+ * ```typescript
392
+ * const userSchema = new Schema({ name: { type: 'string' } }, 'User');
393
+ * const userV2Schema = userSchema.clone('UserV2');
394
+ * // Both schemas have identical properties but different IDs
395
+ * ```
396
+ */
397
+ clone(id: string) {
398
+ return new Schema(this.source, id);
399
+ }
400
+
401
+ /**
402
+ * Creates a schema clone without required constraints and default values.
403
+ *
404
+ * **Intent:** Generate update/patch schemas from create schemas by removing
405
+ * validation constraints that make sense for creation but not for updates.
406
+ *
407
+ * **Use Cases:**
408
+ * - Create update schemas where all fields are optional
409
+ * - Generate PATCH endpoint schemas from POST endpoint schemas
410
+ * - Allow partial updates without requiring all original fields
411
+ * - Create flexible input schemas for editing operations
412
+ *
413
+ * @param id - The new unique identifier for the pure schema
414
+ * @returns A new Schema instance with all required flags and defaults removed
415
+ * @throws Error if called on an enum schema
416
+ *
417
+ * **Example:**
418
+ * ```typescript
419
+ * const createSchema = new Schema({
420
+ * name: { type: 'string', required: true },
421
+ * email: { type: 'string', required: true, default: 'user@example.com' }
422
+ * }, 'CreateUser');
423
+ *
424
+ * const updateSchema = createSchema.pure('UpdateUser');
425
+ * // updateSchema has no required fields and no defaults
426
+ * // All fields are optional for updates
427
+ * ```
428
+ */
429
+ pure(id: string) {
430
+ if (this.isEnum) {
431
+ throw new Error('The "pure" method is not supported for enum schemas.');
432
+ }
433
+
434
+ const { properties: source } = removeRequiredAndDefault({
435
+ type: 'object',
436
+ properties: this.source as PropertiesSchema
437
+ });
438
+
439
+ return new Schema(source, id);
440
+ }
441
+
442
+ /**
443
+ * Creates a schema clone containing only the specified properties.
444
+ *
445
+ * **Intent:** Create focused schemas that expose only a subset of properties,
446
+ * useful for different API views or security contexts.
447
+ *
448
+ * **Use Cases:**
449
+ * - Create public-facing schemas that hide sensitive fields
450
+ * - Generate response schemas with only necessary fields
451
+ * - Create view-specific schemas (e.g., 'UserSummary', 'UserDetail')
452
+ * - Implement field-level access control in schemas
453
+ * - Create lightweight schemas for list views
454
+ *
455
+ * @param propertyNames - Array of property names to include in the new schema
456
+ * @param id - The new unique identifier for the filtered schema
457
+ * @returns A new Schema instance containing only the specified properties
458
+ * @throws Error if called on an enum schema
459
+ *
460
+ * **Example:**
461
+ * ```typescript
462
+ * const fullSchema = new Schema({
463
+ * name: { type: 'string' },
464
+ * email: { type: 'string' },
465
+ * password: { type: 'string' },
466
+ * ssn: { type: 'string' }
467
+ * }, 'User');
468
+ *
469
+ * const publicSchema = fullSchema.only(['name', 'email'], 'PublicUser');
470
+ * // publicSchema only contains name and email, hiding sensitive fields
471
+ * ```
472
+ */
473
+ only(propertyNames: string[], id: string) {
474
+ if (this.isEnum) {
475
+ throw new Error('The "only" method is not supported for enum schemas.');
476
+ }
477
+
478
+ const source = pick(this.source, propertyNames);
479
+ return new Schema(source as PropertiesSchema, id);
480
+ }
481
+
482
+ /**
483
+ * Creates a schema clone extended with additional properties.
484
+ *
485
+ * **Intent:** Build complex schemas incrementally by composing base schemas
486
+ * with additional fields, enabling schema inheritance and composition patterns.
487
+ *
488
+ * **Use Cases:**
489
+ * - Extend base schemas with domain-specific fields
490
+ * - Create schema hierarchies (e.g., BaseEntity -> User -> AdminUser)
491
+ * - Add computed or derived fields to existing schemas
492
+ * - Compose schemas from multiple sources
493
+ * - Build versioned schemas that add new fields
494
+ *
495
+ * @param properties - Additional properties to merge into the schema
496
+ * @param id - The new unique identifier for the extended schema
497
+ * @returns A new Schema instance with merged properties (new properties override existing ones)
498
+ * @throws Error if called on an enum schema
499
+ *
500
+ * **Example:**
501
+ * ```typescript
502
+ * const baseSchema = new Schema({
503
+ * id: { type: 'string', required: true },
504
+ * createdAt: { type: 'string', format: 'date-time', required: true }
505
+ * }, 'BaseEntity');
506
+ *
507
+ * const userSchema = baseSchema.extend({
508
+ * name: { type: 'string', required: true },
509
+ * email: { type: 'string', format: 'email', required: true }
510
+ * }, 'User');
511
+ *
512
+ * // userSchema contains id, createdAt, name, and email
513
+ * ```
514
+ */
515
+ extend(properties: PropertiesSchema, id: string) {
516
+ if (this.isEnum) {
517
+ throw new Error('The "extend" method is not supported for enum schemas.');
518
+ }
519
+
520
+ return new Schema({ ...this.source, ...properties }, id);
521
+ }
522
+
523
+ /**
524
+ * Creates a new schema that wraps the current schema as a nested property.
525
+ *
526
+ * **Intent:** Transform a flat schema into a nested structure, useful for
527
+ * API response formatting or when data needs to be wrapped in a container object.
528
+ *
529
+ * **Use Cases:**
530
+ * - Wrap schemas for API responses (e.g., { data: { ...schema } })
531
+ * - Create nested data structures from flat schemas
532
+ * - Format schemas for specific API conventions
533
+ * - Generate wrapper schemas for pagination or metadata containers
534
+ * - Transform schemas for different API versions or formats
535
+ *
536
+ * @param propertyName - The name of the property that will contain the wrapped schema
537
+ * @param attributes - Optional attributes for the wrapper property (default: { required: true })
538
+ * @param id - The new unique identifier for the wrapped schema
539
+ * @returns A new Schema instance where the original schema is nested under the specified property
540
+ * @throws Error if called on an enum schema
541
+ *
542
+ * **Example:**
543
+ * ```typescript
544
+ * const userSchema = new Schema({
545
+ * name: { type: 'string', required: true },
546
+ * email: { type: 'string', required: true }
547
+ * }, 'User');
548
+ *
549
+ * const wrappedSchema = userSchema.wrap('data', { required: true }, 'UserResponse');
550
+ * // Resulting schema structure:
551
+ * // {
552
+ * // data: {
553
+ * // type: 'object',
554
+ * // properties: { name: {...}, email: {...} },
555
+ * // required: true
556
+ * // }
557
+ * // }
558
+ * ```
559
+ *
560
+ * **Example - With Default Value:**
561
+ * ```typescript
562
+ * const wrappedSchema = userSchema.wrap('data', { default: '{}' }, 'OptionalUserResponse');
563
+ * // The 'data' property has a default value and is not required
564
+ * ```
565
+ */
566
+ wrap(propertyName: string, attributes: { default?: string; required?: boolean; }, id: string) {
567
+ if (this.isEnum) {
568
+ throw new Error('The "wrap" method is not supported for enum schemas.');
569
+ }
570
+
571
+ const source = {
572
+ [propertyName]: {
573
+ type: 'object',
574
+ properties: this.source,
575
+ ...(attributes || { required: true })
576
+ }
577
+ } as PropertiesSchema;
578
+
579
+ return new Schema(source, id);
580
+ }
581
+ }
582
+
583
+ export default Schema;
@@ -0,0 +1,90 @@
1
+ import type { SchemaErrorDetail } from 'z-schema';
2
+
3
+ import { TargetObject } from './helpers/JsonSchema';
4
+
5
+ /**
6
+ * Normalized validation error thrown when object validation fails against a schema.
7
+ *
8
+ * This error is thrown by the Validator when an object does not conform to its schema.
9
+ * It extends the standard Error class and provides structured access to validation
10
+ * failure details, including the schema ID, the invalid object, and normalized error
11
+ * information for each validation failure.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * try {
16
+ * validator.validate(userData, 'UserSchema');
17
+ * } catch (error) {
18
+ * if (error instanceof ValidationError) {
19
+ * const errorDetails = error.toJSON();
20
+ * console.error(errorDetails.schemaId); // 'UserSchema'
21
+ * console.error(errorDetails.validationErrors); // Array of validation failures
22
+ * }
23
+ * }
24
+ * ```
25
+ */
26
+ class ValidationError extends Error {
27
+ private _object: TargetObject;
28
+ private _schemaId: string;
29
+ private _validationErrors: {
30
+ path: string;
31
+ code: string;
32
+ params: string[];
33
+ message: string;
34
+ }[];
35
+
36
+ /**
37
+ * Creates a validation error instance.
38
+ *
39
+ * @param schemaId - The identifier of the schema that failed validation
40
+ * @param invalidObject - The object that failed validation (may be partially processed)
41
+ * @param validationErrors - Array of validation error details from z-schema, which will be
42
+ * normalized to extract only path, code, params, and message
43
+ */
44
+ constructor(schemaId: string, invalidObject: TargetObject, validationErrors: SchemaErrorDetail[]) {
45
+ super(`"${schemaId}" validation failed`);
46
+
47
+ this._object = invalidObject;
48
+
49
+ this._schemaId = schemaId;
50
+
51
+ this._validationErrors = validationErrors
52
+ .map(error => ({
53
+ path: error.path,
54
+ code: error.code,
55
+ params: error.params,
56
+ message: error.message,
57
+ }));
58
+ }
59
+
60
+ /**
61
+ * Returns a JSON serializable representation of the validation error.
62
+ *
63
+ * This method is useful for:
64
+ * - API error responses (can be directly serialized and sent to clients)
65
+ * - Logging validation failures in a structured format
66
+ * - Error reporting and debugging
67
+ *
68
+ * @returns An object containing:
69
+ * - `code`: The error class name ('ValidationError')
70
+ * - `object`: The invalid object that failed validation
71
+ * - `message`: The error message (e.g., '"SchemaId" validation failed')
72
+ * - `schemaId`: The identifier of the schema that failed validation
73
+ * - `validationErrors`: Array of normalized validation errors, each containing:
74
+ * - `path`: JSON path to the invalid field (e.g., '#/user/email')
75
+ * - `code`: Error code from z-schema (e.g., 'INVALID_TYPE', 'REQUIRED')
76
+ * - `params`: Array of error-specific parameters
77
+ * - `message`: Human-readable error message
78
+ */
79
+ toJSON() {
80
+ return {
81
+ code: this.constructor.name,
82
+ object: this._object,
83
+ message: this.message,
84
+ schemaId: this._schemaId,
85
+ validationErrors: this._validationErrors
86
+ };
87
+ }
88
+ }
89
+
90
+ export default ValidationError;