node-opcua-client-dynamic-extension-object 2.70.1 → 2.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/client_dynamic_extension_object.d.ts +22 -0
  2. package/dist/client_dynamic_extension_object.js +1012 -0
  3. package/dist/client_dynamic_extension_object.js.map +1 -0
  4. package/dist/convert_data_type_definition_to_structuretype_schema.d.ts +12 -12
  5. package/dist/convert_data_type_definition_to_structuretype_schema.js +343 -331
  6. package/dist/convert_data_type_definition_to_structuretype_schema.js.map +1 -1
  7. package/dist/extra_data_type_manager.d.ts +16 -16
  8. package/dist/extra_data_type_manager.js +75 -75
  9. package/dist/get_extension_object_constructor.d.ts +7 -7
  10. package/dist/get_extension_object_constructor.js +37 -37
  11. package/dist/get_extra_data_type_manager.d.ts +3 -3
  12. package/dist/get_extra_data_type_manager.js +51 -51
  13. package/dist/index.d.ts +12 -12
  14. package/dist/index.js +28 -28
  15. package/dist/populate_data_type_manager.d.ts +3 -3
  16. package/dist/populate_data_type_manager.js +25 -25
  17. package/dist/private/find_encodings.d.ts +4 -4
  18. package/dist/private/find_encodings.js +55 -55
  19. package/dist/private/populate_data_type_manager_103.d.ts +9 -9
  20. package/dist/private/populate_data_type_manager_103.js +601 -601
  21. package/dist/private/populate_data_type_manager_104.d.ts +9 -9
  22. package/dist/private/populate_data_type_manager_104.js +182 -182
  23. package/dist/private/populate_data_type_manager_104.js.map +1 -1
  24. package/dist/promote_opaque_structure.d.ts +6 -6
  25. package/dist/promote_opaque_structure.js +41 -41
  26. package/dist/promote_opaque_structure_in_notification_data.d.ts +3 -3
  27. package/dist/promote_opaque_structure_in_notification_data.js +51 -51
  28. package/dist/resolve_dynamic_extension_object.d.ts +4 -4
  29. package/dist/resolve_dynamic_extension_object.js +105 -105
  30. package/dist/resolve_dynamic_extension_object.js.map +1 -1
  31. package/package.json +16 -16
  32. package/source/convert_data_type_definition_to_structuretype_schema.ts +43 -30
  33. package/source/private/populate_data_type_manager_104.ts +1 -0
  34. package/source/resolve_dynamic_extension_object.ts +13 -10
@@ -1,602 +1,602 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.populateDataTypeManager103 = void 0;
13
- /* eslint-disable max-statements */
14
- // tslint:disable: no-console
15
- /**
16
- * @module node-opcua-client-dynamic-extension-object
17
- */
18
- const chalk = require("chalk");
19
- const node_opcua_assert_1 = require("node-opcua-assert");
20
- const node_opcua_data_model_1 = require("node-opcua-data-model");
21
- const node_opcua_debug_1 = require("node-opcua-debug");
22
- const node_opcua_factory_1 = require("node-opcua-factory");
23
- const node_opcua_nodeid_1 = require("node-opcua-nodeid");
24
- const node_opcua_pseudo_session_1 = require("node-opcua-pseudo-session");
25
- const node_opcua_schemas_1 = require("node-opcua-schemas");
26
- const node_opcua_service_browse_1 = require("node-opcua-service-browse");
27
- const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
28
- const node_opcua_status_code_1 = require("node-opcua-status-code");
29
- const node_opcua_types_1 = require("node-opcua-types");
30
- const convert_data_type_definition_to_structuretype_schema_1 = require("../convert_data_type_definition_to_structuretype_schema");
31
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
32
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
33
- const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
34
- const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
35
- // DataType
36
- // | 1
37
- // | n
38
- // +- HasEncoding-> "Default Binary" (O)[DataTypeEncodingType]
39
- // |
40
- // +-- HasDescription -> "MyItemType" (V)[DataTypeDescriptionType]
41
- // |
42
- // +- ComponentOf -> Schema(V) []
43
- // |
44
- // +- ComponentOf -> OPC Binary(V)[DataTypeSystemType]
45
- //
46
- // Note that in 1.04 compliant server, DataType definition might be available
47
- // in a DataTypeDefinition attributes of the DataType object
48
- // However this is a brand new aspect of the specification and is not widely implemented
49
- // it is also optional
50
- // It will takes time for old opcua server to be refurbished and we may have to
51
- // keep the current method to access type definition from embedded xsd.
52
- //
53
- function _readDeprecatedFlag(session, dataTypeDictionary) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const browsePath = (0, node_opcua_service_translate_browse_path_1.makeBrowsePath)(dataTypeDictionary, ".Deprecated");
56
- const a = yield session.translateBrowsePath(browsePath);
57
- /* istanbul ignore next */
58
- if (!a.targets || a.targets.length === 0) {
59
- // the server is probably version < 1.04.
60
- debugLog("Cannot find Deprecated property for dataTypeDictionary " + dataTypeDictionary.toString());
61
- return false;
62
- }
63
- const deprecatedFlagNodeId = a.targets[0].targetId;
64
- const dataValue = yield session.read({ nodeId: deprecatedFlagNodeId, attributeId: node_opcua_data_model_1.AttributeIds.Value });
65
- return dataValue.value.value;
66
- });
67
- }
68
- function _readNamespaceUriProperty(session, dataTypeDictionary) {
69
- return __awaiter(this, void 0, void 0, function* () {
70
- const a = yield session.translateBrowsePath((0, node_opcua_service_translate_browse_path_1.makeBrowsePath)(dataTypeDictionary, ".NamespaceUri"));
71
- /* istanbul ignore next */
72
- if (!a.targets || a.targets.length === 0) {
73
- return "??dataTypeDictionary doesn't expose NamespaceUri property??";
74
- }
75
- const namespaceUriProp = a.targets[0].targetId;
76
- const dataValue = yield session.read({ nodeId: namespaceUriProp, attributeId: node_opcua_data_model_1.AttributeIds.Value });
77
- return dataValue.value.value || "<not set>";
78
- });
79
- }
80
- function _getDataTypeDescriptions(session, dataTypeDictionaryNodeId) {
81
- return __awaiter(this, void 0, void 0, function* () {
82
- const nodeToBrowse2 = {
83
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
84
- includeSubtypes: false,
85
- nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Variable"),
86
- nodeId: dataTypeDictionaryNodeId,
87
- referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasComponent"),
88
- // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
89
- resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId | BrowseName")
90
- };
91
- const result2 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodeToBrowse2);
92
- result2.references = result2.references || [];
93
- return result2.references.map((r) => ({ nodeId: r.nodeId, browseName: r.browseName }));
94
- });
95
- }
96
- function _enrichWithDescriptionOf(session, dataTypeDescriptions) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- const nodesToBrowse3 = [];
99
- for (const ref of dataTypeDescriptions) {
100
- ref.browseName.toString();
101
- nodesToBrowse3.push({
102
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
103
- includeSubtypes: false,
104
- nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Object"),
105
- nodeId: ref.nodeId.toString(),
106
- referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasDescription"),
107
- // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
108
- resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId")
109
- });
110
- }
111
- /* istanbul ignore next */
112
- if (nodesToBrowse3.length === 0) {
113
- return [];
114
- }
115
- const results3 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodesToBrowse3);
116
- const binaryEncodings = [];
117
- const nodesToBrowseDataType = [];
118
- let i = 0;
119
- for (const result3 of results3) {
120
- const dataTypeDescription = dataTypeDescriptions[i++];
121
- result3.references = result3.references || [];
122
- if (result3.references.length !== 1) {
123
- warningLog("_enrichWithDescriptionOf : expecting 1 reference for ", dataTypeDescription.browseName.toString());
124
- continue;
125
- }
126
- for (const ref of result3.references) {
127
- const binaryEncodingNodeId = ref.nodeId;
128
- dataTypeDescription.encodings = dataTypeDescription.encodings || {
129
- binaryEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
130
- dataTypeNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
131
- jsonEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
132
- xmlEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId
133
- };
134
- dataTypeDescription.encodings.binaryEncodingNodeId = binaryEncodingNodeId;
135
- binaryEncodings.push(binaryEncodingNodeId);
136
- nodesToBrowseDataType.push({
137
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
138
- includeSubtypes: false,
139
- nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("DataType"),
140
- nodeId: ref.nodeId.toString(),
141
- referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasEncoding"),
142
- // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
143
- resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId | BrowseName")
144
- });
145
- }
146
- }
147
- const dataTypeNodeIds = [];
148
- if (nodesToBrowseDataType.length > 0) {
149
- const results4 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodesToBrowseDataType);
150
- i = 0;
151
- for (const result4 of results4) {
152
- result4.references = result4.references || [];
153
- /* istanbul ignore next */
154
- if (result4.references.length !== 1) {
155
- console.log("What's going on ?", result4.toString());
156
- }
157
- for (const ref of result4.references) {
158
- const dataTypeNodeId = ref.nodeId;
159
- dataTypeNodeIds.push(dataTypeNodeId);
160
- const dataTypeDescription = dataTypeDescriptions[i++];
161
- dataTypeDescription.encodings.dataTypeNodeId = dataTypeNodeId;
162
- }
163
- }
164
- }
165
- return dataTypeNodeIds;
166
- });
167
- }
168
- function sortStructure(dataTypeDefinitions) {
169
- const dataTypeDefinitionsSorted = [];
170
- const _visited = {};
171
- const _map = {};
172
- for (const d of dataTypeDefinitions) {
173
- _map[d.dataTypeNodeId.toString()] = d;
174
- }
175
- function _visit(d) {
176
- const hash = d.dataTypeNodeId.toString();
177
- if (_visited[hash]) {
178
- return;
179
- }
180
- _visited[hash] = d;
181
- const bbb = _map[d.dataTypeDefinition.baseDataType.toString()];
182
- if (bbb) {
183
- _visit(bbb);
184
- }
185
- for (const f of d.dataTypeDefinition.fields || []) {
186
- const ddd = _map[f.dataType.toString()];
187
- if (!ddd) {
188
- continue;
189
- }
190
- _visit(ddd);
191
- }
192
- dataTypeDefinitionsSorted.push(d);
193
- }
194
- for (const d of dataTypeDefinitions) {
195
- _visit(d);
196
- }
197
- return dataTypeDefinitionsSorted;
198
- }
199
- function _extractDataTypeDictionaryFromDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory) {
200
- return __awaiter(this, void 0, void 0, function* () {
201
- (0, node_opcua_assert_1.assert)(dataTypeFactory, "expecting a dataTypeFactory");
202
- const dataTypeDescriptions = yield _getDataTypeDescriptions(session, dataTypeDictionaryNodeId);
203
- const dataTypeNodeIds = yield _enrichWithDescriptionOf(session, dataTypeDescriptions);
204
- // now read DataTypeDefinition attributes of all the dataTypeNodeIds, this will only contains concrete structure
205
- const nodesToRead = dataTypeNodeIds.map((nodeId) => ({
206
- attributeId: node_opcua_data_model_1.AttributeIds.DataTypeDefinition,
207
- nodeId
208
- }));
209
- const cache = {};
210
- const dataValuesWithDataTypeDefinition = nodesToRead.length > 0 ? yield session.read(nodesToRead) : [];
211
- // in some circumstances like Euromap, this assert fails:
212
- // assert(dataValuesWithDataTypeDefinition.length === dataTypeDescriptions.length);
213
- const dataTypeDefinitions = [];
214
- let index = 0;
215
- for (const dataValue of dataValuesWithDataTypeDefinition) {
216
- const dataTypeNodeId = dataTypeNodeIds[index];
217
- const dataTypeDescription = dataTypeDescriptions[index];
218
- /* istanbul ignore else */
219
- if (dataValue.statusCode === node_opcua_status_code_1.StatusCodes.Good) {
220
- const dataTypeDefinition = dataValue.value.value;
221
- if (dataTypeDefinition && dataTypeDefinition instanceof node_opcua_types_1.StructureDefinition) {
222
- const className = dataTypeDescription.browseName.name;
223
- dataTypeDefinitions.push({ className, dataTypeNodeId, dataTypeDefinition });
224
- }
225
- }
226
- else {
227
- debugLog("dataTypeNodeId ", dataTypeNodeId.toString(), " has no DataTypeDescription attribute", dataValue.statusCode.toString());
228
- }
229
- index++;
230
- }
231
- // to do put in logical order
232
- const dataTypeDefinitionsSorted = sortStructure(dataTypeDefinitions);
233
- if (doDebug) {
234
- debugLog("order ", dataTypeDefinitionsSorted.map((a) => a.className + " " + a.dataTypeNodeId).join(" -> "));
235
- }
236
- for (const { className, dataTypeNodeId, dataTypeDefinition } of dataTypeDefinitionsSorted) {
237
- // istanbul ignore next
238
- if (doDebug) {
239
- debugLog(chalk.yellow("--------------------------------------- "), className, dataTypeNodeId.toString());
240
- }
241
- if (dataTypeFactory.hasStructuredType(className)) {
242
- continue; // this structure has already been seen
243
- }
244
- // now fill typeDictionary
245
- try {
246
- const schema = yield (0, convert_data_type_definition_to_structuretype_schema_1.convertDataTypeDefinitionToStructureTypeSchema)(session, dataTypeNodeId, className, dataTypeDefinition, dataTypeFactory, cache);
247
- // istanbul ignore next
248
- if (doDebug) {
249
- debugLog(chalk.red("Registering "), chalk.cyan(className.padEnd(30, " ")), schema.dataTypeNodeId.toString());
250
- }
251
- const Constructor = (0, node_opcua_schemas_1.createDynamicObjectConstructor)(schema, dataTypeFactory);
252
- (0, node_opcua_assert_1.assert)(Constructor.schema === schema);
253
- }
254
- catch (err) {
255
- console.log("Constructor verification err: ", err.message);
256
- console.log("For this reason class " + className + " has not been registered");
257
- console.log(err);
258
- }
259
- }
260
- });
261
- }
262
- function _extractNodeIds(session, dataTypeDictionaryNodeId) {
263
- return __awaiter(this, void 0, void 0, function* () {
264
- const map = {};
265
- const dataTypeDescriptions = yield _getDataTypeDescriptions(session, dataTypeDictionaryNodeId);
266
- /* const dataTypeNodeIds = */
267
- yield _enrichWithDescriptionOf(session, dataTypeDescriptions);
268
- for (const dataTypeDescription of dataTypeDescriptions) {
269
- map[dataTypeDescription.browseName.name.toString()] = dataTypeDescription.encodings;
270
- }
271
- return {
272
- getDataTypeAndEncodingId(key) {
273
- return map[key] || null;
274
- }
275
- };
276
- });
277
- }
278
- function _extractDataTypeDictionary(session, d, dataTypeManager) {
279
- return __awaiter(this, void 0, void 0, function* () {
280
- const dataTypeDictionaryNodeId = d.reference.nodeId;
281
- const isDictionaryDeprecated = d.isDictionaryDeprecated; // await _readDeprecatedFlag(session, dataTypeDictionaryNodeId);
282
- const rawSchema = d.rawSchema; // DataValue = await session.read({ nodeId: dataTypeDictionaryNodeId, attributeId: AttributeIds.Value });
283
- const name = yield session.read({ nodeId: dataTypeDictionaryNodeId, attributeId: node_opcua_data_model_1.AttributeIds.BrowseName });
284
- const namespace = yield _readNamespaceUriProperty(session, dataTypeDictionaryNodeId);
285
- if (isDictionaryDeprecated || rawSchema.length === 0) {
286
- debugLog("DataTypeDictionary is deprecated or BSD schema stored in dataValue is null !", chalk.cyan(name.value.value.toString()), "namespace =", namespace);
287
- debugLog("let's use the new way (1.04) and let's crawl all dataTypes exposed by this name space");
288
- // dataType definition in store directly in UADataType under the definition attribute
289
- const dataTypeFactory2 = dataTypeManager.getDataTypeFactory(dataTypeDictionaryNodeId.namespace);
290
- if (!dataTypeFactory2) {
291
- throw new Error("cannot find dataTypeFactory for namespace " + dataTypeDictionaryNodeId.namespace);
292
- }
293
- yield _extractDataTypeDictionaryFromDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory2);
294
- return;
295
- }
296
- else {
297
- debugLog(" ----- Using old method for extracting schema => with BSD files");
298
- // old method ( until 1.03 )
299
- // one need to read the schema file store in the dataTypeDictionary node and parse it !
300
- /* istanbul ignore next */
301
- if (doDebug) {
302
- debugLog("---------------------------------------------");
303
- debugLog(rawSchema.toString());
304
- debugLog("---------------------------------------------");
305
- }
306
- const idProvider = yield _extractNodeIds(session, dataTypeDictionaryNodeId);
307
- const dataTypeFactory1 = dataTypeManager.getDataTypeFactory(dataTypeDictionaryNodeId.namespace);
308
- yield (0, node_opcua_schemas_1.parseBinaryXSDAsync)(rawSchema, idProvider, dataTypeFactory1);
309
- }
310
- });
311
- }
312
- function _exploreDataTypeDefinition(session, dataTypeDictionaryTypeNode, dataTypeFactory, namespaces) {
313
- return __awaiter(this, void 0, void 0, function* () {
314
- const nodeToBrowse = {
315
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
316
- includeSubtypes: false,
317
- nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Variable"),
318
- nodeId: dataTypeDictionaryTypeNode,
319
- referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasComponent"),
320
- resultMask: (0, node_opcua_data_model_1.makeResultMask)("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
321
- };
322
- const result = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodeToBrowse);
323
- const references = result.references || [];
324
- /* istanbul ignore next */
325
- if (references.length === 0) {
326
- return;
327
- }
328
- // request the Definition of each nodes
329
- const nodesToBrowse2 = references.map((ref) => {
330
- return {
331
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
332
- includeSubtypes: false,
333
- nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Object | Variable"),
334
- nodeId: ref.nodeId,
335
- referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasDescription"),
336
- resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
337
- };
338
- });
339
- const results2 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodesToBrowse2);
340
- const binaryEncodingNodeIds = results2.map((br) => {
341
- const defaultBin = br.references.filter((r) => r.browseName.toString() === "Default Binary");
342
- /* istanbul ignore next */
343
- if (defaultBin.length < 1) {
344
- return node_opcua_nodeid_1.ExpandedNodeId;
345
- }
346
- return node_opcua_nodeid_1.ExpandedNodeId.fromNodeId(defaultBin[0].nodeId, namespaces[defaultBin[0].nodeId.namespace]);
347
- });
348
- // follow now Default Binary <= [Has Encoding] = [DataType]
349
- /* istanbul ignore next */
350
- if (doDebug) {
351
- console.log(chalk.bgWhite.red("testing new constructors"));
352
- for (let i = 0; i < references.length; i++) {
353
- const ref = references[i];
354
- const binaryEncoding = binaryEncodingNodeIds[i];
355
- const name = ref.browseName.name.toString();
356
- if (doDebug) {
357
- debugLog(" type ", name.padEnd(30, " "), binaryEncoding.toString());
358
- }
359
- // let's verify that constructor is operational
360
- try {
361
- const constructor = dataTypeFactory.getStructureTypeConstructor(name);
362
- // xx const constructor = getOrCreateConstructor(name, dataTypeFactory, defaultBinary);
363
- const testObject = new constructor();
364
- debugLog(testObject.toString());
365
- }
366
- catch (err) {
367
- debugLog(" Error cannot construct Extension Object " + name);
368
- debugLog(" " + err.message);
369
- }
370
- }
371
- }
372
- });
373
- }
374
- const regexTargetNamespaceAttribute = /TargetNamespace="([^"]+)"|TargetNamespace='([^"]+)'/;
375
- function extractTargetNamespaceAttribute(xmlElement) {
376
- // warning TargetNamespace could have ' or " , Wago PLC for instance uses simple quotes
377
- const c2 = xmlElement.match(regexTargetNamespaceAttribute);
378
- if (c2) {
379
- return c2[1] || c2[2];
380
- }
381
- return "";
382
- }
383
- const regexNamespaceRef = /xmlns:(.*)=(("([^"]+)")|('([^']+)'))/;
384
- function extraNamespaceRef(attribute) {
385
- const c = attribute.match(regexNamespaceRef);
386
- if (c) {
387
- const xmlns = c[1];
388
- const namespace = c[3] || c[4];
389
- return { xmlns, namespace };
390
- }
391
- return null;
392
- }
393
- /**
394
- * Extract all custom dataType
395
- * @param session
396
- * @param dataTypeManager
397
- * @async
398
- */
399
- function populateDataTypeManager103(session, dataTypeManager) {
400
- var _a;
401
- return __awaiter(this, void 0, void 0, function* () {
402
- debugLog("in ... populateDataTypeManager");
403
- // read namespace array
404
- const dataValueNamespaceArray = yield session.read({
405
- attributeId: node_opcua_data_model_1.AttributeIds.Value,
406
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)("Server_NamespaceArray")
407
- });
408
- const namespaceArray = dataValueNamespaceArray.value.value;
409
- // istanbul ignore next
410
- if (!namespaceArray) {
411
- debugLog("session: cannot read Server_NamespaceArray");
412
- // throw new Error("Cannot get Server_NamespaceArray as a array of string");
413
- return;
414
- }
415
- // istanbul ignore next
416
- if (doDebug) {
417
- debugLog("namespaceArray ", namespaceArray.map((a, index) => " " + index.toString().padEnd(3) + ":" + a).join(" "));
418
- }
419
- if (dataValueNamespaceArray.statusCode === node_opcua_status_code_1.StatusCodes.Good && namespaceArray && namespaceArray.length > 0) {
420
- dataTypeManager.setNamespaceArray(namespaceArray);
421
- for (let namespaceIndex = 1; namespaceIndex < namespaceArray.length; namespaceIndex++) {
422
- if (!dataTypeManager.hasDataTypeFactory(namespaceIndex)) {
423
- const dataTypeFactory1 = new node_opcua_factory_1.DataTypeFactory([(0, node_opcua_factory_1.getStandardDataTypeFactory)()]);
424
- dataTypeManager.registerDataTypeFactory(namespaceIndex, dataTypeFactory1);
425
- }
426
- }
427
- }
428
- /// to do :: may be not useful
429
- if (!dataValueNamespaceArray.value.value && dataTypeManager.namespaceArray.length === 0) {
430
- dataTypeManager.setNamespaceArray([]);
431
- }
432
- const dataTypeDictionaryType = (0, node_opcua_nodeid_1.resolveNodeId)("DataTypeDictionaryType");
433
- // DataType/OPCBinary => i=93 [OPCBinarySchema_TypeSystem]
434
- // "OPC Binary"[DataSystemType]
435
- const opcBinaryNodeId = (0, node_opcua_nodeid_1.resolveNodeId)("OPCBinarySchema_TypeSystem");
436
- // let find all DataType dictionary node corresponding to a given namespace
437
- // (have DataTypeDictionaryType)
438
- const nodeToBrowse = {
439
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
440
- includeSubtypes: false,
441
- nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Variable"),
442
- nodeId: opcBinaryNodeId,
443
- referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasComponent"),
444
- resultMask: (0, node_opcua_data_model_1.makeResultMask)("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
445
- };
446
- const result = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodeToBrowse);
447
- if (doDebug) {
448
- debugLog(result.statusCode.toString());
449
- debugLog((_a = result.references) === null || _a === void 0 ? void 0 : _a.map((r) => { var _a; return (_a = r.browseName) === null || _a === void 0 ? void 0 : _a.toString(); }).join(" "));
450
- }
451
- // filter nodes that have the expected namespace Index
452
- // ( more specifically we want to filter out DataStructure from namespace 0)
453
- // we also want to keep only object of type DataTypeDictionaryType
454
- const references = result.references.filter((e) => e.nodeId.namespace !== 0 && (0, node_opcua_nodeid_1.sameNodeId)(e.typeDefinition, dataTypeDictionaryType));
455
- debugLog(`found ${references.length} dictionary`);
456
- function putInCorrectOrder() {
457
- return __awaiter(this, void 0, void 0, function* () {
458
- const infos = [];
459
- const innerMap = {};
460
- for (const reference of references) {
461
- const dataTypeDictionaryNodeId = reference.nodeId;
462
- const isDictionaryDeprecated = yield _readDeprecatedFlag(session, dataTypeDictionaryNodeId);
463
- const rawSchemaDataValue = yield session.read({
464
- attributeId: node_opcua_data_model_1.AttributeIds.Value,
465
- nodeId: dataTypeDictionaryNodeId
466
- });
467
- const rawSchema = rawSchemaDataValue.value.value ? rawSchemaDataValue.value.value.toString() : "";
468
- const info = {
469
- dataTypeDictionaryNodeId,
470
- dependencies: {},
471
- isDictionaryDeprecated,
472
- rawSchema,
473
- reference,
474
- targetNamespace: ""
475
- };
476
- infos.push(info);
477
- if (!isDictionaryDeprecated && rawSchema.length > 0) {
478
- if (doDebug) {
479
- console.log("schema", rawSchema);
480
- }
481
- const matches = rawSchema.match(/<opc:TypeDictionary([^>]+)>/);
482
- if (matches) {
483
- // extract xml:NS="namespace" from attribute list
484
- // for instance:
485
- // <opc:TypeDictionary
486
- // xmlns:opc="http://opcfoundation.org/BinarySchema/"
487
- // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
488
- // xmlns:ua="http://opcfoundation.org/UA/"
489
- // xmlns:tns="urn:SomeName:Ua:Types:GlobalTypes"
490
- // DefaultByteOrder="LittleEndian"
491
- // TargetNamespace="urn:SomeName:Ua:Types:GlobalTypes">
492
- const typeDictionaryElementAttributes = matches[1];
493
- info.targetNamespace = extractTargetNamespaceAttribute(typeDictionaryElementAttributes);
494
- const nsKeyNamespace = {};
495
- for (const attribute of typeDictionaryElementAttributes.split(" ")) {
496
- const r = extraNamespaceRef(attribute);
497
- if (r) {
498
- const { xmlns, namespace } = r;
499
- nsKeyNamespace[xmlns] = namespace;
500
- debugLog("xxxx ns= ", xmlns, "=>", namespace);
501
- }
502
- }
503
- info.dependencies = nsKeyNamespace;
504
- debugLog("xxx targetNamespace = ", info.targetNamespace);
505
- innerMap[info.targetNamespace] = info;
506
- }
507
- }
508
- else {
509
- // may be 1.04 => the rawSchema is no more needed in new version
510
- info.targetNamespace = namespaceArray[dataTypeDictionaryNodeId.namespace];
511
- debugLog("xxx targetNamespace = ", info.targetNamespace);
512
- innerMap[info.targetNamespace] = info;
513
- }
514
- // assert(info.targetNamespace.length !== 0);
515
- }
516
- // ----------------------------------
517
- const orderedList = [];
518
- const visited = {};
519
- function explore(d) {
520
- if (visited[d.targetNamespace]) {
521
- return;
522
- }
523
- visited[d.targetNamespace] = 1;
524
- for (const [xmlns, namespace] of Object.entries(d.dependencies)) {
525
- if (!innerMap[namespace] || namespace === d.targetNamespace) {
526
- continue;
527
- }
528
- explore(innerMap[namespace]);
529
- }
530
- orderedList.push(d);
531
- }
532
- for (const d of infos) {
533
- explore(d);
534
- }
535
- debugLog(" Ordered List = ", orderedList.map((a) => a.targetNamespace).join(" "));
536
- return orderedList;
537
- });
538
- }
539
- const dataTypeDictionaryInfo = yield putInCorrectOrder();
540
- // setup dependencies
541
- const map = {};
542
- for (const d of dataTypeDictionaryInfo) {
543
- map[d.targetNamespace] = d;
544
- debugLog(" fixing based dataTypeFactory dependencies for ", d.targetNamespace, "index = ", d.dataTypeDictionaryNodeId.namespace);
545
- const baseDataFactories = [(0, node_opcua_factory_1.getStandardDataTypeFactory)()];
546
- for (const namespace of Object.values(d.dependencies)) {
547
- if (namespace === d.targetNamespace) {
548
- continue;
549
- }
550
- const baseDataFactory = map[namespace];
551
- if (!baseDataFactory) {
552
- // xx console.log("xxxxx baseDataFactory = ", namespace);
553
- continue;
554
- }
555
- const namespaceIndex = baseDataFactory.dataTypeDictionaryNodeId.namespace;
556
- if (dataTypeManager.hasDataTypeFactory(namespaceIndex)) {
557
- const dep = dataTypeManager.getDataTypeFactory(namespaceIndex);
558
- baseDataFactories.push(dep);
559
- debugLog(" considering , ", baseDataFactory.targetNamespace, "index = ", baseDataFactory.dataTypeDictionaryNodeId.namespace);
560
- }
561
- }
562
- const dataTypeFactory = dataTypeManager.getDataTypeFactory(d.dataTypeDictionaryNodeId.namespace);
563
- if (dataTypeFactory) {
564
- dataTypeFactory.repairBaseDataFactories(baseDataFactories);
565
- }
566
- }
567
- // --------------------
568
- // now investigate DataTypeDescriptionType
569
- function processReferenceOnDataTypeDictionaryType(d) {
570
- return __awaiter(this, void 0, void 0, function* () {
571
- debugLog(chalk.cyan("processReferenceOnDataTypeDictionaryType on "), d.targetNamespace);
572
- const ref = d.reference;
573
- const dataTypeDictionaryNodeId = d.reference.nodeId;
574
- yield _extractDataTypeDictionary(session, d, dataTypeManager);
575
- /* istanbul ignore next */
576
- if (doDebug) {
577
- debugLog(chalk.bgWhite(" => "), ref.browseName.toString(), ref.nodeId.toString());
578
- }
579
- const dataTypeFactory = dataTypeManager.getDataTypeFactoryForNamespace(dataTypeDictionaryNodeId.namespace);
580
- yield _exploreDataTypeDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory, dataTypeManager.namespaceArray);
581
- });
582
- }
583
- // https://medium.com/swlh/dealing-with-multiple-promises-in-javascript-41d6c21f20ff
584
- for (const d of dataTypeDictionaryInfo) {
585
- try {
586
- yield processReferenceOnDataTypeDictionaryType(d).catch((e) => {
587
- console.log(e);
588
- debugLog("processReferenceOnDataTypeDictionaryType has failed ");
589
- debugLog("Error", e.message);
590
- debugLog(e);
591
- return e;
592
- });
593
- }
594
- catch (err) {
595
- debugLog(chalk.red("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "), err);
596
- }
597
- }
598
- debugLog("out ... populateDataTypeManager");
599
- });
600
- }
601
- exports.populateDataTypeManager103 = populateDataTypeManager103;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.populateDataTypeManager103 = void 0;
13
+ /* eslint-disable max-statements */
14
+ // tslint:disable: no-console
15
+ /**
16
+ * @module node-opcua-client-dynamic-extension-object
17
+ */
18
+ const chalk = require("chalk");
19
+ const node_opcua_assert_1 = require("node-opcua-assert");
20
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
21
+ const node_opcua_debug_1 = require("node-opcua-debug");
22
+ const node_opcua_factory_1 = require("node-opcua-factory");
23
+ const node_opcua_nodeid_1 = require("node-opcua-nodeid");
24
+ const node_opcua_pseudo_session_1 = require("node-opcua-pseudo-session");
25
+ const node_opcua_schemas_1 = require("node-opcua-schemas");
26
+ const node_opcua_service_browse_1 = require("node-opcua-service-browse");
27
+ const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
28
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
29
+ const node_opcua_types_1 = require("node-opcua-types");
30
+ const convert_data_type_definition_to_structuretype_schema_1 = require("../convert_data_type_definition_to_structuretype_schema");
31
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
32
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
33
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
34
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
35
+ // DataType
36
+ // | 1
37
+ // | n
38
+ // +- HasEncoding-> "Default Binary" (O)[DataTypeEncodingType]
39
+ // |
40
+ // +-- HasDescription -> "MyItemType" (V)[DataTypeDescriptionType]
41
+ // |
42
+ // +- ComponentOf -> Schema(V) []
43
+ // |
44
+ // +- ComponentOf -> OPC Binary(V)[DataTypeSystemType]
45
+ //
46
+ // Note that in 1.04 compliant server, DataType definition might be available
47
+ // in a DataTypeDefinition attributes of the DataType object
48
+ // However this is a brand new aspect of the specification and is not widely implemented
49
+ // it is also optional
50
+ // It will takes time for old opcua server to be refurbished and we may have to
51
+ // keep the current method to access type definition from embedded xsd.
52
+ //
53
+ function _readDeprecatedFlag(session, dataTypeDictionary) {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ const browsePath = (0, node_opcua_service_translate_browse_path_1.makeBrowsePath)(dataTypeDictionary, ".Deprecated");
56
+ const a = yield session.translateBrowsePath(browsePath);
57
+ /* istanbul ignore next */
58
+ if (!a.targets || a.targets.length === 0) {
59
+ // the server is probably version < 1.04.
60
+ debugLog("Cannot find Deprecated property for dataTypeDictionary " + dataTypeDictionary.toString());
61
+ return false;
62
+ }
63
+ const deprecatedFlagNodeId = a.targets[0].targetId;
64
+ const dataValue = yield session.read({ nodeId: deprecatedFlagNodeId, attributeId: node_opcua_data_model_1.AttributeIds.Value });
65
+ return dataValue.value.value;
66
+ });
67
+ }
68
+ function _readNamespaceUriProperty(session, dataTypeDictionary) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ const a = yield session.translateBrowsePath((0, node_opcua_service_translate_browse_path_1.makeBrowsePath)(dataTypeDictionary, ".NamespaceUri"));
71
+ /* istanbul ignore next */
72
+ if (!a.targets || a.targets.length === 0) {
73
+ return "??dataTypeDictionary doesn't expose NamespaceUri property??";
74
+ }
75
+ const namespaceUriProp = a.targets[0].targetId;
76
+ const dataValue = yield session.read({ nodeId: namespaceUriProp, attributeId: node_opcua_data_model_1.AttributeIds.Value });
77
+ return dataValue.value.value || "<not set>";
78
+ });
79
+ }
80
+ function _getDataTypeDescriptions(session, dataTypeDictionaryNodeId) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const nodeToBrowse2 = {
83
+ browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
84
+ includeSubtypes: false,
85
+ nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Variable"),
86
+ nodeId: dataTypeDictionaryNodeId,
87
+ referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasComponent"),
88
+ // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
89
+ resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId | BrowseName")
90
+ };
91
+ const result2 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodeToBrowse2);
92
+ result2.references = result2.references || [];
93
+ return result2.references.map((r) => ({ nodeId: r.nodeId, browseName: r.browseName }));
94
+ });
95
+ }
96
+ function _enrichWithDescriptionOf(session, dataTypeDescriptions) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ const nodesToBrowse3 = [];
99
+ for (const ref of dataTypeDescriptions) {
100
+ ref.browseName.toString();
101
+ nodesToBrowse3.push({
102
+ browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
103
+ includeSubtypes: false,
104
+ nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Object"),
105
+ nodeId: ref.nodeId.toString(),
106
+ referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasDescription"),
107
+ // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
108
+ resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId")
109
+ });
110
+ }
111
+ /* istanbul ignore next */
112
+ if (nodesToBrowse3.length === 0) {
113
+ return [];
114
+ }
115
+ const results3 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodesToBrowse3);
116
+ const binaryEncodings = [];
117
+ const nodesToBrowseDataType = [];
118
+ let i = 0;
119
+ for (const result3 of results3) {
120
+ const dataTypeDescription = dataTypeDescriptions[i++];
121
+ result3.references = result3.references || [];
122
+ if (result3.references.length !== 1) {
123
+ warningLog("_enrichWithDescriptionOf : expecting 1 reference for ", dataTypeDescription.browseName.toString());
124
+ continue;
125
+ }
126
+ for (const ref of result3.references) {
127
+ const binaryEncodingNodeId = ref.nodeId;
128
+ dataTypeDescription.encodings = dataTypeDescription.encodings || {
129
+ binaryEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
130
+ dataTypeNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
131
+ jsonEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
132
+ xmlEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId
133
+ };
134
+ dataTypeDescription.encodings.binaryEncodingNodeId = binaryEncodingNodeId;
135
+ binaryEncodings.push(binaryEncodingNodeId);
136
+ nodesToBrowseDataType.push({
137
+ browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
138
+ includeSubtypes: false,
139
+ nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("DataType"),
140
+ nodeId: ref.nodeId.toString(),
141
+ referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasEncoding"),
142
+ // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
143
+ resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId | BrowseName")
144
+ });
145
+ }
146
+ }
147
+ const dataTypeNodeIds = [];
148
+ if (nodesToBrowseDataType.length > 0) {
149
+ const results4 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodesToBrowseDataType);
150
+ i = 0;
151
+ for (const result4 of results4) {
152
+ result4.references = result4.references || [];
153
+ /* istanbul ignore next */
154
+ if (result4.references.length !== 1) {
155
+ console.log("What's going on ?", result4.toString());
156
+ }
157
+ for (const ref of result4.references) {
158
+ const dataTypeNodeId = ref.nodeId;
159
+ dataTypeNodeIds.push(dataTypeNodeId);
160
+ const dataTypeDescription = dataTypeDescriptions[i++];
161
+ dataTypeDescription.encodings.dataTypeNodeId = dataTypeNodeId;
162
+ }
163
+ }
164
+ }
165
+ return dataTypeNodeIds;
166
+ });
167
+ }
168
+ function sortStructure(dataTypeDefinitions) {
169
+ const dataTypeDefinitionsSorted = [];
170
+ const _visited = {};
171
+ const _map = {};
172
+ for (const d of dataTypeDefinitions) {
173
+ _map[d.dataTypeNodeId.toString()] = d;
174
+ }
175
+ function _visit(d) {
176
+ const hash = d.dataTypeNodeId.toString();
177
+ if (_visited[hash]) {
178
+ return;
179
+ }
180
+ _visited[hash] = d;
181
+ const bbb = _map[d.dataTypeDefinition.baseDataType.toString()];
182
+ if (bbb) {
183
+ _visit(bbb);
184
+ }
185
+ for (const f of d.dataTypeDefinition.fields || []) {
186
+ const ddd = _map[f.dataType.toString()];
187
+ if (!ddd) {
188
+ continue;
189
+ }
190
+ _visit(ddd);
191
+ }
192
+ dataTypeDefinitionsSorted.push(d);
193
+ }
194
+ for (const d of dataTypeDefinitions) {
195
+ _visit(d);
196
+ }
197
+ return dataTypeDefinitionsSorted;
198
+ }
199
+ function _extractDataTypeDictionaryFromDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory) {
200
+ return __awaiter(this, void 0, void 0, function* () {
201
+ (0, node_opcua_assert_1.assert)(dataTypeFactory, "expecting a dataTypeFactory");
202
+ const dataTypeDescriptions = yield _getDataTypeDescriptions(session, dataTypeDictionaryNodeId);
203
+ const dataTypeNodeIds = yield _enrichWithDescriptionOf(session, dataTypeDescriptions);
204
+ // now read DataTypeDefinition attributes of all the dataTypeNodeIds, this will only contains concrete structure
205
+ const nodesToRead = dataTypeNodeIds.map((nodeId) => ({
206
+ attributeId: node_opcua_data_model_1.AttributeIds.DataTypeDefinition,
207
+ nodeId
208
+ }));
209
+ const cache = {};
210
+ const dataValuesWithDataTypeDefinition = nodesToRead.length > 0 ? yield session.read(nodesToRead) : [];
211
+ // in some circumstances like Euromap, this assert fails:
212
+ // assert(dataValuesWithDataTypeDefinition.length === dataTypeDescriptions.length);
213
+ const dataTypeDefinitions = [];
214
+ let index = 0;
215
+ for (const dataValue of dataValuesWithDataTypeDefinition) {
216
+ const dataTypeNodeId = dataTypeNodeIds[index];
217
+ const dataTypeDescription = dataTypeDescriptions[index];
218
+ /* istanbul ignore else */
219
+ if (dataValue.statusCode === node_opcua_status_code_1.StatusCodes.Good) {
220
+ const dataTypeDefinition = dataValue.value.value;
221
+ if (dataTypeDefinition && dataTypeDefinition instanceof node_opcua_types_1.StructureDefinition) {
222
+ const className = dataTypeDescription.browseName.name;
223
+ dataTypeDefinitions.push({ className, dataTypeNodeId, dataTypeDefinition });
224
+ }
225
+ }
226
+ else {
227
+ debugLog("dataTypeNodeId ", dataTypeNodeId.toString(), " has no DataTypeDescription attribute", dataValue.statusCode.toString());
228
+ }
229
+ index++;
230
+ }
231
+ // to do put in logical order
232
+ const dataTypeDefinitionsSorted = sortStructure(dataTypeDefinitions);
233
+ if (doDebug) {
234
+ debugLog("order ", dataTypeDefinitionsSorted.map((a) => a.className + " " + a.dataTypeNodeId).join(" -> "));
235
+ }
236
+ for (const { className, dataTypeNodeId, dataTypeDefinition } of dataTypeDefinitionsSorted) {
237
+ // istanbul ignore next
238
+ if (doDebug) {
239
+ debugLog(chalk.yellow("--------------------------------------- "), className, dataTypeNodeId.toString());
240
+ }
241
+ if (dataTypeFactory.hasStructuredType(className)) {
242
+ continue; // this structure has already been seen
243
+ }
244
+ // now fill typeDictionary
245
+ try {
246
+ const schema = yield (0, convert_data_type_definition_to_structuretype_schema_1.convertDataTypeDefinitionToStructureTypeSchema)(session, dataTypeNodeId, className, dataTypeDefinition, dataTypeFactory, cache);
247
+ // istanbul ignore next
248
+ if (doDebug) {
249
+ debugLog(chalk.red("Registering "), chalk.cyan(className.padEnd(30, " ")), schema.dataTypeNodeId.toString());
250
+ }
251
+ const Constructor = (0, node_opcua_schemas_1.createDynamicObjectConstructor)(schema, dataTypeFactory);
252
+ (0, node_opcua_assert_1.assert)(Constructor.schema === schema);
253
+ }
254
+ catch (err) {
255
+ console.log("Constructor verification err: ", err.message);
256
+ console.log("For this reason class " + className + " has not been registered");
257
+ console.log(err);
258
+ }
259
+ }
260
+ });
261
+ }
262
+ function _extractNodeIds(session, dataTypeDictionaryNodeId) {
263
+ return __awaiter(this, void 0, void 0, function* () {
264
+ const map = {};
265
+ const dataTypeDescriptions = yield _getDataTypeDescriptions(session, dataTypeDictionaryNodeId);
266
+ /* const dataTypeNodeIds = */
267
+ yield _enrichWithDescriptionOf(session, dataTypeDescriptions);
268
+ for (const dataTypeDescription of dataTypeDescriptions) {
269
+ map[dataTypeDescription.browseName.name.toString()] = dataTypeDescription.encodings;
270
+ }
271
+ return {
272
+ getDataTypeAndEncodingId(key) {
273
+ return map[key] || null;
274
+ }
275
+ };
276
+ });
277
+ }
278
+ function _extractDataTypeDictionary(session, d, dataTypeManager) {
279
+ return __awaiter(this, void 0, void 0, function* () {
280
+ const dataTypeDictionaryNodeId = d.reference.nodeId;
281
+ const isDictionaryDeprecated = d.isDictionaryDeprecated; // await _readDeprecatedFlag(session, dataTypeDictionaryNodeId);
282
+ const rawSchema = d.rawSchema; // DataValue = await session.read({ nodeId: dataTypeDictionaryNodeId, attributeId: AttributeIds.Value });
283
+ const name = yield session.read({ nodeId: dataTypeDictionaryNodeId, attributeId: node_opcua_data_model_1.AttributeIds.BrowseName });
284
+ const namespace = yield _readNamespaceUriProperty(session, dataTypeDictionaryNodeId);
285
+ if (isDictionaryDeprecated || rawSchema.length === 0) {
286
+ debugLog("DataTypeDictionary is deprecated or BSD schema stored in dataValue is null !", chalk.cyan(name.value.value.toString()), "namespace =", namespace);
287
+ debugLog("let's use the new way (1.04) and let's crawl all dataTypes exposed by this name space");
288
+ // dataType definition in store directly in UADataType under the definition attribute
289
+ const dataTypeFactory2 = dataTypeManager.getDataTypeFactory(dataTypeDictionaryNodeId.namespace);
290
+ if (!dataTypeFactory2) {
291
+ throw new Error("cannot find dataTypeFactory for namespace " + dataTypeDictionaryNodeId.namespace);
292
+ }
293
+ yield _extractDataTypeDictionaryFromDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory2);
294
+ return;
295
+ }
296
+ else {
297
+ debugLog(" ----- Using old method for extracting schema => with BSD files");
298
+ // old method ( until 1.03 )
299
+ // one need to read the schema file store in the dataTypeDictionary node and parse it !
300
+ /* istanbul ignore next */
301
+ if (doDebug) {
302
+ debugLog("---------------------------------------------");
303
+ debugLog(rawSchema.toString());
304
+ debugLog("---------------------------------------------");
305
+ }
306
+ const idProvider = yield _extractNodeIds(session, dataTypeDictionaryNodeId);
307
+ const dataTypeFactory1 = dataTypeManager.getDataTypeFactory(dataTypeDictionaryNodeId.namespace);
308
+ yield (0, node_opcua_schemas_1.parseBinaryXSDAsync)(rawSchema, idProvider, dataTypeFactory1);
309
+ }
310
+ });
311
+ }
312
+ function _exploreDataTypeDefinition(session, dataTypeDictionaryTypeNode, dataTypeFactory, namespaces) {
313
+ return __awaiter(this, void 0, void 0, function* () {
314
+ const nodeToBrowse = {
315
+ browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
316
+ includeSubtypes: false,
317
+ nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Variable"),
318
+ nodeId: dataTypeDictionaryTypeNode,
319
+ referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasComponent"),
320
+ resultMask: (0, node_opcua_data_model_1.makeResultMask)("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
321
+ };
322
+ const result = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodeToBrowse);
323
+ const references = result.references || [];
324
+ /* istanbul ignore next */
325
+ if (references.length === 0) {
326
+ return;
327
+ }
328
+ // request the Definition of each nodes
329
+ const nodesToBrowse2 = references.map((ref) => {
330
+ return {
331
+ browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
332
+ includeSubtypes: false,
333
+ nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Object | Variable"),
334
+ nodeId: ref.nodeId,
335
+ referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasDescription"),
336
+ resultMask: (0, node_opcua_data_model_1.makeResultMask)("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
337
+ };
338
+ });
339
+ const results2 = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodesToBrowse2);
340
+ const binaryEncodingNodeIds = results2.map((br) => {
341
+ const defaultBin = br.references.filter((r) => r.browseName.toString() === "Default Binary");
342
+ /* istanbul ignore next */
343
+ if (defaultBin.length < 1) {
344
+ return node_opcua_nodeid_1.ExpandedNodeId;
345
+ }
346
+ return node_opcua_nodeid_1.ExpandedNodeId.fromNodeId(defaultBin[0].nodeId, namespaces[defaultBin[0].nodeId.namespace]);
347
+ });
348
+ // follow now Default Binary <= [Has Encoding] = [DataType]
349
+ /* istanbul ignore next */
350
+ if (doDebug) {
351
+ console.log(chalk.bgWhite.red("testing new constructors"));
352
+ for (let i = 0; i < references.length; i++) {
353
+ const ref = references[i];
354
+ const binaryEncoding = binaryEncodingNodeIds[i];
355
+ const name = ref.browseName.name.toString();
356
+ if (doDebug) {
357
+ debugLog(" type ", name.padEnd(30, " "), binaryEncoding.toString());
358
+ }
359
+ // let's verify that constructor is operational
360
+ try {
361
+ const constructor = dataTypeFactory.getStructureTypeConstructor(name);
362
+ // xx const constructor = getOrCreateConstructor(name, dataTypeFactory, defaultBinary);
363
+ const testObject = new constructor();
364
+ debugLog(testObject.toString());
365
+ }
366
+ catch (err) {
367
+ debugLog(" Error cannot construct Extension Object " + name);
368
+ debugLog(" " + err.message);
369
+ }
370
+ }
371
+ }
372
+ });
373
+ }
374
+ const regexTargetNamespaceAttribute = /TargetNamespace="([^"]+)"|TargetNamespace='([^"]+)'/;
375
+ function extractTargetNamespaceAttribute(xmlElement) {
376
+ // warning TargetNamespace could have ' or " , Wago PLC for instance uses simple quotes
377
+ const c2 = xmlElement.match(regexTargetNamespaceAttribute);
378
+ if (c2) {
379
+ return c2[1] || c2[2];
380
+ }
381
+ return "";
382
+ }
383
+ const regexNamespaceRef = /xmlns:(.*)=(("([^"]+)")|('([^']+)'))/;
384
+ function extraNamespaceRef(attribute) {
385
+ const c = attribute.match(regexNamespaceRef);
386
+ if (c) {
387
+ const xmlns = c[1];
388
+ const namespace = c[3] || c[4];
389
+ return { xmlns, namespace };
390
+ }
391
+ return null;
392
+ }
393
+ /**
394
+ * Extract all custom dataType
395
+ * @param session
396
+ * @param dataTypeManager
397
+ * @async
398
+ */
399
+ function populateDataTypeManager103(session, dataTypeManager) {
400
+ var _a;
401
+ return __awaiter(this, void 0, void 0, function* () {
402
+ debugLog("in ... populateDataTypeManager");
403
+ // read namespace array
404
+ const dataValueNamespaceArray = yield session.read({
405
+ attributeId: node_opcua_data_model_1.AttributeIds.Value,
406
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)("Server_NamespaceArray")
407
+ });
408
+ const namespaceArray = dataValueNamespaceArray.value.value;
409
+ // istanbul ignore next
410
+ if (!namespaceArray) {
411
+ debugLog("session: cannot read Server_NamespaceArray");
412
+ // throw new Error("Cannot get Server_NamespaceArray as a array of string");
413
+ return;
414
+ }
415
+ // istanbul ignore next
416
+ if (doDebug) {
417
+ debugLog("namespaceArray ", namespaceArray.map((a, index) => " " + index.toString().padEnd(3) + ":" + a).join(" "));
418
+ }
419
+ if (dataValueNamespaceArray.statusCode === node_opcua_status_code_1.StatusCodes.Good && namespaceArray && namespaceArray.length > 0) {
420
+ dataTypeManager.setNamespaceArray(namespaceArray);
421
+ for (let namespaceIndex = 1; namespaceIndex < namespaceArray.length; namespaceIndex++) {
422
+ if (!dataTypeManager.hasDataTypeFactory(namespaceIndex)) {
423
+ const dataTypeFactory1 = new node_opcua_factory_1.DataTypeFactory([(0, node_opcua_factory_1.getStandardDataTypeFactory)()]);
424
+ dataTypeManager.registerDataTypeFactory(namespaceIndex, dataTypeFactory1);
425
+ }
426
+ }
427
+ }
428
+ /// to do :: may be not useful
429
+ if (!dataValueNamespaceArray.value.value && dataTypeManager.namespaceArray.length === 0) {
430
+ dataTypeManager.setNamespaceArray([]);
431
+ }
432
+ const dataTypeDictionaryType = (0, node_opcua_nodeid_1.resolveNodeId)("DataTypeDictionaryType");
433
+ // DataType/OPCBinary => i=93 [OPCBinarySchema_TypeSystem]
434
+ // "OPC Binary"[DataSystemType]
435
+ const opcBinaryNodeId = (0, node_opcua_nodeid_1.resolveNodeId)("OPCBinarySchema_TypeSystem");
436
+ // let find all DataType dictionary node corresponding to a given namespace
437
+ // (have DataTypeDictionaryType)
438
+ const nodeToBrowse = {
439
+ browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
440
+ includeSubtypes: false,
441
+ nodeClassMask: (0, node_opcua_data_model_1.makeNodeClassMask)("Variable"),
442
+ nodeId: opcBinaryNodeId,
443
+ referenceTypeId: (0, node_opcua_nodeid_1.resolveNodeId)("HasComponent"),
444
+ resultMask: (0, node_opcua_data_model_1.makeResultMask)("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
445
+ };
446
+ const result = yield (0, node_opcua_pseudo_session_1.browseAll)(session, nodeToBrowse);
447
+ if (doDebug) {
448
+ debugLog(result.statusCode.toString());
449
+ debugLog((_a = result.references) === null || _a === void 0 ? void 0 : _a.map((r) => { var _a; return (_a = r.browseName) === null || _a === void 0 ? void 0 : _a.toString(); }).join(" "));
450
+ }
451
+ // filter nodes that have the expected namespace Index
452
+ // ( more specifically we want to filter out DataStructure from namespace 0)
453
+ // we also want to keep only object of type DataTypeDictionaryType
454
+ const references = result.references.filter((e) => e.nodeId.namespace !== 0 && (0, node_opcua_nodeid_1.sameNodeId)(e.typeDefinition, dataTypeDictionaryType));
455
+ debugLog(`found ${references.length} dictionary`);
456
+ function putInCorrectOrder() {
457
+ return __awaiter(this, void 0, void 0, function* () {
458
+ const infos = [];
459
+ const innerMap = {};
460
+ for (const reference of references) {
461
+ const dataTypeDictionaryNodeId = reference.nodeId;
462
+ const isDictionaryDeprecated = yield _readDeprecatedFlag(session, dataTypeDictionaryNodeId);
463
+ const rawSchemaDataValue = yield session.read({
464
+ attributeId: node_opcua_data_model_1.AttributeIds.Value,
465
+ nodeId: dataTypeDictionaryNodeId
466
+ });
467
+ const rawSchema = rawSchemaDataValue.value.value ? rawSchemaDataValue.value.value.toString() : "";
468
+ const info = {
469
+ dataTypeDictionaryNodeId,
470
+ dependencies: {},
471
+ isDictionaryDeprecated,
472
+ rawSchema,
473
+ reference,
474
+ targetNamespace: ""
475
+ };
476
+ infos.push(info);
477
+ if (!isDictionaryDeprecated && rawSchema.length > 0) {
478
+ if (doDebug) {
479
+ console.log("schema", rawSchema);
480
+ }
481
+ const matches = rawSchema.match(/<opc:TypeDictionary([^>]+)>/);
482
+ if (matches) {
483
+ // extract xml:NS="namespace" from attribute list
484
+ // for instance:
485
+ // <opc:TypeDictionary
486
+ // xmlns:opc="http://opcfoundation.org/BinarySchema/"
487
+ // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
488
+ // xmlns:ua="http://opcfoundation.org/UA/"
489
+ // xmlns:tns="urn:SomeName:Ua:Types:GlobalTypes"
490
+ // DefaultByteOrder="LittleEndian"
491
+ // TargetNamespace="urn:SomeName:Ua:Types:GlobalTypes">
492
+ const typeDictionaryElementAttributes = matches[1];
493
+ info.targetNamespace = extractTargetNamespaceAttribute(typeDictionaryElementAttributes);
494
+ const nsKeyNamespace = {};
495
+ for (const attribute of typeDictionaryElementAttributes.split(" ")) {
496
+ const r = extraNamespaceRef(attribute);
497
+ if (r) {
498
+ const { xmlns, namespace } = r;
499
+ nsKeyNamespace[xmlns] = namespace;
500
+ debugLog("xxxx ns= ", xmlns, "=>", namespace);
501
+ }
502
+ }
503
+ info.dependencies = nsKeyNamespace;
504
+ debugLog("xxx targetNamespace = ", info.targetNamespace);
505
+ innerMap[info.targetNamespace] = info;
506
+ }
507
+ }
508
+ else {
509
+ // may be 1.04 => the rawSchema is no more needed in new version
510
+ info.targetNamespace = namespaceArray[dataTypeDictionaryNodeId.namespace];
511
+ debugLog("xxx targetNamespace = ", info.targetNamespace);
512
+ innerMap[info.targetNamespace] = info;
513
+ }
514
+ // assert(info.targetNamespace.length !== 0);
515
+ }
516
+ // ----------------------------------
517
+ const orderedList = [];
518
+ const visited = {};
519
+ function explore(d) {
520
+ if (visited[d.targetNamespace]) {
521
+ return;
522
+ }
523
+ visited[d.targetNamespace] = 1;
524
+ for (const [xmlns, namespace] of Object.entries(d.dependencies)) {
525
+ if (!innerMap[namespace] || namespace === d.targetNamespace) {
526
+ continue;
527
+ }
528
+ explore(innerMap[namespace]);
529
+ }
530
+ orderedList.push(d);
531
+ }
532
+ for (const d of infos) {
533
+ explore(d);
534
+ }
535
+ debugLog(" Ordered List = ", orderedList.map((a) => a.targetNamespace).join(" "));
536
+ return orderedList;
537
+ });
538
+ }
539
+ const dataTypeDictionaryInfo = yield putInCorrectOrder();
540
+ // setup dependencies
541
+ const map = {};
542
+ for (const d of dataTypeDictionaryInfo) {
543
+ map[d.targetNamespace] = d;
544
+ debugLog(" fixing based dataTypeFactory dependencies for ", d.targetNamespace, "index = ", d.dataTypeDictionaryNodeId.namespace);
545
+ const baseDataFactories = [(0, node_opcua_factory_1.getStandardDataTypeFactory)()];
546
+ for (const namespace of Object.values(d.dependencies)) {
547
+ if (namespace === d.targetNamespace) {
548
+ continue;
549
+ }
550
+ const baseDataFactory = map[namespace];
551
+ if (!baseDataFactory) {
552
+ // xx console.log("xxxxx baseDataFactory = ", namespace);
553
+ continue;
554
+ }
555
+ const namespaceIndex = baseDataFactory.dataTypeDictionaryNodeId.namespace;
556
+ if (dataTypeManager.hasDataTypeFactory(namespaceIndex)) {
557
+ const dep = dataTypeManager.getDataTypeFactory(namespaceIndex);
558
+ baseDataFactories.push(dep);
559
+ debugLog(" considering , ", baseDataFactory.targetNamespace, "index = ", baseDataFactory.dataTypeDictionaryNodeId.namespace);
560
+ }
561
+ }
562
+ const dataTypeFactory = dataTypeManager.getDataTypeFactory(d.dataTypeDictionaryNodeId.namespace);
563
+ if (dataTypeFactory) {
564
+ dataTypeFactory.repairBaseDataFactories(baseDataFactories);
565
+ }
566
+ }
567
+ // --------------------
568
+ // now investigate DataTypeDescriptionType
569
+ function processReferenceOnDataTypeDictionaryType(d) {
570
+ return __awaiter(this, void 0, void 0, function* () {
571
+ debugLog(chalk.cyan("processReferenceOnDataTypeDictionaryType on "), d.targetNamespace);
572
+ const ref = d.reference;
573
+ const dataTypeDictionaryNodeId = d.reference.nodeId;
574
+ yield _extractDataTypeDictionary(session, d, dataTypeManager);
575
+ /* istanbul ignore next */
576
+ if (doDebug) {
577
+ debugLog(chalk.bgWhite(" => "), ref.browseName.toString(), ref.nodeId.toString());
578
+ }
579
+ const dataTypeFactory = dataTypeManager.getDataTypeFactoryForNamespace(dataTypeDictionaryNodeId.namespace);
580
+ yield _exploreDataTypeDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory, dataTypeManager.namespaceArray);
581
+ });
582
+ }
583
+ // https://medium.com/swlh/dealing-with-multiple-promises-in-javascript-41d6c21f20ff
584
+ for (const d of dataTypeDictionaryInfo) {
585
+ try {
586
+ yield processReferenceOnDataTypeDictionaryType(d).catch((e) => {
587
+ console.log(e);
588
+ debugLog("processReferenceOnDataTypeDictionaryType has failed ");
589
+ debugLog("Error", e.message);
590
+ debugLog(e);
591
+ return e;
592
+ });
593
+ }
594
+ catch (err) {
595
+ debugLog(chalk.red("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "), err);
596
+ }
597
+ }
598
+ debugLog("out ... populateDataTypeManager");
599
+ });
600
+ }
601
+ exports.populateDataTypeManager103 = populateDataTypeManager103;
602
602
  //# sourceMappingURL=populate_data_type_manager_103.js.map