@twin.org/data-core 0.0.2-next.4 → 0.0.3-next.10

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 (38) hide show
  1. package/dist/es/factories/dataTypeHandlerFactory.js +9 -0
  2. package/dist/es/factories/dataTypeHandlerFactory.js.map +1 -0
  3. package/dist/es/factories/identifierHandlerFactory.js +19 -0
  4. package/dist/es/factories/identifierHandlerFactory.js.map +1 -0
  5. package/dist/es/index.js +13 -0
  6. package/dist/es/index.js.map +1 -0
  7. package/dist/es/models/IDataTypeHandler.js +2 -0
  8. package/dist/es/models/IDataTypeHandler.js.map +1 -0
  9. package/dist/es/models/IIdentifierHandler.js +2 -0
  10. package/dist/es/models/IIdentifierHandler.js.map +1 -0
  11. package/dist/es/models/IJsonSchema.js +2 -0
  12. package/dist/es/models/IJsonSchema.js.map +1 -0
  13. package/dist/es/models/ISchemaValidationError.js +2 -0
  14. package/dist/es/models/ISchemaValidationError.js.map +1 -0
  15. package/dist/es/models/ISchemaValidationResult.js +2 -0
  16. package/dist/es/models/ISchemaValidationResult.js.map +1 -0
  17. package/dist/es/models/validationMode.js +25 -0
  18. package/dist/es/models/validationMode.js.map +1 -0
  19. package/dist/es/utils/dataTypeHelper.js +115 -0
  20. package/dist/es/utils/dataTypeHelper.js.map +1 -0
  21. package/dist/es/utils/jsonSchemaHelper.js +161 -0
  22. package/dist/es/utils/jsonSchemaHelper.js.map +1 -0
  23. package/dist/types/factories/dataTypeHandlerFactory.d.ts +1 -1
  24. package/dist/types/factories/identifierHandlerFactory.d.ts +1 -1
  25. package/dist/types/index.d.ts +10 -10
  26. package/dist/types/models/IDataTypeHandler.d.ts +7 -3
  27. package/dist/types/models/IJsonSchema.d.ts +2 -2
  28. package/dist/types/models/ISchemaValidationResult.d.ts +1 -1
  29. package/dist/types/utils/dataTypeHelper.d.ts +26 -1
  30. package/dist/types/utils/jsonSchemaHelper.d.ts +7 -3
  31. package/docs/changelog.md +87 -0
  32. package/docs/reference/classes/DataTypeHelper.md +93 -1
  33. package/docs/reference/classes/JsonSchemaHelper.md +12 -4
  34. package/docs/reference/interfaces/IDataTypeHandler.md +13 -5
  35. package/docs/reference/type-aliases/IJsonSchema.md +1 -1
  36. package/package.json +5 -7
  37. package/dist/cjs/index.cjs +0 -282
  38. package/dist/esm/index.mjs +0 -276
@@ -0,0 +1,9 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { Factory } from "@twin.org/core";
4
+ /**
5
+ * Factory for creating handlers for data types.
6
+ */
7
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8
+ export const DataTypeHandlerFactory = Factory.createFactory("data-type");
9
+ //# sourceMappingURL=dataTypeHandlerFactory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataTypeHandlerFactory.js","sourceRoot":"","sources":["../../../src/factories/dataTypeHandlerFactory.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAGzC;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,sBAAsB,GAAG,OAAO,CAAC,aAAa,CAAmB,WAAW,CAAC,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { Factory } from \"@twin.org/core\";\nimport type { IDataTypeHandler } from \"../models/IDataTypeHandler.js\";\n\n/**\n * Factory for creating handlers for data types.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const DataTypeHandlerFactory = Factory.createFactory<IDataTypeHandler>(\"data-type\");\n"]}
@@ -0,0 +1,19 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { Factory, Urn } from "@twin.org/core";
4
+ /**
5
+ * Factory for creating handlers for identifiers.
6
+ */
7
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8
+ export const IdentifierHandlerFactory = Factory.createFactory("namespace", false, (names, uri) => {
9
+ Urn.guard("IdentifierHandlerFactory", "uri", uri);
10
+ const urn = Urn.fromValidString(uri);
11
+ const urnParts = urn.parts();
12
+ for (let i = urnParts.length - 1; i >= 0; i--) {
13
+ const wholeNamespace = urnParts.slice(i).join(":");
14
+ if (names.includes(wholeNamespace)) {
15
+ return wholeNamespace;
16
+ }
17
+ }
18
+ });
19
+ //# sourceMappingURL=identifierHandlerFactory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifierHandlerFactory.js","sourceRoot":"","sources":["../../../src/factories/identifierHandlerFactory.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAI9C;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,wBAAwB,GAAG,OAAO,CAAC,aAAa,CAC5D,WAAW,EACX,KAAK,EACL,CAAC,KAAe,EAAE,GAAW,EAAE,EAAE;IAChC,GAAG,CAAC,KAAK,oCAAgD,GAAG,CAAC,CAAC;IAE9D,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IACrC,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC;IAE7B,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC/C,MAAM,cAAc,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACnD,IAAI,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;YACpC,OAAO,cAAc,CAAC;QACvB,CAAC;IACF,CAAC;AACF,CAAC,CACD,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { Factory, Urn } from \"@twin.org/core\";\nimport { nameof } from \"@twin.org/nameof\";\nimport type { IIdentifierHandler } from \"../models/IIdentifierHandler.js\";\n\n/**\n * Factory for creating handlers for identifiers.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const IdentifierHandlerFactory = Factory.createFactory<IIdentifierHandler>(\n\t\"namespace\",\n\tfalse,\n\t(names: string[], uri: string) => {\n\t\tUrn.guard(nameof(IdentifierHandlerFactory), nameof(uri), uri);\n\n\t\tconst urn = Urn.fromValidString(uri);\n\t\tconst urnParts = urn.parts();\n\n\t\tfor (let i = urnParts.length - 1; i >= 0; i--) {\n\t\t\tconst wholeNamespace = urnParts.slice(i).join(\":\");\n\t\t\tif (names.includes(wholeNamespace)) {\n\t\t\t\treturn wholeNamespace;\n\t\t\t}\n\t\t}\n\t}\n);\n"]}
@@ -0,0 +1,13 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export * from "./factories/dataTypeHandlerFactory.js";
4
+ export * from "./factories/identifierHandlerFactory.js";
5
+ export * from "./models/IDataTypeHandler.js";
6
+ export * from "./models/IIdentifierHandler.js";
7
+ export * from "./models/IJsonSchema.js";
8
+ export * from "./models/ISchemaValidationError.js";
9
+ export * from "./models/ISchemaValidationResult.js";
10
+ export * from "./models/validationMode.js";
11
+ export * from "./utils/dataTypeHelper.js";
12
+ export * from "./utils/jsonSchemaHelper.js";
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,uCAAuC,CAAC;AACtD,cAAc,yCAAyC,CAAC;AACxD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,oCAAoC,CAAC;AACnD,cAAc,qCAAqC,CAAC;AACpD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,6BAA6B,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./factories/dataTypeHandlerFactory.js\";\nexport * from \"./factories/identifierHandlerFactory.js\";\nexport * from \"./models/IDataTypeHandler.js\";\nexport * from \"./models/IIdentifierHandler.js\";\nexport * from \"./models/IJsonSchema.js\";\nexport * from \"./models/ISchemaValidationError.js\";\nexport * from \"./models/ISchemaValidationResult.js\";\nexport * from \"./models/validationMode.js\";\nexport * from \"./utils/dataTypeHelper.js\";\nexport * from \"./utils/jsonSchemaHelper.js\";\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IDataTypeHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IDataTypeHandler.js","sourceRoot":"","sources":["../../../src/models/IDataTypeHandler.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IValidationFailure } from \"@twin.org/core\";\nimport type { IJsonSchema } from \"./IJsonSchema.js\";\n\n/**\n * Interface describing a type which can handle a specific data type.\n */\nexport interface IDataTypeHandler {\n\t/**\n\t * The namespace for the type.\n\t */\n\tnamespace: string;\n\n\t/**\n\t * The type for the item.\n\t */\n\ttype: string;\n\n\t/**\n\t * The JSON LD context for the type.\n\t */\n\tjsonLdContext?: string;\n\n\t/**\n\t * The default value for the item to use when constructing a new object.\n\t */\n\tdefaultValue?: unknown;\n\n\t/**\n\t * Get the JSON schema for the data type.\n\t * @returns The JSON schema for the data type.\n\t */\n\tjsonSchema?(): Promise<IJsonSchema | undefined>;\n\n\t/**\n\t * A method for validating the data type.\n\t * @param propertyName The name of the property being validated.\n\t * @param value The value to validate.\n\t * @param failures List of failures to add to.\n\t * @param container The object which contains this one.\n\t * @returns True if the item is valid.\n\t */\n\tvalidate?(\n\t\tpropertyName: string,\n\t\tvalue: unknown,\n\t\tfailures: IValidationFailure[],\n\t\tcontainer?: unknown\n\t): Promise<boolean>;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IIdentifierHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IIdentifierHandler.js","sourceRoot":"","sources":["../../../src/models/IIdentifierHandler.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IValidationFailure } from \"@twin.org/core\";\n\n/**\n * Interface describing a type which can handle a specific urn namespace.\n */\nexport interface IIdentifierHandler {\n\t/**\n\t * The namespace for the identifier.\n\t */\n\tnamespace: string;\n\n\t/**\n\t * A method for validating the identifier.\n\t * @param propertyName The name of the property being validated.\n\t * @param value The value to validate.\n\t * @param failures List of failures to add to.\n\t * @returns True if the item is valid.\n\t */\n\tvalidate(propertyName: string, value: unknown, failures: IValidationFailure[]): boolean;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IJsonSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IJsonSchema.js","sourceRoot":"","sources":["../../../src/models/IJsonSchema.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type Ajv from \"ajv/dist/2020.js\";\n\n/**\n * Default schema type.\n */\nexport type IJsonSchema = Ajv.SchemaObject;\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISchemaValidationError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ISchemaValidationError.js","sourceRoot":"","sources":["../../../src/models/ISchemaValidationError.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ErrorObject } from \"ajv\";\n\n/**\n * Schema validation error.\n */\nexport type ISchemaValidationError = ErrorObject[];\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISchemaValidationResult.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ISchemaValidationResult.js","sourceRoot":"","sources":["../../../src/models/ISchemaValidationResult.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ISchemaValidationError } from \"./ISchemaValidationError.js\";\n\n/**\n * Validation result.\n */\nexport interface ISchemaValidationResult {\n\t/**\n\t * The result.\n\t */\n\tresult: boolean;\n\n\t/**\n\t * The error.\n\t */\n\terror?: ISchemaValidationError;\n}\n"]}
@@ -0,0 +1,25 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ /**
4
+ * Validation modes for validating data types.
5
+ */
6
+ // eslint-disable-next-line @typescript-eslint/naming-convention
7
+ export const ValidationMode = {
8
+ /**
9
+ * Use the validation method of the data type.
10
+ */
11
+ Validate: "validate",
12
+ /**
13
+ * Use the JSON Schema methods of the data type.
14
+ */
15
+ JsonSchema: "json-schema",
16
+ /**
17
+ * Use either validation mode.
18
+ */
19
+ Either: "either",
20
+ /**
21
+ * Use both validation modes.
22
+ */
23
+ Both: "both"
24
+ };
25
+ //# sourceMappingURL=validationMode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validationMode.js","sourceRoot":"","sources":["../../../src/models/validationMode.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AAEvC;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B;;OAEG;IACH,QAAQ,EAAE,UAAU;IAEpB;;OAEG;IACH,UAAU,EAAE,aAAa;IAEzB;;OAEG;IACH,MAAM,EAAE,QAAQ;IAEhB;;OAEG;IACH,IAAI,EAAE,MAAM;CACH,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Validation modes for validating data types.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const ValidationMode = {\n\t/**\n\t * Use the validation method of the data type.\n\t */\n\tValidate: \"validate\",\n\n\t/**\n\t * Use the JSON Schema methods of the data type.\n\t */\n\tJsonSchema: \"json-schema\",\n\n\t/**\n\t * Use either validation mode.\n\t */\n\tEither: \"either\",\n\n\t/**\n\t * Use both validation modes.\n\t */\n\tBoth: \"both\"\n} as const;\n\n/**\n * Validation modes for validating data types.\n */\nexport type ValidationMode = (typeof ValidationMode)[keyof typeof ValidationMode];\n"]}
@@ -0,0 +1,115 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { Is } from "@twin.org/core";
4
+ import { JsonSchemaHelper } from "./jsonSchemaHelper.js";
5
+ import { DataTypeHandlerFactory } from "../factories/dataTypeHandlerFactory.js";
6
+ import { ValidationMode } from "../models/validationMode.js";
7
+ /**
8
+ * Class to help with data types.
9
+ */
10
+ export class DataTypeHelper {
11
+ /**
12
+ * Register a data type.
13
+ * @param namespace The namespace for the type.
14
+ * @param type The type for the item.
15
+ * @param jsonLdContext The JSON LD context for the type.
16
+ * @param schema The JSON schema for the type.
17
+ */
18
+ static registerType(namespace, type, jsonLdContext, schema) {
19
+ DataTypeHandlerFactory.register(`${namespace}${type}`, () => ({
20
+ namespace,
21
+ jsonLdContext,
22
+ type,
23
+ jsonSchema: async () => schema
24
+ }));
25
+ }
26
+ /**
27
+ * Register a list of types.
28
+ * @param namespace The namespace for the types.
29
+ * @param jsonLdContext The JSON LD context for the types.
30
+ * @param typeDefinition The type definitions to register.
31
+ */
32
+ static registerTypes(namespace, jsonLdContext, typeDefinition) {
33
+ for (const typeDef of typeDefinition) {
34
+ DataTypeHelper.registerType(namespace, typeDef.type, jsonLdContext, typeDef.schema);
35
+ }
36
+ }
37
+ /**
38
+ * Get the JSON schema for a data type.
39
+ * @param dataType The data type to get the schema for.
40
+ * @returns The JSON schema for the data type or undefined if not found.
41
+ */
42
+ static async getSchemaForType(dataType) {
43
+ const handler = DataTypeHandlerFactory.getIfExists(dataType);
44
+ return handler?.jsonSchema ? handler.jsonSchema() : undefined;
45
+ }
46
+ /**
47
+ * Validate a data type.
48
+ * @param propertyName The name of the property being validated to use in error messages.
49
+ * @param dataType The data type to validate.
50
+ * @param data The data to validate.
51
+ * @param validationFailures The list of validation failures to add to.
52
+ * @param options Optional options for validation.
53
+ * @param options.failOnMissingType If true, will fail validation if the data type is missing, defaults to false.
54
+ * @param options.validationMode The validation mode to use, defaults to either.
55
+ * @returns True if the data was valid.
56
+ */
57
+ static async validate(propertyName, dataType, data, validationFailures, options) {
58
+ let isValid = true;
59
+ if (Is.stringValue(dataType)) {
60
+ const handler = DataTypeHandlerFactory.getIfExists(dataType);
61
+ if (handler) {
62
+ const validationMode = options?.validationMode ?? ValidationMode.Either;
63
+ // If we have a validate function use that as it is more specific
64
+ // and will produce better error messages
65
+ let hasValidated = false;
66
+ const validateMethod = handler.validate?.bind(handler);
67
+ if ((validationMode === ValidationMode.Validate ||
68
+ validationMode === ValidationMode.Both ||
69
+ validationMode === ValidationMode.Either) &&
70
+ Is.function(validateMethod)) {
71
+ isValid = await validateMethod(propertyName, data, validationFailures);
72
+ hasValidated = true;
73
+ }
74
+ const jsonSchemaMethod = handler.jsonSchema?.bind(handler);
75
+ if ((validationMode === ValidationMode.JsonSchema ||
76
+ (validationMode === ValidationMode.Either && !hasValidated) ||
77
+ validationMode === ValidationMode.Both) &&
78
+ Is.function(jsonSchemaMethod)) {
79
+ // Otherwise use the JSON schema if there is one
80
+ const schema = await jsonSchemaMethod();
81
+ if (Is.object(schema)) {
82
+ const validationResult = await JsonSchemaHelper.validate(schema, data);
83
+ if (Is.arrayValue(validationResult.error)) {
84
+ validationFailures.push({
85
+ property: propertyName,
86
+ reason: "validation.schema.failedValidation",
87
+ properties: {
88
+ value: data,
89
+ schemaErrors: validationResult.error,
90
+ message: validationResult.error.map(e => e.message).join("\n")
91
+ }
92
+ });
93
+ }
94
+ if (!validationResult.result) {
95
+ isValid = false;
96
+ }
97
+ }
98
+ }
99
+ }
100
+ else if (options?.failOnMissingType ?? false) {
101
+ // If we don't have a handler for a specific type and we are failing on missing type
102
+ validationFailures.push({
103
+ property: propertyName,
104
+ reason: "validation.schema.missingType",
105
+ properties: {
106
+ dataType
107
+ }
108
+ });
109
+ isValid = false;
110
+ }
111
+ }
112
+ return isValid;
113
+ }
114
+ }
115
+ //# sourceMappingURL=dataTypeHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataTypeHelper.js","sourceRoot":"","sources":["../../../src/utils/dataTypeHelper.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,EAAE,EAA2B,MAAM,gBAAgB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D;;GAEG;AACH,MAAM,OAAO,cAAc;IAC1B;;;;;;OAMG;IACI,MAAM,CAAC,YAAY,CACzB,SAAiB,EACjB,IAAY,EACZ,aAAiC,EACjC,MAA0C;QAE1C,sBAAsB,CAAC,QAAQ,CAAC,GAAG,SAAS,GAAG,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;YAC7D,SAAS;YACT,aAAa;YACb,IAAI;YACJ,UAAU,EAAE,KAAK,IAAI,EAAE,CAAC,MAAM;SAC9B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,aAAa,CAC1B,SAAiB,EACjB,aAAiC,EACjC,cAGG;QAEH,KAAK,MAAM,OAAO,IAAI,cAAc,EAAE,CAAC;YACtC,cAAc,CAAC,YAAY,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,EAAE,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,C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YACjB,CAAC;QACF,CAAC;QAED,OAAO,OAAO,CAAC;IAChB,CAAC;CACD","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { Is, type IValidationFailure } from \"@twin.org/core\";\nimport { JsonSchemaHelper } from \"./jsonSchemaHelper.js\";\nimport { DataTypeHandlerFactory } from \"../factories/dataTypeHandlerFactory.js\";\nimport type { IJsonSchema } from \"../models/IJsonSchema.js\";\nimport { ValidationMode } from \"../models/validationMode.js\";\n\n/**\n * Class to help with data types.\n */\nexport class DataTypeHelper {\n\t/**\n\t * Register a data type.\n\t * @param namespace The namespace for the type.\n\t * @param type The type for the item.\n\t * @param jsonLdContext The JSON LD context for the type.\n\t * @param schema The JSON schema for the type.\n\t */\n\tpublic static registerType(\n\t\tnamespace: string,\n\t\ttype: string,\n\t\tjsonLdContext: string | undefined,\n\t\tschema: IJsonSchema | Promise<IJsonSchema>\n\t): void {\n\t\tDataTypeHandlerFactory.register(`${namespace}${type}`, () => ({\n\t\t\tnamespace,\n\t\t\tjsonLdContext,\n\t\t\ttype,\n\t\t\tjsonSchema: async () => schema\n\t\t}));\n\t}\n\n\t/**\n\t * Register a list of types.\n\t * @param namespace The namespace for the types.\n\t * @param jsonLdContext The JSON LD context for the types.\n\t * @param typeDefinition The type definitions to register.\n\t */\n\tpublic static registerTypes(\n\t\tnamespace: string,\n\t\tjsonLdContext: string | undefined,\n\t\ttypeDefinition: {\n\t\t\ttype: string;\n\t\t\tschema: IJsonSchema | Promise<IJsonSchema>;\n\t\t}[]\n\t): void {\n\t\tfor (const typeDef of typeDefinition) {\n\t\t\tDataTypeHelper.registerType(namespace, typeDef.type, jsonLdContext, typeDef.schema);\n\t\t}\n\t}\n\n\t/**\n\t * Get the JSON schema for a data type.\n\t * @param dataType The data type to get the schema for.\n\t * @returns The JSON schema for the data type or undefined if not found.\n\t */\n\tpublic static async getSchemaForType(dataType: string): Promise<IJsonSchema | undefined> {\n\t\tconst handler = DataTypeHandlerFactory.getIfExists(dataType);\n\t\treturn handler?.jsonSchema ? handler.jsonSchema() : undefined;\n\t}\n\n\t/**\n\t * Validate a data type.\n\t * @param propertyName The name of the property being validated to use in error messages.\n\t * @param dataType The data type to validate.\n\t * @param data The data to validate.\n\t * @param validationFailures The list of validation failures to add to.\n\t * @param options Optional options for validation.\n\t * @param options.failOnMissingType If true, will fail validation if the data type is missing, defaults to false.\n\t * @param options.validationMode The validation mode to use, defaults to either.\n\t * @returns True if the data was valid.\n\t */\n\tpublic static async validate(\n\t\tpropertyName: string,\n\t\tdataType: string | undefined,\n\t\tdata: unknown,\n\t\tvalidationFailures: IValidationFailure[],\n\t\toptions?: {\n\t\t\tvalidationMode?: ValidationMode;\n\t\t\tfailOnMissingType?: boolean;\n\t\t}\n\t): Promise<boolean> {\n\t\tlet isValid = true;\n\n\t\tif (Is.stringValue(dataType)) {\n\t\t\tconst handler = DataTypeHandlerFactory.getIfExists(dataType);\n\n\t\t\tif (handler) {\n\t\t\t\tconst validationMode = options?.validationMode ?? ValidationMode.Either;\n\n\t\t\t\t// If we have a validate function use that as it is more specific\n\t\t\t\t// and will produce better error messages\n\t\t\t\tlet hasValidated = false;\n\t\t\t\tconst validateMethod = handler.validate?.bind(handler);\n\t\t\t\tif (\n\t\t\t\t\t(validationMode === ValidationMode.Validate ||\n\t\t\t\t\t\tvalidationMode === ValidationMode.Both ||\n\t\t\t\t\t\tvalidationMode === ValidationMode.Either) &&\n\t\t\t\t\tIs.function(validateMethod)\n\t\t\t\t) {\n\t\t\t\t\tisValid = await validateMethod(propertyName, data, validationFailures);\n\t\t\t\t\thasValidated = true;\n\t\t\t\t}\n\n\t\t\t\tconst jsonSchemaMethod = handler.jsonSchema?.bind(handler);\n\t\t\t\tif (\n\t\t\t\t\t(validationMode === ValidationMode.JsonSchema ||\n\t\t\t\t\t\t(validationMode === ValidationMode.Either && !hasValidated) ||\n\t\t\t\t\t\tvalidationMode === ValidationMode.Both) &&\n\t\t\t\t\tIs.function(jsonSchemaMethod)\n\t\t\t\t) {\n\t\t\t\t\t// Otherwise use the JSON schema if there is one\n\t\t\t\t\tconst schema = await jsonSchemaMethod();\n\n\t\t\t\t\tif (Is.object<IJsonSchema>(schema)) {\n\t\t\t\t\t\tconst validationResult = await JsonSchemaHelper.validate(schema, data);\n\t\t\t\t\t\tif (Is.arrayValue(validationResult.error)) {\n\t\t\t\t\t\t\tvalidationFailures.push({\n\t\t\t\t\t\t\t\tproperty: propertyName,\n\t\t\t\t\t\t\t\treason: \"validation.schema.failedValidation\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tvalue: data,\n\t\t\t\t\t\t\t\t\tschemaErrors: validationResult.error,\n\t\t\t\t\t\t\t\t\tmessage: validationResult.error.map(e => e.message).join(\"\\n\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!validationResult.result) {\n\t\t\t\t\t\t\tisValid = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (options?.failOnMissingType ?? false) {\n\t\t\t\t// If we don't have a handler for a specific type and we are failing on missing type\n\t\t\t\tvalidationFailures.push({\n\t\t\t\t\tproperty: propertyName,\n\t\t\t\t\treason: \"validation.schema.missingType\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tdataType\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tisValid = false;\n\t\t\t}\n\t\t}\n\n\t\treturn isValid;\n\t}\n}\n"]}
@@ -0,0 +1,161 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { Is, StringHelper } from "@twin.org/core";
4
+ import { FetchHelper, HttpMethod } from "@twin.org/web";
5
+ import Ajv2019 from "ajv/dist/2019.js";
6
+ import Ajv2020 from "ajv/dist/2020.js";
7
+ import formatsPlugin from "ajv-formats";
8
+ import { DataTypeHandlerFactory } from "../factories/dataTypeHandlerFactory.js";
9
+ /**
10
+ * A helper for JSON schemas.
11
+ */
12
+ export class JsonSchemaHelper {
13
+ /**
14
+ * The schema version 2020 (default).
15
+ */
16
+ static SCHEMA_VERSION = "https://json-schema.org/draft/2020-12/schema";
17
+ /**
18
+ * The schema version 2019.
19
+ */
20
+ static SCHEMA_VERSION_2019 = "https://json-schema.org/draft/2019-09/schema";
21
+ /**
22
+ * The class name.
23
+ * @internal
24
+ */
25
+ static CLASS_NAME = "JsonSchemaHelper";
26
+ /**
27
+ * Validates data against the schema.
28
+ * @param schema The schema to validate the data with.
29
+ * @param data The data to be validated.
30
+ * @param additionalTypes Additional types to add for reference, not already in DataTypeHandlerFactory.
31
+ * @returns Result containing errors if there are any.
32
+ */
33
+ static async validate(schema, data, additionalTypes) {
34
+ const params = {
35
+ allowUnionTypes: true,
36
+ // Disable strict tuples as it causes issues with the schema validation when
37
+ // you have an array with fixed elements e.g. myType: [string, ...string[]]
38
+ // https://github.com/ajv-validator/ajv/issues/1417
39
+ strictTuples: false,
40
+ loadSchema: async (uri) => {
41
+ const subTypeHandler = DataTypeHandlerFactory.getIfExists(uri);
42
+ const jsonSchemaMethod = subTypeHandler?.jsonSchema?.bind(subTypeHandler);
43
+ if (Is.function(jsonSchemaMethod)) {
44
+ const subSchema = await jsonSchemaMethod();
45
+ if (Is.object(subSchema)) {
46
+ return subSchema;
47
+ }
48
+ }
49
+ try {
50
+ // We don't have the type in our local data types, so we try to fetch it from the web
51
+ const result = await FetchHelper.fetchJson(JsonSchemaHelper.CLASS_NAME, uri, HttpMethod.GET, undefined, {
52
+ // Cache for an hour
53
+ cacheTtlMs: 3600000
54
+ });
55
+ return result;
56
+ }
57
+ catch {
58
+ // Failed to load remotely so return an empty object
59
+ // so the schema validation doesn't completely fail
60
+ return {};
61
+ }
62
+ }
63
+ };
64
+ let ajv = new Ajv2020.Ajv2020(params);
65
+ if (schema.$schema === JsonSchemaHelper.SCHEMA_VERSION_2019) {
66
+ ajv = new Ajv2019.Ajv2019({ strict: false, ...params });
67
+ }
68
+ formatsPlugin.default(ajv);
69
+ // Add the additional types provided by the user
70
+ if (Is.objectValue(additionalTypes)) {
71
+ for (const key in additionalTypes) {
72
+ ajv.addSchema(additionalTypes[key], key);
73
+ }
74
+ }
75
+ const compiled = await ajv.compileAsync(schema);
76
+ const result = compiled(data);
77
+ const output = {
78
+ result
79
+ };
80
+ if (!output.result) {
81
+ output.error = compiled.errors;
82
+ }
83
+ return output;
84
+ }
85
+ /**
86
+ * Get the property type from a schema.
87
+ * @param schema The schema to extract the types from.
88
+ * @param propertyName The name of the property to get the type for.
89
+ * @returns The types of the property.
90
+ */
91
+ static getPropertyType(schema, propertyName) {
92
+ if (schema.type === "object" && Is.objectValue(schema.properties)) {
93
+ const propertySchema = schema.properties[propertyName];
94
+ if (Is.object(propertySchema)) {
95
+ if (Is.stringValue(propertySchema.$ref)) {
96
+ return propertySchema.$ref;
97
+ }
98
+ return propertySchema.type;
99
+ }
100
+ }
101
+ }
102
+ /**
103
+ * Convert an entity schema to JSON schema e.g https://example.com/schemas/.
104
+ * @param entitySchema The entity schema to convert.
105
+ * @param baseDomain The base domain for local schemas e.g. https://example.com/
106
+ * @returns The JSON schema for the entity.
107
+ */
108
+ static entitySchemaToJsonSchema(entitySchema, baseDomain) {
109
+ let domain = StringHelper.trimTrailingSlashes(baseDomain ?? "");
110
+ if (domain.length > 0) {
111
+ domain += "/";
112
+ }
113
+ const properties = {};
114
+ const required = [];
115
+ if (Is.arrayValue(entitySchema?.properties)) {
116
+ for (const propertySchema of entitySchema.properties) {
117
+ const jsonPropertySchema = {
118
+ type: propertySchema.type,
119
+ description: propertySchema.description,
120
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
121
+ examples: propertySchema.examples
122
+ };
123
+ if (Is.stringValue(propertySchema.itemType) && propertySchema.type === "array") {
124
+ if (propertySchema.itemType === "object") {
125
+ jsonPropertySchema.items = {
126
+ $ref: propertySchema.itemTypeRef?.startsWith("http")
127
+ ? propertySchema.itemTypeRef
128
+ : `${domain}${propertySchema.itemTypeRef}`
129
+ };
130
+ }
131
+ else {
132
+ jsonPropertySchema.items = {
133
+ type: propertySchema.itemType
134
+ };
135
+ }
136
+ }
137
+ else if (propertySchema.type === "object") {
138
+ delete jsonPropertySchema.type;
139
+ jsonPropertySchema.$ref = propertySchema.itemTypeRef?.startsWith("http")
140
+ ? propertySchema.itemTypeRef
141
+ : `${domain}${propertySchema.itemTypeRef}`;
142
+ }
143
+ properties[propertySchema.property] = jsonPropertySchema;
144
+ if (!propertySchema.optional) {
145
+ required.push(propertySchema.property);
146
+ }
147
+ }
148
+ }
149
+ return {
150
+ $schema: JsonSchemaHelper.SCHEMA_VERSION,
151
+ $id: `${domain}${entitySchema?.type}`,
152
+ title: entitySchema?.type,
153
+ type: entitySchema ? "object" : "null",
154
+ description: entitySchema?.options?.description,
155
+ required,
156
+ properties,
157
+ additionalProperties: false
158
+ };
159
+ }
160
+ }
161
+ //# sourceMappingURL=jsonSchemaHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonSchemaHelper.js","sourceRoot":"","sources":["../../../src/utils/jsonSchemaHelper.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGlD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,OAAO,MAAM,kBAAkB,CAAC;AACvC,OAAO,OAAO,MAAM,kBAAkB,CAAC;AACvC,OAAO,aAAa,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAKhF;;GAEG;AACH,MAAM,OAAO,gBAAgB;IAC5B;;OAEG;IACI,MAAM,CAAU,cAAc,GAAG,8CAA8C,CAAC;IAEvF;;OAEG;IACI,MAAM,CAAU,mBAAmB,GAAG,8CAA8C,CAAC;IAE5F;;;OAGG;IACI,MAAM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,UAAU,CAAC,MAAM,CAAC;wBACvE,CAAC,CAAC,cAAc,CAAC,WAAW;wBAC5B,CAAC,CAAC,GAAG,MAAM,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC;gBAC7C,CAAC;gBAED,UAAU,CAAC,cAAc,CAAC,QAAQ,CAAC,GAAG,kBAAkB,CAAC;gBAEzD,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC;oBAC9B,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;gBACxC,CAAC;YACF,CAAC;QACF,CAAC;QAED,OAAO;YACN,OAAO,EAAE,gBAAgB,CAAC,cAAc;YACxC,GAAG,EAAE,GAAG,MAAM,GAAG,YAAY,EAAE,IAAI,EAAE;YACrC,KAAK,EAAE,YAAY,EAAE,IAAI;YACzB,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM;YACtC,WAAW,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW;YAC/C,QAAQ;YACR,UAAU;YACV,oBAAoB,EAAE,KAAK;SAC3B,CAAC;IACH,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { Is, StringHelper } from \"@twin.org/core\";\nimport type { IEntitySchema } from \"@twin.org/entity\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { FetchHelper, HttpMethod } from \"@twin.org/web\";\nimport Ajv2019 from \"ajv/dist/2019.js\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport formatsPlugin from \"ajv-formats\";\nimport { DataTypeHandlerFactory } from \"../factories/dataTypeHandlerFactory.js\";\nimport type { IJsonSchema } from \"../models/IJsonSchema.js\";\nimport type { ISchemaValidationError } from \"../models/ISchemaValidationError.js\";\nimport type { ISchemaValidationResult } from \"../models/ISchemaValidationResult.js\";\n\n/**\n * A helper for JSON schemas.\n */\nexport class JsonSchemaHelper {\n\t/**\n\t * The schema version 2020 (default).\n\t */\n\tpublic static readonly SCHEMA_VERSION = \"https://json-schema.org/draft/2020-12/schema\";\n\n\t/**\n\t * The schema version 2019.\n\t */\n\tpublic static readonly SCHEMA_VERSION_2019 = \"https://json-schema.org/draft/2019-09/schema\";\n\n\t/**\n\t * The class name.\n\t * @internal\n\t */\n\tpublic static readonly CLASS_NAME = nameof<JsonSchemaHelper>();\n\n\t/**\n\t * Validates data against the schema.\n\t * @param schema The schema to validate the data with.\n\t * @param data The data to be validated.\n\t * @param additionalTypes Additional types to add for reference, not already in DataTypeHandlerFactory.\n\t * @returns Result containing errors if there are any.\n\t */\n\tpublic static async validate<T = unknown>(\n\t\tschema: IJsonSchema,\n\t\tdata: T,\n\t\tadditionalTypes?: { [id: string]: IJsonSchema }\n\t): Promise<ISchemaValidationResult> {\n\t\tconst params = {\n\t\t\tallowUnionTypes: true,\n\t\t\t// Disable strict tuples as it causes issues with the schema validation when\n\t\t\t// you have an array with fixed elements e.g. myType: [string, ...string[]]\n\t\t\t// https://github.com/ajv-validator/ajv/issues/1417\n\t\t\tstrictTuples: false,\n\t\t\tloadSchema: async (uri: string) => {\n\t\t\t\tconst subTypeHandler = DataTypeHandlerFactory.getIfExists(uri);\n\t\t\t\tconst jsonSchemaMethod = subTypeHandler?.jsonSchema?.bind(subTypeHandler);\n\t\t\t\tif (Is.function(jsonSchemaMethod)) {\n\t\t\t\t\tconst subSchema = await jsonSchemaMethod();\n\t\t\t\t\tif (Is.object<IJsonSchema>(subSchema)) {\n\t\t\t\t\t\treturn subSchema;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\t// We don't have the type in our local data types, so we try to fetch it from the web\n\t\t\t\t\tconst result = await FetchHelper.fetchJson<never, IJsonSchema>(\n\t\t\t\t\t\tJsonSchemaHelper.CLASS_NAME,\n\t\t\t\t\t\turi,\n\t\t\t\t\t\tHttpMethod.GET,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Cache for an hour\n\t\t\t\t\t\t\tcacheTtlMs: 3600000\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t\treturn result;\n\t\t\t\t} catch {\n\t\t\t\t\t// Failed to load remotely so return an empty object\n\t\t\t\t\t// so the schema validation doesn't completely fail\n\t\t\t\t\treturn {};\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tlet ajv = new Ajv2020.Ajv2020(params);\n\t\tif (schema.$schema === JsonSchemaHelper.SCHEMA_VERSION_2019) {\n\t\t\tajv = new Ajv2019.Ajv2019({ strict: false, ...params });\n\t\t}\n\n\t\tformatsPlugin.default(ajv);\n\n\t\t// Add the additional types provided by the user\n\t\tif (Is.objectValue(additionalTypes)) {\n\t\t\tfor (const key in additionalTypes) {\n\t\t\t\tajv.addSchema(additionalTypes[key], key);\n\t\t\t}\n\t\t}\n\n\t\tconst compiled = await ajv.compileAsync(schema);\n\t\tconst result = compiled(data);\n\n\t\tconst output: ISchemaValidationResult = {\n\t\t\tresult\n\t\t};\n\n\t\tif (!output.result) {\n\t\t\toutput.error = compiled.errors as ISchemaValidationError;\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t/**\n\t * Get the property type from a schema.\n\t * @param schema The schema to extract the types from.\n\t * @param propertyName The name of the property to get the type for.\n\t * @returns The types of the property.\n\t */\n\tpublic static getPropertyType(schema: IJsonSchema, propertyName: string): string | undefined {\n\t\tif (schema.type === \"object\" && Is.objectValue(schema.properties)) {\n\t\t\tconst propertySchema = schema.properties[propertyName];\n\t\t\tif (Is.object<IJsonSchema>(propertySchema)) {\n\t\t\t\tif (Is.stringValue(propertySchema.$ref)) {\n\t\t\t\t\treturn propertySchema.$ref;\n\t\t\t\t}\n\t\t\t\treturn propertySchema.type as string;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Convert an entity schema to JSON schema e.g https://example.com/schemas/.\n\t * @param entitySchema The entity schema to convert.\n\t * @param baseDomain The base domain for local schemas e.g. https://example.com/\n\t * @returns The JSON schema for the entity.\n\t */\n\tpublic static entitySchemaToJsonSchema(\n\t\tentitySchema: IEntitySchema | undefined,\n\t\tbaseDomain?: string\n\t): IJsonSchema {\n\t\tlet domain = StringHelper.trimTrailingSlashes(baseDomain ?? \"\");\n\t\tif (domain.length > 0) {\n\t\t\tdomain += \"/\";\n\t\t}\n\n\t\tconst properties: {\n\t\t\t[key: string]: IJsonSchema;\n\t\t} = {};\n\n\t\tconst required: string[] = [];\n\n\t\tif (Is.arrayValue(entitySchema?.properties)) {\n\t\t\tfor (const propertySchema of entitySchema.properties) {\n\t\t\t\tconst jsonPropertySchema: IJsonSchema = {\n\t\t\t\t\ttype: propertySchema.type,\n\t\t\t\t\tdescription: propertySchema.description,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\t\texamples: propertySchema.examples as unknown as any\n\t\t\t\t};\n\n\t\t\t\tif (Is.stringValue(propertySchema.itemType) && propertySchema.type === \"array\") {\n\t\t\t\t\tif (propertySchema.itemType === \"object\") {\n\t\t\t\t\t\tjsonPropertySchema.items = {\n\t\t\t\t\t\t\t$ref: propertySchema.itemTypeRef?.startsWith(\"http\")\n\t\t\t\t\t\t\t\t? propertySchema.itemTypeRef\n\t\t\t\t\t\t\t\t: `${domain}${propertySchema.itemTypeRef}`\n\t\t\t\t\t\t};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonPropertySchema.items = {\n\t\t\t\t\t\t\ttype: propertySchema.itemType\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else if (propertySchema.type === \"object\") {\n\t\t\t\t\tdelete jsonPropertySchema.type;\n\t\t\t\t\tjsonPropertySchema.$ref = propertySchema.itemTypeRef?.startsWith(\"http\")\n\t\t\t\t\t\t? propertySchema.itemTypeRef\n\t\t\t\t\t\t: `${domain}${propertySchema.itemTypeRef}`;\n\t\t\t\t}\n\n\t\t\t\tproperties[propertySchema.property] = jsonPropertySchema;\n\n\t\t\t\tif (!propertySchema.optional) {\n\t\t\t\t\trequired.push(propertySchema.property);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\t$schema: JsonSchemaHelper.SCHEMA_VERSION,\n\t\t\t$id: `${domain}${entitySchema?.type}`,\n\t\t\ttitle: entitySchema?.type,\n\t\t\ttype: entitySchema ? \"object\" : \"null\",\n\t\t\tdescription: entitySchema?.options?.description,\n\t\t\trequired,\n\t\t\tproperties,\n\t\t\tadditionalProperties: false\n\t\t};\n\t}\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { Factory } from "@twin.org/core";
2
- import type { IDataTypeHandler } from "../models/IDataTypeHandler";
2
+ import type { IDataTypeHandler } from "../models/IDataTypeHandler.js";
3
3
  /**
4
4
  * Factory for creating handlers for data types.
5
5
  */
@@ -1,5 +1,5 @@
1
1
  import { Factory } from "@twin.org/core";
2
- import type { IIdentifierHandler } from "../models/IIdentifierHandler";
2
+ import type { IIdentifierHandler } from "../models/IIdentifierHandler.js";
3
3
  /**
4
4
  * Factory for creating handlers for identifiers.
5
5
  */
@@ -1,10 +1,10 @@
1
- export * from "./factories/dataTypeHandlerFactory";
2
- export * from "./factories/identifierHandlerFactory";
3
- export * from "./models/IDataTypeHandler";
4
- export * from "./models/IIdentifierHandler";
5
- export * from "./models/IJsonSchema";
6
- export * from "./models/ISchemaValidationError";
7
- export * from "./models/ISchemaValidationResult";
8
- export * from "./models/validationMode";
9
- export * from "./utils/dataTypeHelper";
10
- export * from "./utils/jsonSchemaHelper";
1
+ export * from "./factories/dataTypeHandlerFactory.js";
2
+ export * from "./factories/identifierHandlerFactory.js";
3
+ export * from "./models/IDataTypeHandler.js";
4
+ export * from "./models/IIdentifierHandler.js";
5
+ export * from "./models/IJsonSchema.js";
6
+ export * from "./models/ISchemaValidationError.js";
7
+ export * from "./models/ISchemaValidationResult.js";
8
+ export * from "./models/validationMode.js";
9
+ export * from "./utils/dataTypeHelper.js";
10
+ export * from "./utils/jsonSchemaHelper.js";
@@ -1,17 +1,21 @@
1
1
  import type { IValidationFailure } from "@twin.org/core";
2
- import type { IJsonSchema } from "./IJsonSchema";
2
+ import type { IJsonSchema } from "./IJsonSchema.js";
3
3
  /**
4
4
  * Interface describing a type which can handle a specific data type.
5
5
  */
6
6
  export interface IDataTypeHandler {
7
7
  /**
8
- * The context for the type.
8
+ * The namespace for the type.
9
9
  */
10
- context: string;
10
+ namespace: string;
11
11
  /**
12
12
  * The type for the item.
13
13
  */
14
14
  type: string;
15
+ /**
16
+ * The JSON LD context for the type.
17
+ */
18
+ jsonLdContext?: string;
15
19
  /**
16
20
  * The default value for the item to use when constructing a new object.
17
21
  */
@@ -1,5 +1,5 @@
1
- import type { SchemaObject } from "ajv/dist/2020";
1
+ import type Ajv from "ajv/dist/2020.js";
2
2
  /**
3
3
  * Default schema type.
4
4
  */
5
- export type IJsonSchema = SchemaObject;
5
+ export type IJsonSchema = Ajv.SchemaObject;
@@ -1,4 +1,4 @@
1
- import type { ISchemaValidationError } from "./ISchemaValidationError";
1
+ import type { ISchemaValidationError } from "./ISchemaValidationError.js";
2
2
  /**
3
3
  * Validation result.
4
4
  */
@@ -1,9 +1,34 @@
1
1
  import { type IValidationFailure } from "@twin.org/core";
2
- import { ValidationMode } from "../models/validationMode";
2
+ import type { IJsonSchema } from "../models/IJsonSchema.js";
3
+ import { ValidationMode } from "../models/validationMode.js";
3
4
  /**
4
5
  * Class to help with data types.
5
6
  */
6
7
  export declare class DataTypeHelper {
8
+ /**
9
+ * Register a data type.
10
+ * @param namespace The namespace for the type.
11
+ * @param type The type for the item.
12
+ * @param jsonLdContext The JSON LD context for the type.
13
+ * @param schema The JSON schema for the type.
14
+ */
15
+ static registerType(namespace: string, type: string, jsonLdContext: string | undefined, schema: IJsonSchema | Promise<IJsonSchema>): void;
16
+ /**
17
+ * Register a list of types.
18
+ * @param namespace The namespace for the types.
19
+ * @param jsonLdContext The JSON LD context for the types.
20
+ * @param typeDefinition The type definitions to register.
21
+ */
22
+ static registerTypes(namespace: string, jsonLdContext: string | undefined, typeDefinition: {
23
+ type: string;
24
+ schema: IJsonSchema | Promise<IJsonSchema>;
25
+ }[]): void;
26
+ /**
27
+ * Get the JSON schema for a data type.
28
+ * @param dataType The data type to get the schema for.
29
+ * @returns The JSON schema for the data type or undefined if not found.
30
+ */
31
+ static getSchemaForType(dataType: string): Promise<IJsonSchema | undefined>;
7
32
  /**
8
33
  * Validate a data type.
9
34
  * @param propertyName The name of the property being validated to use in error messages.
@@ -1,14 +1,18 @@
1
1
  import type { IEntitySchema } from "@twin.org/entity";
2
- import type { IJsonSchema } from "../models/IJsonSchema";
3
- import type { ISchemaValidationResult } from "../models/ISchemaValidationResult";
2
+ import type { IJsonSchema } from "../models/IJsonSchema.js";
3
+ import type { ISchemaValidationResult } from "../models/ISchemaValidationResult.js";
4
4
  /**
5
5
  * A helper for JSON schemas.
6
6
  */
7
7
  export declare class JsonSchemaHelper {
8
8
  /**
9
- * The schema version.
9
+ * The schema version 2020 (default).
10
10
  */
11
11
  static readonly SCHEMA_VERSION = "https://json-schema.org/draft/2020-12/schema";
12
+ /**
13
+ * The schema version 2019.
14
+ */
15
+ static readonly SCHEMA_VERSION_2019 = "https://json-schema.org/draft/2019-09/schema";
12
16
  /**
13
17
  * Validates data against the schema.
14
18
  * @param schema The schema to validate the data with.