@azure/schema-registry-json 1.0.1-alpha.20241206.1 → 1.0.1-alpha.20241210.2
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/dist/browser/errors.d.ts +5 -0
- package/dist/browser/errors.d.ts.map +1 -0
- package/dist/browser/index.d.ts +3 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +5 -0
- package/{dist-esm/src → dist/browser}/index.js.map +1 -1
- package/dist/browser/jsonSchemaSerializer.d.ts +46 -0
- package/dist/browser/jsonSchemaSerializer.d.ts.map +1 -0
- package/{dist-esm/src → dist/browser}/jsonSchemaSerializer.js +3 -3
- package/dist/browser/jsonSchemaSerializer.js.map +1 -0
- package/dist/browser/logger.d.ts +5 -0
- package/dist/browser/logger.d.ts.map +1 -0
- package/dist/browser/models.d.ts +51 -0
- package/dist/browser/models.d.ts.map +1 -0
- package/dist/browser/package.json +3 -0
- package/dist/browser/utility.d.ts +3 -0
- package/dist/browser/utility.d.ts.map +1 -0
- package/{dist-esm/src → dist/browser}/utility.js.map +1 -1
- package/dist/commonjs/errors.d.ts +5 -0
- package/dist/commonjs/errors.d.ts.map +1 -0
- package/dist/commonjs/errors.js +27 -0
- package/dist/commonjs/errors.js.map +1 -0
- package/dist/commonjs/index.d.ts +3 -0
- package/dist/commonjs/index.d.ts.map +1 -0
- package/dist/commonjs/index.js +10 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/jsonSchemaSerializer.d.ts +46 -0
- package/dist/commonjs/jsonSchemaSerializer.d.ts.map +1 -0
- package/dist/commonjs/jsonSchemaSerializer.js +177 -0
- package/dist/commonjs/jsonSchemaSerializer.js.map +1 -0
- package/dist/commonjs/logger.d.ts +5 -0
- package/dist/commonjs/logger.d.ts.map +1 -0
- package/dist/commonjs/logger.js +11 -0
- package/dist/commonjs/logger.js.map +1 -0
- package/dist/commonjs/models.d.ts +51 -0
- package/dist/commonjs/models.d.ts.map +1 -0
- package/dist/commonjs/models.js +5 -0
- package/dist/commonjs/models.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/commonjs/tsdoc-metadata.json +11 -0
- package/dist/commonjs/utility.d.ts +3 -0
- package/dist/commonjs/utility.d.ts.map +1 -0
- package/dist/commonjs/utility.js +10 -0
- package/dist/commonjs/utility.js.map +1 -0
- package/dist/esm/errors.d.ts +5 -0
- package/dist/esm/errors.d.ts.map +1 -0
- package/dist/esm/errors.js +23 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/index.d.ts +3 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/jsonSchemaSerializer.d.ts +46 -0
- package/dist/esm/jsonSchemaSerializer.d.ts.map +1 -0
- package/dist/{index.js → esm/jsonSchemaSerializer.js} +10 -52
- package/dist/esm/jsonSchemaSerializer.js.map +1 -0
- package/dist/esm/logger.d.ts +5 -0
- package/dist/esm/logger.d.ts.map +1 -0
- package/dist/esm/logger.js +8 -0
- package/dist/esm/logger.js.map +1 -0
- package/dist/esm/models.d.ts +51 -0
- package/dist/esm/models.d.ts.map +1 -0
- package/dist/esm/models.js +4 -0
- package/dist/esm/models.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/utility.d.ts +3 -0
- package/dist/esm/utility.d.ts.map +1 -0
- package/dist/esm/utility.js +7 -0
- package/dist/esm/utility.js.map +1 -0
- package/dist/react-native/errors.d.ts +5 -0
- package/dist/react-native/errors.d.ts.map +1 -0
- package/dist/react-native/errors.js +23 -0
- package/dist/react-native/errors.js.map +1 -0
- package/dist/react-native/index.d.ts +3 -0
- package/dist/react-native/index.d.ts.map +1 -0
- package/dist/react-native/index.js +5 -0
- package/dist/react-native/index.js.map +1 -0
- package/dist/react-native/jsonSchemaSerializer.d.ts +46 -0
- package/dist/react-native/jsonSchemaSerializer.d.ts.map +1 -0
- package/dist/react-native/jsonSchemaSerializer.js +173 -0
- package/dist/react-native/jsonSchemaSerializer.js.map +1 -0
- package/dist/react-native/logger.d.ts +5 -0
- package/dist/react-native/logger.d.ts.map +1 -0
- package/dist/react-native/logger.js +8 -0
- package/dist/react-native/logger.js.map +1 -0
- package/dist/react-native/models.d.ts +51 -0
- package/dist/react-native/models.d.ts.map +1 -0
- package/dist/react-native/models.js +4 -0
- package/dist/react-native/models.js.map +1 -0
- package/dist/react-native/package.json +3 -0
- package/dist/react-native/utility.d.ts +3 -0
- package/dist/react-native/utility.d.ts.map +1 -0
- package/dist/react-native/utility.js +7 -0
- package/dist/react-native/utility.js.map +1 -0
- package/package.json +65 -36
- package/dist/index.js.map +0 -1
- package/dist-esm/src/index.js +0 -5
- package/dist-esm/src/jsonSchemaSerializer.js.map +0 -1
- package/types/schema-registry-json.d.ts +0 -101
- /package/{dist-esm/src → dist/browser}/errors.js +0 -0
- /package/{dist-esm/src → dist/browser}/errors.js.map +0 -0
- /package/{dist-esm/src → dist/browser}/logger.js +0 -0
- /package/{dist-esm/src → dist/browser}/logger.js.map +0 -0
- /package/{dist-esm/src → dist/browser}/models.js +0 -0
- /package/{dist-esm/src → dist/browser}/models.js.map +0 -0
- /package/{dist-esm/src → dist/browser}/utility.js +0 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Copyright (c) Microsoft Corporation.
|
|
2
|
+
// Licensed under the MIT License.
|
|
3
|
+
import { KnownSchemaFormats } from "@azure/schema-registry";
|
|
4
|
+
import { isMessageContent } from "./utility.js";
|
|
5
|
+
import { errorWithCause, wrapError } from "./errors.js";
|
|
6
|
+
import { LRUCache } from "lru-cache";
|
|
7
|
+
import { logger } from "./logger.js";
|
|
8
|
+
const jsonMimeType = "application/json";
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
const decoder = new TextDecoder();
|
|
11
|
+
function getSchemaObject(schema) {
|
|
12
|
+
return wrapError(() => JSON.parse(schema), `Parsing Json schema failed:\n\n\t${schema}\n\nSee 'cause' for more details.`);
|
|
13
|
+
}
|
|
14
|
+
const cacheOptions = {
|
|
15
|
+
max: 128,
|
|
16
|
+
/**
|
|
17
|
+
* This is needed in order to specify `sizeCalculation` but we do not intend
|
|
18
|
+
* to limit the size just yet.
|
|
19
|
+
*/
|
|
20
|
+
maxSize: Number.MAX_VALUE,
|
|
21
|
+
sizeCalculation: (_value, key) => {
|
|
22
|
+
return key.length;
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Json serializer that obtains schemas from a schema registry and does not
|
|
27
|
+
* pack schemas into its payloads.
|
|
28
|
+
*/
|
|
29
|
+
export class JsonSchemaSerializer {
|
|
30
|
+
/**
|
|
31
|
+
* Creates a new serializer.
|
|
32
|
+
*
|
|
33
|
+
* @param client - Schema Registry where schemas are registered and obtained.
|
|
34
|
+
* Usually this is a SchemaRegistryClient instance.
|
|
35
|
+
*/
|
|
36
|
+
constructor(client, options) {
|
|
37
|
+
this.cacheIdByDefinition = new LRUCache(cacheOptions);
|
|
38
|
+
this.cacheById = new LRUCache(cacheOptions);
|
|
39
|
+
this.registry = client;
|
|
40
|
+
this.schemaGroup = options === null || options === void 0 ? void 0 : options.groupName;
|
|
41
|
+
this.messageAdapter = options === null || options === void 0 ? void 0 : options.messageAdapter;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* serializes the value parameter according to the input schema and creates a message
|
|
45
|
+
* with the serialized data.
|
|
46
|
+
*
|
|
47
|
+
* @param value - The value to serialize.
|
|
48
|
+
* @param schema - The Json schema to use.
|
|
49
|
+
* @returns A new message with the serialized value. The structure of message is
|
|
50
|
+
* constrolled by the message factory option.
|
|
51
|
+
* @throws {@link Error}
|
|
52
|
+
* Thrown if the schema can not be parsed or the value does not match the schema.
|
|
53
|
+
*/
|
|
54
|
+
async serialize(value, schema) {
|
|
55
|
+
const entry = await this.getSchemaByDefinition(schema);
|
|
56
|
+
const data = wrapError(() => encoder.encode(JSON.stringify(value)), `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`);
|
|
57
|
+
const contentType = `${jsonMimeType}+${entry.id}`;
|
|
58
|
+
return this.messageAdapter
|
|
59
|
+
? this.messageAdapter.produce({
|
|
60
|
+
contentType,
|
|
61
|
+
data,
|
|
62
|
+
})
|
|
63
|
+
: /**
|
|
64
|
+
* If no message consumer was provided, then a MessageContent will be
|
|
65
|
+
* returned. This should work because the MessageT type parameter defaults
|
|
66
|
+
* to MessageContent.
|
|
67
|
+
*/
|
|
68
|
+
{
|
|
69
|
+
data,
|
|
70
|
+
contentType,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Deserializes the payload of the message using the schema ID in the content type
|
|
75
|
+
* field if no schema was provided.
|
|
76
|
+
*
|
|
77
|
+
* @param message - The message with the payload to be deserialized.
|
|
78
|
+
* @returns The deserialized value.
|
|
79
|
+
* @throws {@link Error}
|
|
80
|
+
* Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.
|
|
81
|
+
*/
|
|
82
|
+
async deserialize(message, options) {
|
|
83
|
+
const { data, contentType } = convertMessage(message, this.messageAdapter);
|
|
84
|
+
const schemaId = getSchemaId(contentType);
|
|
85
|
+
const schema = await this.getSchemaById(schemaId);
|
|
86
|
+
const returnedMessage = wrapError(() => JSON.parse(decoder.decode(data)), `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`);
|
|
87
|
+
const validate = options === null || options === void 0 ? void 0 : options.validateCallback;
|
|
88
|
+
if (validate) {
|
|
89
|
+
wrapError(() => validate(returnedMessage, schema), `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`);
|
|
90
|
+
}
|
|
91
|
+
return returnedMessage;
|
|
92
|
+
}
|
|
93
|
+
async getSchemaById(schemaId) {
|
|
94
|
+
const cached = this.cacheById.get(schemaId);
|
|
95
|
+
if (cached) {
|
|
96
|
+
return cached;
|
|
97
|
+
}
|
|
98
|
+
const schemaResponse = await this.registry.getSchema(schemaId);
|
|
99
|
+
if (!schemaResponse) {
|
|
100
|
+
throw new Error(`Schema with ID '${schemaId}' not found.`);
|
|
101
|
+
}
|
|
102
|
+
if (!schemaResponse.properties.format.match(/^json$/i)) {
|
|
103
|
+
throw new Error(`Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`);
|
|
104
|
+
}
|
|
105
|
+
return this.cache(schemaResponse.definition, schemaId).schema;
|
|
106
|
+
}
|
|
107
|
+
async getSchemaByDefinition(definition) {
|
|
108
|
+
const schemaId = this.cacheIdByDefinition.get(definition);
|
|
109
|
+
if (schemaId) {
|
|
110
|
+
return { id: schemaId, schema: definition };
|
|
111
|
+
}
|
|
112
|
+
if (!this.schemaGroup) {
|
|
113
|
+
throw new Error("Schema group must have been specified in the constructor options when the client was created in order to serialize.");
|
|
114
|
+
}
|
|
115
|
+
const schemaObj = getSchemaObject(definition);
|
|
116
|
+
const description = {
|
|
117
|
+
groupName: this.schemaGroup,
|
|
118
|
+
name: getSchemaName(schemaObj),
|
|
119
|
+
format: KnownSchemaFormats.Json,
|
|
120
|
+
definition,
|
|
121
|
+
};
|
|
122
|
+
let id;
|
|
123
|
+
try {
|
|
124
|
+
id = (await this.registry.getSchemaProperties(description)).id;
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
if (e.statusCode === 404) {
|
|
128
|
+
throw errorWithCause(`Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`, e);
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
throw e;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return this.cache(definition, id);
|
|
135
|
+
}
|
|
136
|
+
cache(schema, id) {
|
|
137
|
+
const entry = { schema, id };
|
|
138
|
+
this.cacheIdByDefinition.set(schema, id);
|
|
139
|
+
this.cacheById.set(id, schema);
|
|
140
|
+
logger.verbose(`Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`);
|
|
141
|
+
return entry;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function getSchemaId(contentType) {
|
|
145
|
+
const contentTypeParts = contentType.split("+");
|
|
146
|
+
if (contentTypeParts.length !== 2) {
|
|
147
|
+
throw new Error("Content type was not in the expected format of MIME type + schema ID");
|
|
148
|
+
}
|
|
149
|
+
if (contentTypeParts[0] !== jsonMimeType) {
|
|
150
|
+
throw new Error(`Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`);
|
|
151
|
+
}
|
|
152
|
+
return contentTypeParts[1];
|
|
153
|
+
}
|
|
154
|
+
function convertMessage(message, adapter) {
|
|
155
|
+
const messageConsumer = adapter === null || adapter === void 0 ? void 0 : adapter.consume;
|
|
156
|
+
if (messageConsumer) {
|
|
157
|
+
return messageConsumer(message);
|
|
158
|
+
}
|
|
159
|
+
else if (isMessageContent(message)) {
|
|
160
|
+
return message;
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
throw new Error(`Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function getSchemaName(schema) {
|
|
167
|
+
const id = schema.$id || schema.id;
|
|
168
|
+
if (!id) {
|
|
169
|
+
throw new Error("Schema must have an ID.");
|
|
170
|
+
}
|
|
171
|
+
return id;
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=jsonSchemaSerializer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW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C,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,eAAO,MAAM,MAAM,qCAA6C,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Copyright (c) Microsoft Corporation.
|
|
2
|
+
// Licensed under the MIT License.
|
|
3
|
+
import { createClientLogger } from "@azure/logger";
|
|
4
|
+
/**
|
|
5
|
+
* The \@azure/logger configuration for the schema-registry-json package.
|
|
6
|
+
*/
|
|
7
|
+
export const logger = createClientLogger("schema-registry-json");
|
|
8
|
+
//# sourceMappingURL=logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,sBAAsB,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The \\@azure/logger configuration for the schema-registry-json package.\n */\nexport const logger = createClientLogger(\"schema-registry-json\");\n"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A message that contains binary data and a content type.
|
|
3
|
+
*/
|
|
4
|
+
export interface MessageContent {
|
|
5
|
+
/**
|
|
6
|
+
* The message's binary data
|
|
7
|
+
*/
|
|
8
|
+
data: Uint8Array;
|
|
9
|
+
/**
|
|
10
|
+
* The message's content type
|
|
11
|
+
*/
|
|
12
|
+
contentType: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* MessageAdapter is an interface that converts to/from a concrete message type
|
|
16
|
+
* to a MessageContent
|
|
17
|
+
*/
|
|
18
|
+
export interface MessageAdapter<MessageT> {
|
|
19
|
+
/**
|
|
20
|
+
* defines how to create a message from a payload and a content type
|
|
21
|
+
*/
|
|
22
|
+
produce: (messageContent: MessageContent) => MessageT;
|
|
23
|
+
/**
|
|
24
|
+
* defines how to access the payload and the content type of a message
|
|
25
|
+
*/
|
|
26
|
+
consume: (message: MessageT) => MessageContent;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Options for Schema
|
|
30
|
+
*/
|
|
31
|
+
export interface JsonSchemaSerializerOptions<MessageT> {
|
|
32
|
+
/**
|
|
33
|
+
* The group name to be used when registering/looking up a schema. Must be specified
|
|
34
|
+
* if `serialize` will be called.
|
|
35
|
+
*/
|
|
36
|
+
groupName?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Message Adapter enables the serializer to produce and consume custom messages.
|
|
39
|
+
*/
|
|
40
|
+
messageAdapter?: MessageAdapter<MessageT>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The options to the deserialize method.
|
|
44
|
+
*/
|
|
45
|
+
export interface DeserializeOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Validate the value against the schema. Raise an error if the validation is not successful.
|
|
48
|
+
*/
|
|
49
|
+
validateCallback?: (value: unknown, schema: string) => void;
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=models.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../../src/models.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,IAAI,EAAE,UAAU,CAAC;IACjB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc,CAAC,QAAQ;IACtC;;OAEG;IACH,OAAO,EAAE,CAAC,cAAc,EAAE,cAAc,KAAK,QAAQ,CAAC;IACtD;;OAEG;IACH,OAAO,EAAE,CAAC,OAAO,EAAE,QAAQ,KAAK,cAAc,CAAC;CAChD;AAED;;GAEG;AACH,MAAM,WAAW,2BAA2B,CAAC,QAAQ;IACnD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC;CAC3C;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7D"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"models.js","sourceRoot":"","sources":["../../src/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * A message that contains binary data and a content type.\n */\nexport interface MessageContent {\n /**\n * The message's binary data\n */\n data: Uint8Array;\n /**\n * The message's content type\n */\n contentType: string;\n}\n\n/**\n * MessageAdapter is an interface that converts to/from a concrete message type\n * to a MessageContent\n */\nexport interface MessageAdapter<MessageT> {\n /**\n * defines how to create a message from a payload and a content type\n */\n produce: (messageContent: MessageContent) => MessageT;\n /**\n * defines how to access the payload and the content type of a message\n */\n consume: (message: MessageT) => MessageContent;\n}\n\n/**\n * Options for Schema\n */\nexport interface JsonSchemaSerializerOptions<MessageT> {\n /**\n * The group name to be used when registering/looking up a schema. Must be specified\n * if `serialize` will be called.\n */\n groupName?: string;\n /**\n * Message Adapter enables the serializer to produce and consume custom messages.\n */\n messageAdapter?: MessageAdapter<MessageT>;\n}\n\n/**\n * The options to the deserialize method.\n */\nexport interface DeserializeOptions {\n /**\n * Validate the value against the schema. Raise an error if the validation is not successful.\n */\n validateCallback?: (value: unknown, schema: string) => void;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utility.d.ts","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,cAAc,CAG5E"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Copyright (c) Microsoft Corporation.
|
|
2
|
+
// Licensed under the MIT License.
|
|
3
|
+
export function isMessageContent(message) {
|
|
4
|
+
const castMessage = message;
|
|
5
|
+
return castMessage.data !== undefined && castMessage.contentType !== undefined;
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=utility.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAC/C,MAAM,WAAW,GAAG,OAAyB,CAAC;IAC9C,OAAO,WAAW,CAAC,IAAI,KAAK,SAAS,IAAI,WAAW,CAAC,WAAW,KAAK,SAAS,CAAC;AACjF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MessageContent } from \"./models.js\";\n\nexport function isMessageContent(message: unknown): message is MessageContent {\n const castMessage = message as MessageContent;\n return castMessage.data !== undefined && castMessage.contentType !== undefined;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@azure/schema-registry-json",
|
|
3
|
-
"version": "1.0.1-alpha.
|
|
3
|
+
"version": "1.0.1-alpha.20241210.2",
|
|
4
4
|
"description": "Schema Registry JSON Serializer Library with typescript type definitions for node.js and browser.",
|
|
5
5
|
"sdk-type": "client",
|
|
6
|
-
"main": "dist/index.js",
|
|
7
|
-
"module": "dist
|
|
8
|
-
"types": "
|
|
6
|
+
"main": "./dist/commonjs/index.js",
|
|
7
|
+
"module": "./dist/esm/index.js",
|
|
8
|
+
"types": "./dist/commonjs/index.d.ts",
|
|
9
9
|
"scripts": {
|
|
10
|
-
"build": "npm run clean &&
|
|
10
|
+
"build": "npm run clean && dev-tool run build-package && dev-tool run extract-api",
|
|
11
11
|
"build:browser": "npm run bundle",
|
|
12
12
|
"build:node": "npm run bundle",
|
|
13
13
|
"build:samples": "echo Obsolete.",
|
|
14
14
|
"build:test": "npm run bundle",
|
|
15
|
-
"bundle": "
|
|
15
|
+
"bundle": "dev-tool run build-package && dev-tool run bundle --polyfill-node false --inject-node-polyfills true --ignore-missing-node-builtins true",
|
|
16
16
|
"check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
|
|
17
17
|
"clean": "dev-tool run vendored rimraf --glob dist dist-* temp types *.tgz *.log",
|
|
18
18
|
"execute:samples": "dev-tool samples run samples-dev",
|
|
19
|
-
"extract-api": "
|
|
19
|
+
"extract-api": "dev-tool run build-package && dev-tool run extract-api",
|
|
20
20
|
"format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
|
|
21
21
|
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
|
|
22
|
-
"integration-test:browser": "dev-tool run test:browser",
|
|
23
|
-
"integration-test:node": "dev-tool run test:
|
|
22
|
+
"integration-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser",
|
|
23
|
+
"integration-test:node": "dev-tool run test:vitest --esm",
|
|
24
24
|
"lint": "eslint package.json api-extractor.json README.md src test",
|
|
25
25
|
"lint:fix": "eslint package.json api-extractor.json README.md src test --fix --fix-type [problem,suggestion]",
|
|
26
26
|
"pack": "npm pack 2>&1",
|
|
@@ -28,14 +28,12 @@
|
|
|
28
28
|
"test:browser": "npm run build:test && npm run unit-test:browser && npm run integration-test:browser",
|
|
29
29
|
"test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node",
|
|
30
30
|
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
|
|
31
|
-
"unit-test:browser": "dev-tool run test:browser",
|
|
32
|
-
"unit-test:node": "dev-tool run test:
|
|
31
|
+
"unit-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser",
|
|
32
|
+
"unit-test:node": "dev-tool run test:vitest",
|
|
33
33
|
"update-snippets": "echo skipped"
|
|
34
34
|
},
|
|
35
35
|
"files": [
|
|
36
36
|
"dist/",
|
|
37
|
-
"dist-esm/src/",
|
|
38
|
-
"types/schema-registry-json.d.ts",
|
|
39
37
|
"README.md",
|
|
40
38
|
"LICENSE"
|
|
41
39
|
],
|
|
@@ -71,36 +69,67 @@
|
|
|
71
69
|
"@azure/logger": "^1.0.0",
|
|
72
70
|
"@azure/schema-registry": "^1.3.0",
|
|
73
71
|
"lru-cache": "^10.2.0",
|
|
74
|
-
"tslib": "^2.
|
|
72
|
+
"tslib": "^2.8.1"
|
|
75
73
|
},
|
|
76
74
|
"devDependencies": {
|
|
77
|
-
"@azure-tools/test-credential": "^
|
|
78
|
-
"@azure-tools/test-recorder": "
|
|
79
|
-
"@azure-tools/test-utils": "
|
|
75
|
+
"@azure-tools/test-credential": "^2.0.0",
|
|
76
|
+
"@azure-tools/test-recorder": ">=4.1.0-alpha <4.1.0-alphb",
|
|
77
|
+
"@azure-tools/test-utils-vitest": ">=1.0.0-alpha <1.0.0-alphb",
|
|
78
|
+
"@azure-tools/vite-plugin-browser-test-map": ">=1.0.0-alpha <1.0.0-alphb",
|
|
80
79
|
"@azure/core-util": "^1.3.0",
|
|
81
80
|
"@azure/dev-tool": ">=1.0.0-alpha <1.0.0-alphb",
|
|
82
81
|
"@azure/eslint-plugin-azure-sdk": ">=3.0.0-alpha <3.0.0-alphb",
|
|
83
|
-
"@azure/event-hubs": "^5.
|
|
84
|
-
"@azure/identity": "^4.0
|
|
85
|
-
"@
|
|
82
|
+
"@azure/event-hubs": "^5.12.2",
|
|
83
|
+
"@azure/identity": "^4.5.0",
|
|
84
|
+
"@rollup/plugin-inject": "^5.0.5",
|
|
86
85
|
"@types/node": "^18.0.0",
|
|
87
|
-
"
|
|
86
|
+
"@vitest/browser": "^2.1.8",
|
|
87
|
+
"@vitest/coverage-istanbul": "^2.1.8",
|
|
88
|
+
"ajv": "^8.17.1",
|
|
89
|
+
"buffer": "^6.0.3",
|
|
88
90
|
"dotenv": "^16.0.0",
|
|
89
91
|
"eslint": "^9.9.0",
|
|
90
|
-
"
|
|
91
|
-
"
|
|
92
|
-
"
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
"
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
"
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
"
|
|
92
|
+
"playwright": "^1.49.0",
|
|
93
|
+
"typescript": "~5.6.2",
|
|
94
|
+
"vitest": "^2.1.8"
|
|
95
|
+
},
|
|
96
|
+
"type": "module",
|
|
97
|
+
"tshy": {
|
|
98
|
+
"exports": {
|
|
99
|
+
"./package.json": "./package.json",
|
|
100
|
+
".": "./src/index.ts"
|
|
101
|
+
},
|
|
102
|
+
"dialects": [
|
|
103
|
+
"esm",
|
|
104
|
+
"commonjs"
|
|
105
|
+
],
|
|
106
|
+
"esmDialects": [
|
|
107
|
+
"browser",
|
|
108
|
+
"react-native"
|
|
109
|
+
],
|
|
110
|
+
"selfLink": false,
|
|
111
|
+
"project": "./tsconfig.src.json"
|
|
112
|
+
},
|
|
113
|
+
"browser": "./dist/browser/index.js",
|
|
114
|
+
"exports": {
|
|
115
|
+
"./package.json": "./package.json",
|
|
116
|
+
".": {
|
|
117
|
+
"browser": {
|
|
118
|
+
"types": "./dist/browser/index.d.ts",
|
|
119
|
+
"default": "./dist/browser/index.js"
|
|
120
|
+
},
|
|
121
|
+
"react-native": {
|
|
122
|
+
"types": "./dist/react-native/index.d.ts",
|
|
123
|
+
"default": "./dist/react-native/index.js"
|
|
124
|
+
},
|
|
125
|
+
"import": {
|
|
126
|
+
"types": "./dist/esm/index.d.ts",
|
|
127
|
+
"default": "./dist/esm/index.js"
|
|
128
|
+
},
|
|
129
|
+
"require": {
|
|
130
|
+
"types": "./dist/commonjs/index.d.ts",
|
|
131
|
+
"default": "./dist/commonjs/index.js"
|
|
132
|
+
}
|
|
133
|
+
}
|
|
105
134
|
}
|
|
106
135
|
}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/utility.ts","../src/errors.ts","../src/logger.ts","../src/jsonSchemaSerializer.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MessageContent } from \"./models\";\n\nexport function isMessageContent(message: unknown): message is MessageContent {\n const castMessage = message as MessageContent;\n return castMessage.data !== undefined && castMessage.contentType !== undefined;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/** @internal */\nexport function wrapError<T>(f: () => T, message: string): T {\n let result: T;\n try {\n result = f();\n } catch (cause) {\n throw errorWithCause(message, cause as Error);\n }\n return result;\n}\n\n/** @internal */\nexport function errorWithCause(message: string, cause: Error): Error {\n return new Error(\n message,\n // TS v4.6 and below do not yet recognize the cause option in the Error constructor\n // see https://medium.com/ovrsea/power-up-your-node-js-debugging-and-error-handling-with-the-new-error-cause-feature-4136c563126a\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n { cause },\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The \\@azure/logger configuration for the schema-registry-json package.\n */\nexport const logger = createClientLogger(\"schema-registry-json\");\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility\";\nimport { errorWithCause, wrapError } from \"./errors\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"],"names":["createClientLogger","LRUCache","KnownSchemaFormats"],"mappings":";;;;;;;;AAAA;AACA;AAIM,SAAU,gBAAgB,CAAC,OAAgB,EAAA;IAC/C,MAAM,WAAW,GAAG,OAAyB;IAC7C,OAAO,WAAW,CAAC,IAAI,KAAK,SAAS,IAAI,WAAW,CAAC,WAAW,KAAK,SAAS;AAChF;;ACRA;AACA;AAEA;AACgB,SAAA,SAAS,CAAI,CAAU,EAAE,OAAe,EAAA;AACtD,IAAA,IAAI,MAAS;AACb,IAAA,IAAI;QACF,MAAM,GAAG,CAAC,EAAE;;IACZ,OAAO,KAAK,EAAE;AACd,QAAA,MAAM,cAAc,CAAC,OAAO,EAAE,KAAc,CAAC;;AAE/C,IAAA,OAAO,MAAM;AACf;A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AS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility\";\nimport { errorWithCause, wrapError } from \"./errors\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
|