node-opcua-generator 2.51.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.
- package/.mocharc.yml +8 -0
- package/LICENSE +20 -0
- package/dist/factory_code_generator.d.ts +9 -0
- package/dist/factory_code_generator.js +807 -0
- package/dist/factory_code_generator.js.map +1 -0
- package/dist/generate_extension_object_code.d.ts +1 -0
- package/dist/generate_extension_object_code.js +323 -0
- package/dist/generate_extension_object_code.js.map +1 -0
- package/dist/generator.d.ts +6 -0
- package/dist/generator.js +172 -0
- package/dist/generator.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/opcua_code_generator.d.ts +1 -0
- package/dist/opcua_code_generator.js +28 -0
- package/dist/opcua_code_generator.js.map +1 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +15 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/line_file.d.ts +6 -0
- package/dist/utils/line_file.js +26 -0
- package/dist/utils/line_file.js.map +1 -0
- package/dist/utils/normalize_require_file.d.ts +10 -0
- package/dist/utils/normalize_require_file.js +26 -0
- package/dist/utils/normalize_require_file.js.map +1 -0
- package/dist/utils/write_func.d.ts +7 -0
- package/dist/utils/write_func.js +15 -0
- package/dist/utils/write_func.js.map +1 -0
- package/package.json +58 -0
- package/source/factory_code_generator.ts +893 -0
- package/source/generate_extension_object_code.ts +356 -0
- package/source/generator.ts +191 -0
- package/source/index.ts +6 -0
- package/source/opcua_code_generator.ts +17 -0
- package/source/utils/index.ts +2 -0
- package/source/utils/line_file.ts +23 -0
- package/source/utils/normalize_require_file.ts +21 -0
- package/source/utils/write_func.ts +18 -0
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/* istanbul ignore file */
|
|
2
|
+
/**
|
|
3
|
+
* @module node-opcua-generator
|
|
4
|
+
*/
|
|
5
|
+
// tslint:disable:max-line-length
|
|
6
|
+
// tslint:disable:no-inner-declarations
|
|
7
|
+
//
|
|
8
|
+
import * as chalk from "chalk";
|
|
9
|
+
import * as fs from "fs";
|
|
10
|
+
// node 14 onward : import { readFile } from "fs/promises";
|
|
11
|
+
const { readFile }= fs.promises;
|
|
12
|
+
|
|
13
|
+
// import * as prettier from "prettier";
|
|
14
|
+
|
|
15
|
+
import { assert } from "node-opcua-assert";
|
|
16
|
+
import { DataTypeIds, ObjectIds } from "node-opcua-constants";
|
|
17
|
+
import { checkDebugFlag, make_debugLog } from "node-opcua-debug";
|
|
18
|
+
import {
|
|
19
|
+
EnumerationDefinitionSchema,
|
|
20
|
+
FieldCategory,
|
|
21
|
+
getStandardDataTypeFactory,
|
|
22
|
+
StructuredTypeSchema,
|
|
23
|
+
DataTypeFactory
|
|
24
|
+
} from "node-opcua-factory";
|
|
25
|
+
import { NodeId } from "node-opcua-nodeid";
|
|
26
|
+
import { DataTypeAndEncodingId, MapDataTypeAndEncodingIdProvider, parseBinaryXSDAsync } from "node-opcua-schemas";
|
|
27
|
+
|
|
28
|
+
import { writeStructuredType } from "./factory_code_generator";
|
|
29
|
+
import { LineFile1 } from "./utils/line_file";
|
|
30
|
+
import { makeWrite } from "./utils/write_func";
|
|
31
|
+
|
|
32
|
+
const doDebug = checkDebugFlag(__filename);
|
|
33
|
+
const debugLog = make_debugLog(__filename);
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
const f = new LineFile1();
|
|
37
|
+
|
|
38
|
+
const write = makeWrite(f);
|
|
39
|
+
|
|
40
|
+
function writeEnumeratedType(enumerationSchema: EnumerationDefinitionSchema) {
|
|
41
|
+
const arrayValues = Object.keys(enumerationSchema.enumValues)
|
|
42
|
+
.filter((a: string) => a.match("[0-9]+"))
|
|
43
|
+
.map((a: string) => parseInt(a, 10))
|
|
44
|
+
.filter((a: number) => a !== 0xffffffff)
|
|
45
|
+
.sort((a: number, b: number) => a - b);
|
|
46
|
+
|
|
47
|
+
// determining if enum is of type FLAGS
|
|
48
|
+
const isFlaggable = arrayValues.length > 2 && arrayValues[2] === arrayValues[1] * 2 && arrayValues[3] === arrayValues[2] * 2;
|
|
49
|
+
// find min and max values (excluding
|
|
50
|
+
const minEnumValue = Math.min.apply(null, arrayValues);
|
|
51
|
+
const maxEnumValue = Math.max.apply(null, arrayValues);
|
|
52
|
+
|
|
53
|
+
// make sure there is a Invalid key in the enum => else insert one (but only if not flaggable)
|
|
54
|
+
const hasInvalid = enumerationSchema.enumValues.hasOwnProperty("Invalid");
|
|
55
|
+
if (!hasInvalid && !isFlaggable) {
|
|
56
|
+
enumerationSchema.enumValues[(enumerationSchema.enumValues.Invalid = 0xffffffff)] = "Invalid";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
write("");
|
|
60
|
+
write(`// --------------------------------------------------------------------------------------------`);
|
|
61
|
+
write(`export enum ${enumerationSchema.name} {`);
|
|
62
|
+
|
|
63
|
+
const str = [];
|
|
64
|
+
|
|
65
|
+
const values = Object.keys(enumerationSchema.enumValues).filter((a: any) => a.match("[0-9]+"));
|
|
66
|
+
|
|
67
|
+
for (const value of values) {
|
|
68
|
+
str.push(` ${enumerationSchema.enumValues[value]} = ${value}`);
|
|
69
|
+
}
|
|
70
|
+
write(str.join(",\n"));
|
|
71
|
+
write(`}`);
|
|
72
|
+
|
|
73
|
+
write(`const schema${enumerationSchema.name} = {`);
|
|
74
|
+
// xx write(` documentation: "${enumerationSchema.documentation}",`);
|
|
75
|
+
write(` enumValues: ${enumerationSchema.name},`);
|
|
76
|
+
write(` flaggable: ${isFlaggable},`);
|
|
77
|
+
if (!isFlaggable) {
|
|
78
|
+
write(` minValue: ${minEnumValue},`);
|
|
79
|
+
write(` maxValue: ${maxEnumValue},`);
|
|
80
|
+
}
|
|
81
|
+
write(` name: "${enumerationSchema.name}"`);
|
|
82
|
+
|
|
83
|
+
write(`};`);
|
|
84
|
+
write(
|
|
85
|
+
`function decode${enumerationSchema.name}(stream: BinaryStream, _value?: ${enumerationSchema.name}): ${enumerationSchema.name} {`
|
|
86
|
+
);
|
|
87
|
+
if (!isFlaggable) {
|
|
88
|
+
if (enumerationSchema.lengthInBits === 16) {
|
|
89
|
+
write(` let value = stream.readUInt16() as ${enumerationSchema.name};`);
|
|
90
|
+
} else {
|
|
91
|
+
assert(enumerationSchema.lengthInBits === 32);
|
|
92
|
+
write(` let value = stream.readUInt32() as ${enumerationSchema.name};`);
|
|
93
|
+
}
|
|
94
|
+
write(
|
|
95
|
+
` value = (value < schema${enumerationSchema.name}.minValue || value > schema${enumerationSchema.name}.maxValue) ? ${enumerationSchema.name}.Invalid : value; `
|
|
96
|
+
);
|
|
97
|
+
write(` return value;`);
|
|
98
|
+
} else {
|
|
99
|
+
write(` return stream.readUInt32() as ${enumerationSchema.name};`);
|
|
100
|
+
}
|
|
101
|
+
write(`}`);
|
|
102
|
+
write(`function encode${enumerationSchema.name}(value: ${enumerationSchema.name}, stream: OutputBinaryStream): void {`);
|
|
103
|
+
if (enumerationSchema.lengthInBits === 16) {
|
|
104
|
+
write(` stream.writeUInt16(value);`);
|
|
105
|
+
} else {
|
|
106
|
+
assert(enumerationSchema.lengthInBits === 32);
|
|
107
|
+
write(` stream.writeUInt32(value);`);
|
|
108
|
+
}
|
|
109
|
+
write(`}`);
|
|
110
|
+
|
|
111
|
+
write(`export const _enumeration${enumerationSchema.name} = registerEnumeration(schema${enumerationSchema.name});`);
|
|
112
|
+
write(`assert(_enumeration${enumerationSchema.name}.isFlaggable === ${isFlaggable});`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function writeStructuredTypeWithSchema(structuredType: StructuredTypeSchema) {
|
|
116
|
+
write(`// --------------------------------------------------------------------------------------------`);
|
|
117
|
+
|
|
118
|
+
write(`const schema${structuredType.name} = buildStructuredType({`);
|
|
119
|
+
write(` name: "${structuredType.name}",`);
|
|
120
|
+
write(``);
|
|
121
|
+
write(` baseType: "${structuredType.baseType}",`);
|
|
122
|
+
write(` fields: [`);
|
|
123
|
+
for (const field of structuredType.fields) {
|
|
124
|
+
write(` {`);
|
|
125
|
+
write(` name: "${field.name}",`);
|
|
126
|
+
write(``);
|
|
127
|
+
write(` fieldType: "${field.fieldType}",`);
|
|
128
|
+
if (field.isArray) {
|
|
129
|
+
write(` isArray: ${field.isArray}`);
|
|
130
|
+
}
|
|
131
|
+
// write(` /* cat = ${field.category} */`);
|
|
132
|
+
write(` },`);
|
|
133
|
+
}
|
|
134
|
+
write(` ]`);
|
|
135
|
+
write(`});`);
|
|
136
|
+
|
|
137
|
+
writeStructuredType(write, structuredType);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function generate(filename: string, generatedTypescriptFilename: string) {
|
|
141
|
+
try {
|
|
142
|
+
const content = await readFile(filename, "ascii");
|
|
143
|
+
|
|
144
|
+
const idProvider: MapDataTypeAndEncodingIdProvider = {
|
|
145
|
+
getDataTypeAndEncodingId(name: string): DataTypeAndEncodingId | null {
|
|
146
|
+
const dataType = (DataTypeIds as any)[name] || 0;
|
|
147
|
+
const binEncoding = (ObjectIds as any)[name + "_Encoding_DefaultBinary"] || 0;
|
|
148
|
+
const xmlEncoding = (ObjectIds as any)[name + "_Encoding_DefaultXml"] || 0;
|
|
149
|
+
const jsonEncoding = (ObjectIds as any)[name + "_Encoding_DefaultJson"] || 0;
|
|
150
|
+
if (dataType === undefined) {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
const dataTypeNodeId = new NodeId(NodeId.NodeIdType.NUMERIC, dataType, 0);
|
|
154
|
+
const binaryEncodingNodeId = new NodeId(NodeId.NodeIdType.NUMERIC, binEncoding, 0);
|
|
155
|
+
const xmlEncodingNodeId = new NodeId(NodeId.NodeIdType.NUMERIC, xmlEncoding, 0);
|
|
156
|
+
const jsonEncodingNodeId = new NodeId(NodeId.NodeIdType.NUMERIC, jsonEncoding, 0);
|
|
157
|
+
const data: DataTypeAndEncodingId = {
|
|
158
|
+
binaryEncodingNodeId,
|
|
159
|
+
dataTypeNodeId,
|
|
160
|
+
jsonEncodingNodeId,
|
|
161
|
+
xmlEncodingNodeId
|
|
162
|
+
};
|
|
163
|
+
if (doDebug) {
|
|
164
|
+
debugLog(
|
|
165
|
+
" data=",
|
|
166
|
+
chalk.cyan(name.padEnd(43, " ")),
|
|
167
|
+
data.dataTypeNodeId.toString().padEnd(43, " "),
|
|
168
|
+
data.binaryEncodingNodeId.toString().padEnd(43, " ")
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
return data;
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const dataTypeFactory = new DataTypeFactory([getStandardDataTypeFactory()]);
|
|
176
|
+
await parseBinaryXSDAsync(content, idProvider, dataTypeFactory);
|
|
177
|
+
|
|
178
|
+
write(
|
|
179
|
+
`// tslint:disable:no-this-assignment
|
|
180
|
+
// tslint:disable:max-classes-per-file
|
|
181
|
+
// tslint:disable:no-empty-interface
|
|
182
|
+
// tslint:disable:no-trailing-whitespace
|
|
183
|
+
// tslint:disable:array-type
|
|
184
|
+
// tslint:disable:object-literal-sort-keys
|
|
185
|
+
// tslint:disable:max-line-length
|
|
186
|
+
|
|
187
|
+
import { assert } from "node-opcua-assert";
|
|
188
|
+
import {
|
|
189
|
+
Byte, ByteString, CharArray, DateTime,
|
|
190
|
+
decodeArray, decodeBoolean, decodeByte, decodeByteString,
|
|
191
|
+
decodeDateTime, decodeDouble, decodeExpandedNodeId, decodeFloat,
|
|
192
|
+
decodeGuid, decodeInt16,
|
|
193
|
+
decodeInt32, decodeInt64,
|
|
194
|
+
decodeInt8, decodeNodeId,
|
|
195
|
+
decodeString, decodeUABoolean,
|
|
196
|
+
decodeUAString, decodeUInt16,
|
|
197
|
+
decodeUInt32, decodeUInt64,
|
|
198
|
+
decodeUInt8,
|
|
199
|
+
decodeSByte,
|
|
200
|
+
Double,
|
|
201
|
+
encodeArray, encodeBoolean,
|
|
202
|
+
encodeSByte, encodeByte, encodeByteString,
|
|
203
|
+
encodeDateTime, encodeDouble,
|
|
204
|
+
encodeExpandedNodeId, encodeFloat,
|
|
205
|
+
encodeGuid, encodeInt16,
|
|
206
|
+
encodeInt32, encodeInt64,
|
|
207
|
+
encodeInt8, encodeNodeId,
|
|
208
|
+
encodeString, encodeUABoolean,
|
|
209
|
+
encodeUAString, encodeUInt16,
|
|
210
|
+
encodeUInt32, encodeUInt64, encodeUInt8,
|
|
211
|
+
Float, Guid,
|
|
212
|
+
Int16, Int32,
|
|
213
|
+
Int64,
|
|
214
|
+
Int8,
|
|
215
|
+
SByte,
|
|
216
|
+
UABoolean,
|
|
217
|
+
UAString, UInt16, UInt32,
|
|
218
|
+
UInt64, UInt8,
|
|
219
|
+
} from "node-opcua-basic-types";
|
|
220
|
+
|
|
221
|
+
import { Enum, EnumItem } from "node-opcua-enum";
|
|
222
|
+
|
|
223
|
+
import { BinaryStream , OutputBinaryStream} from "node-opcua-binary-stream";
|
|
224
|
+
import {
|
|
225
|
+
_enumerationBrowseDirection, BrowseDirection, decodeBrowseDirection, decodeDiagnosticInfo,
|
|
226
|
+
decodeLocalizedText, decodeQualifiedName,
|
|
227
|
+
DiagnosticInfo, DiagnosticInfoOptions,
|
|
228
|
+
encodeBrowseDirection,
|
|
229
|
+
encodeDiagnosticInfo, encodeLocalizedText, encodeQualifiedName,
|
|
230
|
+
LocalizedText, LocalizedTextLike, QualifiedName, QualifiedNameLike,
|
|
231
|
+
LocalizedTextOptions, QualifiedNameOptions,
|
|
232
|
+
} from "node-opcua-data-model";
|
|
233
|
+
import {
|
|
234
|
+
_enumerationTimestampsToReturn, DataValue, DataValueLike, DataValueOptions, decodeDataValue,
|
|
235
|
+
decodeTimestampsToReturn, encodeDataValue, encodeTimestampsToReturn, TimestampsToReturn
|
|
236
|
+
} from "node-opcua-data-value";
|
|
237
|
+
import {
|
|
238
|
+
decodeExtensionObject, encodeExtensionObject, ExtensionObject
|
|
239
|
+
} from "node-opcua-extension-object";
|
|
240
|
+
import {
|
|
241
|
+
BaseUAObject, buildStructuredType, check_options_correctness_against_schema,
|
|
242
|
+
initialize_field, initialize_field_array, parameters,
|
|
243
|
+
registerClassDefinition,
|
|
244
|
+
registerEnumeration, StructuredTypeSchema
|
|
245
|
+
} from "node-opcua-factory";
|
|
246
|
+
import {
|
|
247
|
+
ExpandedNodeId, makeExpandedNodeId, NodeId, NodeIdLike
|
|
248
|
+
} from "node-opcua-nodeid";
|
|
249
|
+
import {
|
|
250
|
+
decodeNumericRange, encodeNumericRange, NumericRange
|
|
251
|
+
} from "node-opcua-numeric-range";
|
|
252
|
+
import {
|
|
253
|
+
decodeStatusCode, encodeStatusCode, StatusCode, StatusCodes
|
|
254
|
+
} from "node-opcua-status-code";
|
|
255
|
+
import {
|
|
256
|
+
decodeVariant, encodeVariant, Variant, VariantLike,
|
|
257
|
+
VariantOptions
|
|
258
|
+
} from "node-opcua-variant";`
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
write(``);
|
|
262
|
+
|
|
263
|
+
write(`export class DataTypeDefinition extends BaseUAObject {`);
|
|
264
|
+
write(` constructor(options: any) {`);
|
|
265
|
+
write(` options = options; // do not remove`);
|
|
266
|
+
write(` super();`);
|
|
267
|
+
write(` }`);
|
|
268
|
+
write(`}`);
|
|
269
|
+
write(``);
|
|
270
|
+
|
|
271
|
+
const alreadyDone: { [key: string]: any } = {};
|
|
272
|
+
/* tslint:disable:no-string-literal */
|
|
273
|
+
alreadyDone["ExtensionObject"] = true;
|
|
274
|
+
alreadyDone["NodeId"] = true;
|
|
275
|
+
|
|
276
|
+
alreadyDone["ExpandedNodeId"] = true;
|
|
277
|
+
alreadyDone["Variant"] = true;
|
|
278
|
+
alreadyDone["XmlElement"] = true;
|
|
279
|
+
|
|
280
|
+
alreadyDone["NodeIdType"] = true;
|
|
281
|
+
alreadyDone["TwoByteNodeId"] = true;
|
|
282
|
+
alreadyDone["FourByteNodeId"] = true;
|
|
283
|
+
alreadyDone["NumericNodeId"] = true;
|
|
284
|
+
alreadyDone["StringNodeId"] = true;
|
|
285
|
+
alreadyDone["GuidNodeId"] = true;
|
|
286
|
+
alreadyDone["ByteStringNodeId"] = true;
|
|
287
|
+
|
|
288
|
+
alreadyDone["DiagnosticInfo"] = true;
|
|
289
|
+
alreadyDone["Variant"] = true;
|
|
290
|
+
alreadyDone["DataValue"] = true;
|
|
291
|
+
alreadyDone["LocalizedText"] = true;
|
|
292
|
+
alreadyDone["QualifiedName"] = true;
|
|
293
|
+
alreadyDone["BrowseDirection"] = true;
|
|
294
|
+
alreadyDone["TimestampsToReturn"] = true;
|
|
295
|
+
|
|
296
|
+
function processEnumeratedType(enumerationSchema: EnumerationDefinitionSchema): void {
|
|
297
|
+
if (alreadyDone[enumerationSchema.name]) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
alreadyDone[enumerationSchema.name] = enumerationSchema;
|
|
301
|
+
writeEnumeratedType(enumerationSchema);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function processStructuredType(structuredType: StructuredTypeSchema): void {
|
|
305
|
+
if (alreadyDone[structuredType.name]) {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
alreadyDone[structuredType.name] = structuredType;
|
|
309
|
+
|
|
310
|
+
// make sure
|
|
311
|
+
if (dataTypeFactory.hasStructuredType(structuredType.baseType)) {
|
|
312
|
+
processStructuredType(dataTypeFactory.getStructuredTypeSchema(structuredType.baseType));
|
|
313
|
+
}
|
|
314
|
+
for (const field of structuredType.fields) {
|
|
315
|
+
if (field.category === FieldCategory.complex) {
|
|
316
|
+
const fieldSchema = dataTypeFactory.getStructuredTypeSchema(field.fieldType);
|
|
317
|
+
processStructuredType(fieldSchema);
|
|
318
|
+
}
|
|
319
|
+
if (field.category === FieldCategory.enumeration) {
|
|
320
|
+
const fieldSchema = dataTypeFactory.getEnumeration(field.fieldType)!;
|
|
321
|
+
processEnumeratedType(fieldSchema);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
writeStructuredTypeWithSchema(structuredType);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
processStructuredType(dataTypeFactory.getStructuredTypeSchema("LocalizedText"));
|
|
328
|
+
processStructuredType(dataTypeFactory.getStructuredTypeSchema("AxisInformation"));
|
|
329
|
+
// processStructuredType(dataTypeFactory.getStructuredTypeSchema("DiagnosticInfo"));
|
|
330
|
+
processStructuredType(dataTypeFactory.getStructuredTypeSchema("SimpleAttributeOperand"));
|
|
331
|
+
|
|
332
|
+
for (const structureType of [...dataTypeFactory.structuredTypesNames()].sort()) {
|
|
333
|
+
if (!dataTypeFactory.hasStructuredType(structureType)) {
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
processStructuredType(dataTypeFactory.getStructuredTypeSchema(structureType));
|
|
337
|
+
// if (++i > 250) { break; }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
write(``);
|
|
341
|
+
f.saveFormat(generatedTypescriptFilename, (code) => {
|
|
342
|
+
return code;
|
|
343
|
+
/*
|
|
344
|
+
const options: prettier.Options = {
|
|
345
|
+
bracketSpacing: true,
|
|
346
|
+
insertPragma: true,
|
|
347
|
+
parser: "typescript",
|
|
348
|
+
printWidth: 120
|
|
349
|
+
};
|
|
350
|
+
return prettier.format(code, options).replace("\n", os.EOL);
|
|
351
|
+
*/
|
|
352
|
+
});
|
|
353
|
+
} catch (err) {
|
|
354
|
+
throw err;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/* istanbul ignore file */
|
|
2
|
+
/**
|
|
3
|
+
* @module node-opcua-generator
|
|
4
|
+
*/
|
|
5
|
+
// tslint:disable:max-line-length
|
|
6
|
+
// tslint:disable:no-console
|
|
7
|
+
import * as fs from "fs";
|
|
8
|
+
// node 14 onward : import { mkdir } from "fs/promises";
|
|
9
|
+
const { mkdir }= fs.promises;
|
|
10
|
+
|
|
11
|
+
import * as path from "path";
|
|
12
|
+
import * as ts from "typescript";
|
|
13
|
+
|
|
14
|
+
import { assert } from "node-opcua-assert";
|
|
15
|
+
import { checkDebugFlag, make_debugLog } from "node-opcua-debug";
|
|
16
|
+
import { ConstructorFunc } from "node-opcua-factory";
|
|
17
|
+
|
|
18
|
+
import { get_class_TScript_filename, produce_TScript_code } from "./factory_code_generator";
|
|
19
|
+
|
|
20
|
+
const debugLog = make_debugLog(__filename);
|
|
21
|
+
const doDebug = checkDebugFlag(__filename);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @module opcua.miscellaneous
|
|
25
|
+
* @class Factory
|
|
26
|
+
* @static
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
function compileTScriptCode(typescriptFilename: string): string {
|
|
30
|
+
const content = fs.readFileSync(typescriptFilename, "ascii");
|
|
31
|
+
|
|
32
|
+
const compilerOptions = {
|
|
33
|
+
module: ts.ModuleKind.CommonJS,
|
|
34
|
+
target: ts.ScriptTarget.ES2016,
|
|
35
|
+
|
|
36
|
+
skipLibCheck: true,
|
|
37
|
+
|
|
38
|
+
declaration: true,
|
|
39
|
+
sourceMap: true,
|
|
40
|
+
strict: true,
|
|
41
|
+
|
|
42
|
+
noImplicitAny: true,
|
|
43
|
+
noImplicitReturns: true
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const res1 = ts.transpileModule(content, { compilerOptions, moduleName: "myModule2" });
|
|
47
|
+
|
|
48
|
+
const javascriptFilename = typescriptFilename.replace(/\.ts$/, ".js");
|
|
49
|
+
const sourceMapFilename = typescriptFilename.replace(/\.ts$/, ".js.map");
|
|
50
|
+
|
|
51
|
+
fs.writeFileSync(javascriptFilename, res1.outputText, "ascii");
|
|
52
|
+
fs.writeFileSync(sourceMapFilename, res1.sourceMapText!, "ascii");
|
|
53
|
+
|
|
54
|
+
return res1.outputText;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const verbose = false;
|
|
58
|
+
|
|
59
|
+
function get_caller_source_filename() {
|
|
60
|
+
// let's find source code where schema file is described
|
|
61
|
+
// to do make change this
|
|
62
|
+
// the line has the following shape:
|
|
63
|
+
// 'at blah (/home/toto/myFile.js:53:34)'
|
|
64
|
+
const err = new Error("");
|
|
65
|
+
const re = /.*\((.*):[0-9]*:[0-9]*\)/g;
|
|
66
|
+
if (!err.stack) {
|
|
67
|
+
return "";
|
|
68
|
+
}
|
|
69
|
+
console.log(err.stack.split("\n"));
|
|
70
|
+
const ma = err.stack.split("\n");
|
|
71
|
+
let m = re.exec(ma[8]);
|
|
72
|
+
if (!m) {
|
|
73
|
+
m = re.exec(ma[4]);
|
|
74
|
+
}
|
|
75
|
+
if (!m) {
|
|
76
|
+
return "../";
|
|
77
|
+
// throw new Error("Invalid: cannot find caller_source_filename : " + err.stack + "\n =============");
|
|
78
|
+
}
|
|
79
|
+
const schemaFile = m[1];
|
|
80
|
+
return schemaFile;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function generateCode(schemaName: string, localSchemaFile: string, generatedCodeFolder?: string) {
|
|
84
|
+
const schemaTypescriptFile = schemaName + "_Schema.ts";
|
|
85
|
+
|
|
86
|
+
const currentFolder = process.cwd();
|
|
87
|
+
//
|
|
88
|
+
const localSchemaFileExists = fs.existsSync(localSchemaFile);
|
|
89
|
+
|
|
90
|
+
if (!localSchemaFileExists) {
|
|
91
|
+
throw new Error(`Cannot find source file for schema ${schemaTypescriptFile}`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!generatedCodeFolder) {
|
|
95
|
+
generatedCodeFolder = path.join(currentFolder, "_generated_");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const generatedCodeFolderExists = fs.existsSync(generatedCodeFolder);
|
|
99
|
+
if (!generatedCodeFolderExists) {
|
|
100
|
+
await mkdir(generatedCodeFolder);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const generatedTypescriptSource = path.join(generatedCodeFolder, "_" + schemaName + ".ts");
|
|
104
|
+
|
|
105
|
+
const generatedSourceExists = fs.existsSync(generatedTypescriptSource);
|
|
106
|
+
|
|
107
|
+
let schemaFileIsNewer = false;
|
|
108
|
+
let codeGeneratorIsNewer = true;
|
|
109
|
+
|
|
110
|
+
if (generatedSourceExists) {
|
|
111
|
+
const generatedSourceMtime = new Date(fs.statSync(generatedTypescriptSource).mtime).getTime();
|
|
112
|
+
|
|
113
|
+
const schemaFileMtime = new Date(fs.statSync(localSchemaFile).mtime).getTime();
|
|
114
|
+
|
|
115
|
+
schemaFileIsNewer = generatedSourceMtime <= schemaFileMtime;
|
|
116
|
+
|
|
117
|
+
let codeGeneratorScript = path.join(__dirname, "factory_code_generator.ts");
|
|
118
|
+
if (!fs.existsSync(codeGeneratorScript)) {
|
|
119
|
+
codeGeneratorScript = path.join(__dirname, "factory_code_generator.js");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
assert(fs.existsSync(codeGeneratorScript), "cannot get code factory_code_generator" + codeGeneratorScript);
|
|
123
|
+
const codeGeneratorScriptMtime = new Date(fs.statSync(codeGeneratorScript).mtime).getTime();
|
|
124
|
+
|
|
125
|
+
codeGeneratorIsNewer = generatedSourceMtime <= codeGeneratorScriptMtime;
|
|
126
|
+
}
|
|
127
|
+
const generatedSourceIsOutdated = !generatedSourceExists || codeGeneratorIsNewer || schemaFileIsNewer;
|
|
128
|
+
|
|
129
|
+
if (generatedSourceIsOutdated) {
|
|
130
|
+
const module = await import(localSchemaFile);
|
|
131
|
+
const schema = module[schemaName + "_Schema"];
|
|
132
|
+
|
|
133
|
+
if (!schema) {
|
|
134
|
+
throw new Error(`module must export a Schema with name ${schemaName}_Schema in ${generatedTypescriptSource}`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
debugLog(" generated_source_is_outdated ", schemaName, " to ", generatedTypescriptSource);
|
|
138
|
+
if (exports.verbose) {
|
|
139
|
+
console.log(" generating ", schemaName, " in ", generatedTypescriptSource);
|
|
140
|
+
}
|
|
141
|
+
const localSchemaFile1 = path.join("../schemas", schemaName + "_schema");
|
|
142
|
+
produce_TScript_code(schema, localSchemaFile1, generatedTypescriptSource);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function generateTypeScriptCodeFromSchema(schemaName: string) {
|
|
147
|
+
const currentFolder = process.cwd();
|
|
148
|
+
const schemaFilename = path.join(currentFolder, "schemas", schemaName + "_schema.ts");
|
|
149
|
+
const generatedCodeFolder = path.join(process.cwd(), "_generated_");
|
|
150
|
+
await generateCode(schemaName, schemaFilename, generatedCodeFolder);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function registerObject(schema: string, generateCodeFolder?: string): Promise<ConstructorFunc | null> {
|
|
154
|
+
if (!schema.split) {
|
|
155
|
+
console.log("error !", schema);
|
|
156
|
+
// xx process.exit(1);
|
|
157
|
+
}
|
|
158
|
+
// we expect <schema>|<hint>
|
|
159
|
+
const hintSchema = schema.split("|");
|
|
160
|
+
if (hintSchema.length === 1) {
|
|
161
|
+
// no hint provided
|
|
162
|
+
const callerFolder = get_caller_source_filename();
|
|
163
|
+
|
|
164
|
+
const defaultHint = path.join(path.dirname(callerFolder), "schemas");
|
|
165
|
+
hintSchema.unshift(defaultHint);
|
|
166
|
+
generateCodeFolder = generateCodeFolder ? generateCodeFolder : path.join(path.dirname(callerFolder), "_generated_");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const folderHint = hintSchema[0];
|
|
170
|
+
schema = hintSchema[1];
|
|
171
|
+
|
|
172
|
+
const schemaName = schema + "_Schema";
|
|
173
|
+
const schemaFile = path.join(folderHint, schema + "_schema.ts");
|
|
174
|
+
const module = await import(schemaFile);
|
|
175
|
+
if (!module) {
|
|
176
|
+
throw new Error("cannot find " + schemaFile);
|
|
177
|
+
}
|
|
178
|
+
const schemaObj = module[schemaName];
|
|
179
|
+
|
|
180
|
+
await generateCode(schemaName, schemaFile, generateCodeFolder);
|
|
181
|
+
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function unregisterObject(schema: any, folder: string) {
|
|
186
|
+
const generateTypeScriptSource = get_class_TScript_filename(schema.name, folder);
|
|
187
|
+
if (fs.existsSync(generateTypeScriptSource)) {
|
|
188
|
+
fs.unlinkSync(generateTypeScriptSource);
|
|
189
|
+
assert(!fs.existsSync(generateTypeScriptSource));
|
|
190
|
+
}
|
|
191
|
+
}
|
package/source/index.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/* istanbul ignore file */
|
|
2
|
+
/**
|
|
3
|
+
* @module node-opcua-generator
|
|
4
|
+
*/
|
|
5
|
+
// tslint:disable:no-console
|
|
6
|
+
import { generateTypeScriptCodeFromSchema } from "./generator";
|
|
7
|
+
|
|
8
|
+
console.log(process.argv);
|
|
9
|
+
|
|
10
|
+
async function main() {
|
|
11
|
+
const className = "LocalizedText";
|
|
12
|
+
generateTypeScriptCodeFromSchema(className);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
main()
|
|
16
|
+
.then()
|
|
17
|
+
.catch();
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module node-opcua-utils
|
|
3
|
+
*/
|
|
4
|
+
import { writeFileSync } from "fs";
|
|
5
|
+
import { LineFile } from "node-opcua-utils";
|
|
6
|
+
|
|
7
|
+
export class LineFile1 extends LineFile {
|
|
8
|
+
constructor() {
|
|
9
|
+
super();
|
|
10
|
+
this.write("// --------- This code has been automatically generated !!! " + new Date().toISOString());
|
|
11
|
+
this.write("/**");
|
|
12
|
+
this.write(" * @module node-opcua-types");
|
|
13
|
+
this.write(" */");
|
|
14
|
+
}
|
|
15
|
+
public save(filename: string): void {
|
|
16
|
+
writeFileSync(filename, this.toString(), "ascii");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
public saveFormat(filename: string, formatter: (code: string) => string): void {
|
|
20
|
+
const code = formatter(this.toString());
|
|
21
|
+
writeFileSync(filename, code, "ascii");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import * as path from "path";
|
|
2
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
3
|
+
/**
|
|
4
|
+
* @method normalize_require_file
|
|
5
|
+
* @param baseFolder
|
|
6
|
+
* @param fullPathToFile
|
|
7
|
+
*
|
|
8
|
+
*
|
|
9
|
+
* @example:
|
|
10
|
+
* normalize_require_file("/home/bob/folder1/","/home/bob/folder1/folder2/toto.js").should.eql("./folder2/toto");
|
|
11
|
+
*/
|
|
12
|
+
export function normalize_require_file(baseFolder: string, fullPathToFile: string): string {
|
|
13
|
+
let localFile = path.relative(baseFolder, fullPathToFile).replace(/\\/g, "/");
|
|
14
|
+
// append ./ if necessary
|
|
15
|
+
if (localFile.substr(0, 1) !== ".") {
|
|
16
|
+
localFile = "./" + localFile;
|
|
17
|
+
}
|
|
18
|
+
// remove extension
|
|
19
|
+
localFile = localFile.substr(0, localFile.length - path.extname(localFile).length);
|
|
20
|
+
return localFile;
|
|
21
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { LineFile1 } from "./line_file";
|
|
2
|
+
|
|
3
|
+
export interface WriteFunc {
|
|
4
|
+
(...args: string[]): void;
|
|
5
|
+
indent(): void;
|
|
6
|
+
pop(): void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const makeWrite = (f: LineFile1) => {
|
|
10
|
+
const _f: any = (...args: string[]) => f.write.apply(f, args);
|
|
11
|
+
_f.indent = () => {
|
|
12
|
+
/** */
|
|
13
|
+
};
|
|
14
|
+
_f.pop = () => {
|
|
15
|
+
/** */
|
|
16
|
+
};
|
|
17
|
+
return _f;
|
|
18
|
+
};
|