@lcap/nasl 3.7.0-beta.8 → 3.7.1-alpha.1

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 (45) hide show
  1. package/out/concepts/ConnectorTrigger__.d.ts +0 -18
  2. package/out/concepts/ConnectorTrigger__.js +0 -145
  3. package/out/concepts/ConnectorTrigger__.js.map +1 -1
  4. package/out/concepts/Connector__.d.ts +1 -1
  5. package/out/concepts/Connector__.js +1 -4
  6. package/out/concepts/Connector__.js.map +1 -1
  7. package/out/concepts/TriggerLauncher__.js +2 -2
  8. package/out/concepts/TriggerLauncher__.js.map +1 -1
  9. package/out/config.d.ts +0 -5
  10. package/out/config.js +0 -1
  11. package/out/config.js.map +1 -1
  12. package/out/generator/genBundleFiles.d.ts +0 -3
  13. package/out/generator/genBundleFiles.js +0 -19
  14. package/out/generator/genBundleFiles.js.map +1 -1
  15. package/out/generator/release-body/body.d.ts +1 -7
  16. package/out/generator/release-body/body.js +1 -66
  17. package/out/generator/release-body/body.js.map +1 -1
  18. package/out/generator/release-body/data.js +1 -10
  19. package/out/generator/release-body/data.js.map +1 -1
  20. package/out/generator/release-body/internal.d.ts +0 -9
  21. package/out/generator/release-body/internal.js.map +1 -1
  22. package/out/generator/release-body/utils.d.ts +2 -9
  23. package/out/generator/release-body/utils.js +5 -30
  24. package/out/generator/release-body/utils.js.map +1 -1
  25. package/out/natural/index.d.ts +1 -0
  26. package/out/natural/index.js +1 -0
  27. package/out/natural/index.js.map +1 -1
  28. package/out/natural/transformTS2UI.d.ts +1 -0
  29. package/out/natural/transformTS2UI.js +1173 -0
  30. package/out/natural/transformTS2UI.js.map +1 -0
  31. package/out/server/naslServer.js +1 -2
  32. package/out/server/naslServer.js.map +1 -1
  33. package/package.json +1 -1
  34. package/src/concepts/ConnectorTrigger__.ts +0 -160
  35. package/src/concepts/Connector__.ts +1 -4
  36. package/src/concepts/TriggerLauncher__.ts +2 -2
  37. package/src/config.ts +0 -5
  38. package/src/generator/genBundleFiles.ts +0 -22
  39. package/src/generator/release-body/body.ts +1 -68
  40. package/src/generator/release-body/data.ts +4 -15
  41. package/src/generator/release-body/internal.ts +0 -10
  42. package/src/generator/release-body/utils.ts +8 -35
  43. package/src/natural/index.ts +1 -0
  44. package/src/natural/transformTS2UI.ts +1123 -0
  45. package/src/server/naslServer.ts +0 -2
@@ -0,0 +1,1173 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.tryTransformTS2UI = void 0;
30
+ /* eslint-disable global-require */
31
+ /* eslint-disable @typescript-eslint/no-use-before-define */
32
+ const lodash_1 = require("lodash");
33
+ const babel = __importStar(require("@babel/core"));
34
+ const generator_1 = __importDefault(require("@babel/generator"));
35
+ const naslTypes = __importStar(require("../concepts"));
36
+ const generator_2 = require("../generator");
37
+ const DEBUG = false;
38
+ function throwError(message) {
39
+ if (DEBUG)
40
+ throw new Error(message);
41
+ else
42
+ console.error(message);
43
+ }
44
+ function flatMemberExpression(node) {
45
+ if (node.type === 'MemberExpression')
46
+ return [...flatMemberExpression(node.object), node.property];
47
+ return [node];
48
+ }
49
+ function flatMatchPatternsExpression(node) {
50
+ if (node.concept === 'BinaryExpression') {
51
+ if (node.operator === '||') {
52
+ return [...flatMatchPatternsExpression(node.left), ...flatMatchPatternsExpression(node.right)];
53
+ }
54
+ if (node.operator === '==') {
55
+ return [node.right];
56
+ }
57
+ return [node];
58
+ }
59
+ return [node];
60
+ }
61
+ function flatIfStatement(node) {
62
+ if (node.alternate.type === 'IfStatement') {
63
+ return [...flatIfStatement(node.alternate), node];
64
+ }
65
+ return [node];
66
+ }
67
+ /**
68
+ * 这个函数是修复 AI 翻译出错的情况,与正常的 transform 做个区分
69
+ * @param node
70
+ * @returns
71
+ */
72
+ function fixLogicNode(node) {
73
+ if (node?.type === 'CallExpression') {
74
+ const calleeName = (0, generator_1.default)(node.callee).code;
75
+ if (calleeName === 'nasl.util.ForEach') {
76
+ const callee = flatMemberExpression(node.callee);
77
+ node.callee = callee[2];
78
+ }
79
+ }
80
+ }
81
+ // 处理类型
82
+ function transformTypeAnnotation(node) {
83
+ if (!node)
84
+ return null;
85
+ if (node.type === 'TSTypeReference') {
86
+ const typeName = node.typeName.name;
87
+ const primitiveType = naslTypes.primitiveTypeList.find((ta) => ta.typeName === typeName);
88
+ if (node?.typeNamespace) {
89
+ return naslTypes.TypeAnnotation.createReference(typeName, {
90
+ typeNamespace: node.typeNamespace,
91
+ });
92
+ }
93
+ if (typeName === 'Any' || typeName === 'any') {
94
+ return undefined;
95
+ }
96
+ if (typeName === 'Integer') {
97
+ return naslTypes.TypeAnnotation.createPrimitive('Long');
98
+ }
99
+ if (primitiveType) {
100
+ return naslTypes.TypeAnnotation.createPrimitive(typeName);
101
+ }
102
+ if (['List', 'Map', 'Current'].includes(typeName) && node?.typeParameters) {
103
+ return naslTypes.TypeAnnotation.createGeneric(typeName, {
104
+ typeArguments: node?.typeParameters?.params.map(transformTypeAnnotation),
105
+ });
106
+ }
107
+ if (node?.typeName?.type === 'TSQualifiedName' && node?.typeParameters) {
108
+ const curTypeName = node?.typeName?.right?.name;
109
+ return naslTypes.TypeAnnotation.createGeneric(curTypeName, {
110
+ typeArguments: node?.typeParameters?.params.map(transformTypeAnnotation),
111
+ });
112
+ }
113
+ if (!node.typeParameters) {
114
+ if (node?.typeName?.type === 'TSQualifiedName') {
115
+ const allTypeName = (0, generator_1.default)(node?.typeName?.left)?.code;
116
+ // 实体、枚举、结构体
117
+ if (/^app.dataSources|.enums|.structures/.test(allTypeName)) {
118
+ const curTypeName = node?.typeName?.right?.name;
119
+ return naslTypes.TypeAnnotation.createReference(curTypeName, {
120
+ typeNamespace: allTypeName,
121
+ });
122
+ }
123
+ }
124
+ return naslTypes.TypeAnnotation.createReference(typeName, {
125
+ typeNamespace: null,
126
+ });
127
+ }
128
+ throwError(`Unhandled node ${node.type}`);
129
+ }
130
+ else if (node.type === 'TSTypeLiteral') {
131
+ return naslTypes.TypeAnnotation.createTypeAnonymousStructure(node.members.map((member) => new naslTypes.StructureProperty({
132
+ name: member.key.name,
133
+ typeAnnotation: transformTypeAnnotation(member.typeAnnotation.typeAnnotation),
134
+ })));
135
+ }
136
+ else if (node.type === 'TSBooleanKeyword') {
137
+ return naslTypes.TypeAnnotation.createPrimitive('Boolean');
138
+ }
139
+ else if (node.type === 'TSStringKeyword') {
140
+ return naslTypes.TypeAnnotation.createPrimitive('String');
141
+ }
142
+ else if (node.type === 'TSNumberKeyword') {
143
+ return naslTypes.TypeAnnotation.createPrimitive('Double');
144
+ }
145
+ else if (node.type === 'TSUnionType') {
146
+ const union = naslTypes.TypeAnnotation.createPrimitive('Union');
147
+ union.typeArguments = [];
148
+ node.types.forEach((curType) => {
149
+ union.typeArguments.push(transformTypeAnnotation(curType));
150
+ });
151
+ return union;
152
+ }
153
+ else {
154
+ throwError(`Unhandled node ${node.type}`);
155
+ }
156
+ }
157
+ // 处理参数
158
+ function transformParam(node) {
159
+ const typeAnnotation = node.typeAnnotation?.typeAnnotation;
160
+ return new naslTypes.Param({
161
+ name: node.name,
162
+ typeAnnotation: typeAnnotation ? transformTypeAnnotation(typeAnnotation) : null,
163
+ });
164
+ }
165
+ // 处理变量
166
+ function transformVariableDeclaration(node) {
167
+ const declList = node?.declarations || [];
168
+ let newNode;
169
+ declList?.forEach((decl) => {
170
+ const variableName = decl.id.name;
171
+ const varTypeAnnotation = decl.id.typeAnnotation?.typeAnnotation;
172
+ newNode = new naslTypes.Variable({
173
+ name: variableName,
174
+ typeAnnotation: varTypeAnnotation && transformTypeAnnotation(varTypeAnnotation),
175
+ });
176
+ if (decl.init) {
177
+ if (decl.init.type !== 'ArrayExpression' && decl.init.type !== 'ObjectExpression') {
178
+ // 变量值需要默认值还是赋值,在使用的地方处理
179
+ newNode.defaultValue = new naslTypes.DefaultValue({
180
+ expression: transformNode2Expression(decl.init),
181
+ });
182
+ }
183
+ }
184
+ });
185
+ return newNode;
186
+ }
187
+ // 处理 if
188
+ function pushElseIf(ifNode, switchStatement) {
189
+ switchStatement.cases.push(new naslTypes.SwitchCase({
190
+ test: transformNode2Expression(ifNode.test),
191
+ consequent: !ifNode.consequent ? [] : ifNode.consequent.body.map((item) => transformNode2Expression(item)).filter((item) => !!item),
192
+ }));
193
+ if (ifNode.alternate && ifNode.alternate.type === 'IfStatement') {
194
+ pushElseIf(ifNode.alternate, switchStatement);
195
+ }
196
+ else {
197
+ switchStatement.cases.push(new naslTypes.SwitchCase({
198
+ test: undefined,
199
+ consequent: !ifNode?.alternate ? [] : ifNode?.alternate?.body.map((item) => transformNode2Expression(item)).filter((item) => !!item),
200
+ }));
201
+ }
202
+ }
203
+ // 处理运算
204
+ function handleBinaryExpression(calleeName, argument) {
205
+ const map = {
206
+ plus: '+',
207
+ minus: '-',
208
+ multiply: '*',
209
+ divide: '/',
210
+ remainder: '%',
211
+ };
212
+ return new naslTypes.BinaryExpression({
213
+ operator: map?.[calleeName],
214
+ left: transformNode2Expression(argument?.[0]),
215
+ right: transformNode2Expression(argument?.[1]),
216
+ });
217
+ }
218
+ // 处理数据结构
219
+ function handleNewExpression(calleeName, node, type) {
220
+ if (calleeName === 'NewList') {
221
+ return new naslTypes.NewList({
222
+ typeAnnotation: naslTypes.TypeAnnotation.createGeneric('List', {
223
+ typeArguments: node?.typeParameters?.params.map(transformTypeAnnotation),
224
+ }),
225
+ items: node?.arguments?.[0]?.elements?.map((arg) => transformNode2Expression(arg, type)),
226
+ });
227
+ }
228
+ if (calleeName === 'NewMap') {
229
+ const keys = [];
230
+ const values = [];
231
+ node?.arguments?.[0]?.properties.forEach((arg) => {
232
+ keys.push(transformNode2Expression(arg.key));
233
+ values.push(transformNode2Expression(arg.value));
234
+ });
235
+ return new naslTypes.NewMap({
236
+ typeAnnotation: naslTypes.TypeAnnotation.createGeneric('Map', {
237
+ typeArguments: node?.typeParameters?.params.map(transformTypeAnnotation),
238
+ }),
239
+ keys,
240
+ values,
241
+ });
242
+ }
243
+ if (calleeName === 'NewEntity') {
244
+ const properties = [];
245
+ const rights = [];
246
+ const assignmentLines = [];
247
+ node?.arguments?.[0]?.properties.forEach((arg, index) => {
248
+ properties.push(transformNode2Expression(arg.key));
249
+ rights.push(new naslTypes.SelectMembers({
250
+ expression: transformNode2Expression(arg.value)
251
+ }));
252
+ if (arg?.value) {
253
+ assignmentLines.push(new naslTypes.AssignmentLine({
254
+ leftIndex: [0, index],
255
+ rightIndex: [index],
256
+ }));
257
+ }
258
+ });
259
+ const typeName = node?.typeParameters?.params?.[0]?.typeName?.name;
260
+ return new naslTypes.NewComposite({
261
+ typeAnnotation: naslTypes.TypeAnnotation.createReference(typeName, {
262
+ typeNamespace: 'app.dataSources.defaultDS.entities',
263
+ typeName
264
+ }),
265
+ properties,
266
+ rights,
267
+ assignmentLines
268
+ });
269
+ }
270
+ if (calleeName === 'NewStructure') {
271
+ const properties = [];
272
+ const rights = [];
273
+ const assignmentLines = [];
274
+ node?.arguments?.[0]?.properties.forEach((arg, index) => {
275
+ properties.push(transformNode2Expression(arg.key));
276
+ rights.push(new naslTypes.SelectMembers({
277
+ expression: transformNode2Expression(arg.value)
278
+ }));
279
+ if (arg?.value) {
280
+ assignmentLines.push(new naslTypes.AssignmentLine({
281
+ leftIndex: [0, index],
282
+ rightIndex: [index],
283
+ }));
284
+ }
285
+ });
286
+ const parameters = node?.typeParameters?.params?.[0] || {};
287
+ if (parameters && parameters?.type === 'TSTypeReference' && parameters?.typeName?.type === 'TSQualifiedName') {
288
+ const { left, right } = parameters?.typeName || {};
289
+ const typeNamespace = (0, generator_1.default)(left)?.code;
290
+ const typeName = right?.name;
291
+ return new naslTypes.NewComposite({
292
+ typeAnnotation: naslTypes.TypeAnnotation.createReference(typeName, {
293
+ typeNamespace,
294
+ typeName
295
+ }),
296
+ properties,
297
+ rights,
298
+ assignmentLines
299
+ });
300
+ }
301
+ const typeName = parameters?.typeName?.name;
302
+ return new naslTypes.NewComposite({
303
+ typeAnnotation: naslTypes.TypeAnnotation.createReference(typeName, {
304
+ typeNamespace: 'app.structures',
305
+ typeName
306
+ }),
307
+ properties,
308
+ rights,
309
+ assignmentLines
310
+ });
311
+ }
312
+ if (calleeName === 'NewAnonymousStructure') {
313
+ const properties = [];
314
+ const rights = [];
315
+ const structureProperties = [];
316
+ const assignmentLines = [];
317
+ node?.arguments?.[0]?.properties?.forEach((arg, index) => {
318
+ properties.push(transformNode2Expression(arg.key));
319
+ rights.push(new naslTypes.SelectMembers({
320
+ expression: transformNode2Expression(arg.value)
321
+ }));
322
+ if (arg?.value) {
323
+ assignmentLines.push(new naslTypes.AssignmentLine({
324
+ leftIndex: [0, index],
325
+ rightIndex: [index],
326
+ }));
327
+ }
328
+ structureProperties.push(new naslTypes.StructureProperty({
329
+ name: arg?.key?.name,
330
+ typeAnnotation: null
331
+ }));
332
+ });
333
+ return new naslTypes.NewComposite({
334
+ typeAnnotation: naslTypes.TypeAnnotation.createTypeAnonymousStructure(structureProperties),
335
+ properties,
336
+ rights,
337
+ assignmentLines
338
+ });
339
+ }
340
+ return node;
341
+ }
342
+ // 处理表达式
343
+ function transformNode2Expression(node, type) {
344
+ if (!node)
345
+ return null;
346
+ fixLogicNode(node);
347
+ // console.log('lemon ~~~ transformNode2Expression:', node);
348
+ if (node.type === 'VariableDeclaration') {
349
+ return transformVariableDeclaration(node);
350
+ }
351
+ if (node.type === 'CallExpression' && node.callee.type === 'CallExpression') {
352
+ // (function match() {})(...) 的情况
353
+ }
354
+ else if (node.type === 'CallExpression') {
355
+ const callee = flatMemberExpression(node.callee);
356
+ const calleeName = (0, generator_1.default)(node.callee).code;
357
+ // console.log('lemon ~~~ CallExpression', node, callee, calleeName);
358
+ if (/^\$refs\./.test(calleeName)) {
359
+ return new naslTypes.CallLogic({
360
+ calleeNamespace: `elements.${callee[1].name}.logics`,
361
+ calleeName: callee[2].name,
362
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
363
+ expression: transformNode2Expression(arg, type),
364
+ })),
365
+ });
366
+ }
367
+ if (callee.length === 2 && callee[0].type === 'Identifier' && callee[0].name.endsWith('Entity')) {
368
+ const entityName = callee[0].name.replace(/Entity$/, '');
369
+ return new naslTypes.CallLogic({
370
+ calleeNamespace: `app.dataSources.defaultDS.entities.${entityName}.logics`,
371
+ calleeName: callee[1].name,
372
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
373
+ expression: transformNode2Expression(arg, type),
374
+ })),
375
+ });
376
+ }
377
+ if (calleeName === 'nasl.util.consoleLog' || calleeName === 'console.log') {
378
+ return new naslTypes.CallLogic({
379
+ calleeNamespace: 'nasl.util',
380
+ calleeName: 'consoleLog',
381
+ shortcut: true,
382
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
383
+ expression: transformNode2Expression(arg, type),
384
+ })),
385
+ });
386
+ }
387
+ if (calleeName.startsWith('nasl.logging.')) {
388
+ return new naslTypes.CallLogic({
389
+ calleeNamespace: 'nasl.logging',
390
+ calleeName: callee[2].name,
391
+ shortcut: true,
392
+ arguments: node.arguments.map((arg) => new naslTypes.Argument({
393
+ expression: transformNode2Expression(arg, type),
394
+ })),
395
+ });
396
+ }
397
+ if (calleeName === 'nasl.util.jsonSerialize' || calleeName === 'nasl.util.jsonDeserialize') {
398
+ const curCalleeName = node.callee.property.name;
399
+ return new naslTypes.CallLogic({
400
+ calleeNamespace: 'nasl.util',
401
+ calleeName: curCalleeName,
402
+ shortcut: true,
403
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
404
+ expression: transformNode2Expression(arg, type),
405
+ })),
406
+ typeArguments: node?.typeParameters?.params.map((curType) => transformTypeAnnotation({ ...curType })),
407
+ });
408
+ }
409
+ ;
410
+ if (calleeName.startsWith('nasl.util.')) {
411
+ let curCalleeName;
412
+ if (callee.length === 3)
413
+ curCalleeName = callee[callee.length - 1].name;
414
+ else {
415
+ let _callee = callee[0].callee;
416
+ while (_callee.type === 'CallExpression')
417
+ _callee = _callee.callee;
418
+ curCalleeName = _callee.property.name;
419
+ }
420
+ const argument = callee.length === 3 ? node.arguments : callee[0].arguments;
421
+ if (['plus', 'minus', 'multiply', 'divide', 'remainder'].includes(curCalleeName)) {
422
+ return handleBinaryExpression(curCalleeName, argument);
423
+ }
424
+ ;
425
+ if (['NewList', 'NewMap', 'NewEntity', 'NewStructure', 'NewAnonymousStructure'].includes(curCalleeName)) {
426
+ return handleNewExpression(curCalleeName, node, type);
427
+ }
428
+ const nodeElement = new naslTypes.CallFunction({
429
+ calleeNamespace: 'nasl.util',
430
+ calleeName: curCalleeName,
431
+ arguments: argument.map((arg, index) => new naslTypes.Argument({
432
+ expression: transformNode2Expression(arg, type),
433
+ keyword: `str${index + 1}`,
434
+ })),
435
+ typeArguments: node?.typeParameters?.params.map(transformTypeAnnotation),
436
+ // typeArguments: node?.typeParameters?.params.map((curType: any) => transformTypeAnnotation({ ...curType, typeNamespace })),
437
+ });
438
+ return nodeElement;
439
+ }
440
+ if (callee.length === 3 && calleeName.startsWith('nasl.ui.')) {
441
+ if (callee[2].name === 'destination') {
442
+ const namespace = node.arguments[0].value;
443
+ const nsArr = namespace.split('.').map((item) => item.replace(/_view$/, ''));
444
+ const pageType = nsArr.shift();
445
+ const viewName = nsArr.pop();
446
+ return new naslTypes.Destination({
447
+ viewNamespace: `app.frontendTypes.${pageType}.frontends.${pageType}.views${nsArr?.map((item) => `.${item}.views`)?.join('')}`,
448
+ viewName,
449
+ arguments: node.arguments.slice(1).map((arg) => new naslTypes.Argument({
450
+ expression: transformNode2Expression(arg, type),
451
+ })),
452
+ });
453
+ }
454
+ return new naslTypes.CallLogic({
455
+ calleeNamespace: 'nasl.ui',
456
+ calleeName: callee[2].name,
457
+ shortcut: true,
458
+ /**
459
+ * 这个函数是修复 AI 翻译出错的情况,与正常的 transform 做个区分
460
+ * @param node
461
+ * @returns
462
+ */
463
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
464
+ expression: transformNode2Expression(arg, type),
465
+ })),
466
+ });
467
+ }
468
+ if (calleeName.endsWith('.map')) {
469
+ return new naslTypes.CallFunction({
470
+ calleeNamespace: 'nasl.util',
471
+ calleeName: 'ListTransform',
472
+ arguments: [new naslTypes.Argument({
473
+ expression: transformNode2Expression(node.callee.object, type),
474
+ }), ...node?.arguments?.map((arg) => new naslTypes.Argument({
475
+ expression: transformNode2Expression(arg, type),
476
+ }))],
477
+ });
478
+ }
479
+ if (calleeName === 'PAGINATE') {
480
+ const newCallee = node?.arguments || [];
481
+ return new naslTypes.Paginate({
482
+ list: newCallee?.[0] && transformNode2Expression(newCallee?.[0], type),
483
+ page: newCallee?.[1] && transformNode2Expression(newCallee?.[1], type),
484
+ size: newCallee?.[2] && transformNode2Expression(newCallee?.[2], type),
485
+ });
486
+ }
487
+ if (calleeName === 'ForEach') {
488
+ const newCallee = node.arguments;
489
+ const arrowFunction = node.arguments[3];
490
+ const nodeElement = new naslTypes.ForEachStatement({
491
+ each: transformNode2Expression(newCallee[0], type),
492
+ start: transformNode2Expression(newCallee[1], type),
493
+ end: transformNode2Expression(newCallee[2], type),
494
+ item: transformParam(arrowFunction.params[0]),
495
+ index: arrowFunction.params[1] ? transformParam(arrowFunction.params[1]) : new naslTypes.Param({
496
+ name: 'index', typeAnnotation: naslTypes.TypeAnnotation.createPrimitive('Long'),
497
+ }),
498
+ body: arrowFunction.body.body.map((item) => transformNode2Expression(item, type)).filter((item) => !!item),
499
+ });
500
+ return nodeElement;
501
+ }
502
+ if (callee.length === 2) {
503
+ const curCalleeName = node.callee.property.name;
504
+ if (curCalleeName === 'forEach') {
505
+ const newCallee = node.callee.object;
506
+ const arrowFunction = node.arguments[0];
507
+ const nodeElement = new naslTypes.ForEachStatement({
508
+ each: transformNode2Expression(newCallee.callee.object, type),
509
+ start: transformNode2Expression(newCallee?.arguments?.[0], type),
510
+ end: transformNode2Expression(newCallee?.arguments?.[1], type),
511
+ item: transformParam(arrowFunction.params[0]),
512
+ index: arrowFunction.params[1] ? transformParam(arrowFunction.params[1]) : new naslTypes.Param({
513
+ name: 'index', typeAnnotation: naslTypes.TypeAnnotation.createPrimitive('Long'),
514
+ }),
515
+ body: arrowFunction.body.body.map((item) => transformNode2Expression(item, type)).filter((item) => !!item),
516
+ });
517
+ return nodeElement;
518
+ }
519
+ }
520
+ else if (['plus', 'minus', 'multiply', 'divide', 'remainder'].includes(calleeName)) {
521
+ return handleBinaryExpression(calleeName, node?.arguments);
522
+ }
523
+ else if (calleeName === 'alert') {
524
+ return new naslTypes.CallLogic({
525
+ calleeNamespace: 'nasl.ui',
526
+ calleeName: 'showMessage',
527
+ shortcut: true,
528
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
529
+ expression: transformNode2Expression(arg, type),
530
+ })),
531
+ });
532
+ }
533
+ else if (/^app.dataSources|app.logics/.test(calleeName)) {
534
+ if (calleeName?.includes('.entities.')) {
535
+ const calleeNamespace = (0, generator_1.default)(node?.callee?.object?.object)?.code;
536
+ const entityName = node?.callee?.object?.property?.name?.replace(/Entity$/, '');
537
+ return new naslTypes.CallLogic({
538
+ calleeNamespace: `${calleeNamespace}.${entityName}.logics`,
539
+ calleeName: node?.callee?.property?.name,
540
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
541
+ expression: transformNode2Expression(arg, type),
542
+ })),
543
+ });
544
+ }
545
+ return new naslTypes.CallLogic({
546
+ calleeNamespace: (0, generator_1.default)(node.callee.object).code,
547
+ calleeName: callee[callee.length - 1].name,
548
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
549
+ expression: transformNode2Expression(arg, type),
550
+ })),
551
+ });
552
+ }
553
+ else if (callee.length === 1) {
554
+ if (calleeName.startsWith('viewLogic_')) {
555
+ return new naslTypes.CallLogic({
556
+ calleeNamespace: '',
557
+ calleeName: calleeName.slice('viewLogic_'.length),
558
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
559
+ expression: transformNode2Expression(arg, type),
560
+ })),
561
+ });
562
+ }
563
+ if (calleeName === 'FROM') {
564
+ // TODO
565
+ return new naslTypes.CallLogic({
566
+ calleeNamespace: `app.logics`,
567
+ calleeName,
568
+ arguments: [],
569
+ });
570
+ }
571
+ return new naslTypes.CallLogic({
572
+ calleeNamespace: `app.logics`,
573
+ calleeName,
574
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
575
+ expression: transformNode2Expression(arg, type),
576
+ })),
577
+ });
578
+ }
579
+ else if (/interfaces/.test(calleeName)) {
580
+ return new naslTypes.CallInterface({
581
+ calleeNamespace: (0, generator_1.default)(node.callee.object).code,
582
+ calleeName: callee[callee.length - 1].name,
583
+ arguments: node?.arguments?.map((arg) => arg?.properties?.map((item) => new naslTypes.Argument({
584
+ keyword: item?.key?.name,
585
+ expression: transformNode2Expression(item?.value, type),
586
+ }))).flat(),
587
+ });
588
+ }
589
+ else if (/connector./.test(calleeName)) {
590
+ const flatCalleeKey = (0, generator_1.default)(node?.callee)?.code;
591
+ const [, calleeConnectionName, calleeNamespace, calleeFunName] = flatCalleeKey?.match(/^(\w+)\.([\w.]+)\.(\w+)$/);
592
+ return new naslTypes.CallConnector({
593
+ calleeConnectionName,
594
+ calleeNamespace,
595
+ calleeName: calleeFunName,
596
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
597
+ expression: transformNode2Expression(arg, type),
598
+ })),
599
+ });
600
+ }
601
+ else if (/extensions./.test(calleeName)) {
602
+ return new naslTypes.CallLogic({
603
+ calleeNamespace: (0, generator_1.default)(node?.callee?.object)?.code,
604
+ calleeName: callee?.[callee?.length - 1]?.name,
605
+ handleError: true,
606
+ arguments: node?.arguments?.map((arg) => new naslTypes.Argument({
607
+ expression: transformNode2Expression(arg, type),
608
+ })),
609
+ });
610
+ }
611
+ else if (node.callee.type === 'ArrowFunctionExpression') {
612
+ // NOTE: 适用于 if else
613
+ const newCallee = node.callee.body.body;
614
+ if (newCallee[newCallee.length - 1].argument?.callee?.name === '__MatchExpressionFuntion') {
615
+ const match = new naslTypes.Match({
616
+ expression: transformNode2Expression(newCallee[0], type),
617
+ isExpression: type !== 'logic',
618
+ cases: flatIfStatement(newCallee[1].body.body[0]).map((_case) => new naslTypes.MatchCase({
619
+ patterns: !_case.test ? [] : flatMatchPatternsExpression(transformNode2Expression(_case.test, type)),
620
+ body: _case.consequent.body.filter((item) => item.type !== 'BreakStatement').map((item) => transformNode2Expression(item, type)).filter((item) => !!item),
621
+ })),
622
+ });
623
+ if (!match.cases.length || match.cases[match.cases.length - 1].patterns.length) {
624
+ match.cases.push(new naslTypes.MatchCase({
625
+ patterns: [],
626
+ body: [],
627
+ }));
628
+ }
629
+ match.cases.forEach((case_) => {
630
+ if (case_.body.length && (case_.body[0].concept === 'BooleanLiteral' || case_.body[0].concept === 'StringLiteral')) {
631
+ case_.isMatchedTypeEnumable = true;
632
+ }
633
+ if (case_.patterns.length && case_.patterns[0].concept === 'MemberExpression') {
634
+ case_.isMatchedTypeEnumable = true;
635
+ case_.patterns[0] = new naslTypes.MemberExpression({
636
+ object: {
637
+ concept: 'Identifier',
638
+ name: case_.patterns[0].object.property.name,
639
+ folded: false,
640
+ namespace: 'app.enums'
641
+ },
642
+ property: {
643
+ concept: 'Identifier',
644
+ name: case_.patterns[0].property.value,
645
+ folded: false,
646
+ },
647
+ });
648
+ }
649
+ });
650
+ return match;
651
+ }
652
+ if (newCallee[newCallee.length - 1].argument?.callee?.name === '__SwitchExpressionFuntion') {
653
+ const switchStatement = transformNode2Expression(newCallee[0].body.body[0], type);
654
+ return switchStatement;
655
+ }
656
+ throwError(`Unhandled ArrowFunctionExpression node ${node.type}`);
657
+ }
658
+ else {
659
+ throwError(`Unhandled node ${callee.map((item) => item.name).join('.')} ${node.type}`);
660
+ }
661
+ }
662
+ else if (node.type === 'IfStatement') {
663
+ if (node.alternate && node.alternate.type === 'IfStatement') {
664
+ const switchStatement = new naslTypes.SwitchStatement({
665
+ cases: [],
666
+ });
667
+ pushElseIf(node, switchStatement);
668
+ return switchStatement;
669
+ }
670
+ let consequentIndex;
671
+ let alternateIndex;
672
+ const naslNode = new naslTypes.IfStatement({
673
+ test: transformNode2Expression(node.test, type),
674
+ consequent: !node.consequent ? [] : node.consequent.body.map((item, index) => {
675
+ if (item?.type === 'ReturnStatement') {
676
+ item.ends = true;
677
+ if (item?.argument) {
678
+ consequentIndex = index;
679
+ }
680
+ }
681
+ return transformNode2Expression(item, type);
682
+ }).filter((item) => !!item),
683
+ alternate: !node.alternate ? [] : node.alternate.body.map((item, index) => {
684
+ if (item?.type === 'ReturnStatement') {
685
+ item.ends = true;
686
+ if (item?.argument) {
687
+ alternateIndex = index;
688
+ }
689
+ }
690
+ return transformNode2Expression(item, type);
691
+ }).filter((item) => !!item),
692
+ });
693
+ if (consequentIndex !== undefined) {
694
+ naslNode?.consequent?.splice(consequentIndex + 1, 0, new naslTypes.End());
695
+ }
696
+ if (alternateIndex !== undefined) {
697
+ naslNode?.alternate?.splice(alternateIndex + 1, 0, new naslTypes.End());
698
+ }
699
+ return naslNode;
700
+ }
701
+ else if (node.type === 'WhileStatement') {
702
+ return new naslTypes.WhileStatement({
703
+ test: transformNode2Expression(node.test, type),
704
+ body: node.body.body.map((item) => transformNode2Expression(item, type)).filter((item) => !!item),
705
+ });
706
+ }
707
+ else if (node.type === 'SwitchStatement') {
708
+ const match = new naslTypes.Match({
709
+ expression: transformNode2Expression(node.discriminant, type),
710
+ isExpression: type !== 'logic',
711
+ cases: node.cases.map((_case) => new naslTypes.MatchCase({
712
+ patterns: !_case.test ? [] : [transformNode2Expression(_case.test, type)],
713
+ body: _case.consequent.filter((item) => item.type !== 'BreakStatement').map((item) => transformNode2Expression(item, type)).filter((item) => !!item),
714
+ })),
715
+ });
716
+ if (!match.cases.length || match.cases[match.cases.length - 1].patterns.length) {
717
+ match.cases.push(new naslTypes.MatchCase({
718
+ patterns: [],
719
+ body: [],
720
+ }));
721
+ }
722
+ match.cases.forEach((case_) => {
723
+ if (case_.body.length && (case_.body[0].concept === 'BooleanLiteral' || case_.body[0].concept === 'StringLiteral')) {
724
+ case_.isMatchedTypeEnumable = true;
725
+ }
726
+ if (case_.patterns.length && case_.patterns[0].concept === 'MemberExpression') {
727
+ case_.isMatchedTypeEnumable = true;
728
+ case_.patterns[0].object.namespace = 'app.enums';
729
+ }
730
+ });
731
+ return match;
732
+ }
733
+ else if (node.type === 'MemberExpression') {
734
+ const callee = flatMemberExpression(node);
735
+ const calleeName = (0, generator_1.default)(node)?.code;
736
+ if (calleeName?.includes('app.enums')) {
737
+ return new naslTypes.MemberExpression({
738
+ object: new naslTypes.Identifier({
739
+ namespace: 'app.enums',
740
+ name: callee?.[2]?.name,
741
+ }),
742
+ property: new naslTypes.Identifier({
743
+ name: callee?.[3]?.value || callee?.[3]?.name,
744
+ }),
745
+ });
746
+ }
747
+ if (node.property.type === 'NumericLiteral') {
748
+ return new naslTypes.CallFunction({
749
+ calleeNamespace: 'nasl.util',
750
+ calleeName: 'Get',
751
+ arguments: [
752
+ new naslTypes.Argument({
753
+ expression: transformNode2Expression(node.object, type),
754
+ }),
755
+ new naslTypes.Argument({
756
+ expression: transformNode2Expression(node.property, type),
757
+ }),
758
+ ],
759
+ });
760
+ }
761
+ return new naslTypes.MemberExpression({
762
+ object: transformNode2Expression(node.object, type),
763
+ property: transformNode2Expression(node.property, type),
764
+ });
765
+ }
766
+ else if (node.type === 'Identifier') {
767
+ return new naslTypes.Identifier({
768
+ name: node.name,
769
+ });
770
+ }
771
+ else if (node.type === 'ExpressionStatement') {
772
+ return transformNode2Expression(node.expression, type);
773
+ }
774
+ else if (node.type === 'AssignmentExpression') {
775
+ if (node.operator === '+=' || node.operator === '-=') {
776
+ if (type === 'logic') {
777
+ return new naslTypes.Assignment({
778
+ left: transformNode2Expression(node.left, type),
779
+ right: new naslTypes.BinaryExpression({
780
+ operator: node.operator[0],
781
+ left: transformNode2Expression(node.left, type),
782
+ right: transformNode2Expression(node.right, type),
783
+ }),
784
+ });
785
+ }
786
+ return new naslTypes.BinaryExpression({
787
+ operator: node.operator[0],
788
+ left: transformNode2Expression(node.left, type),
789
+ right: transformNode2Expression(node.right, type),
790
+ });
791
+ }
792
+ if (type !== 'logic') {
793
+ return transformNode2Expression(node.right, type);
794
+ }
795
+ return new naslTypes.Assignment({
796
+ left: transformNode2Expression(node.left, type),
797
+ right: transformNode2Expression(node.right, type),
798
+ });
799
+ }
800
+ else if (node.type === 'NewExpression') {
801
+ const calleeName = (0, generator_1.default)(node.callee).code;
802
+ if (['Boolean', 'Integer', 'Double', 'Decimal', 'Long'].includes(calleeName)) {
803
+ return transformNode2Expression(node.arguments[0], type);
804
+ }
805
+ throwError(`Unhandled node ${node.type}`);
806
+ }
807
+ else if (node.type === 'ArrowFunctionExpression') {
808
+ return new naslTypes.AnonymousFunction({
809
+ params: node.params.map((param) => transformParam(param)),
810
+ body: transformNode2Expression(node.body, type),
811
+ });
812
+ }
813
+ else if (node.type === 'BooleanLiteral') {
814
+ return new naslTypes.BooleanLiteral({
815
+ value: String(node.value),
816
+ });
817
+ }
818
+ else if (node.type === 'StringLiteral') {
819
+ return new naslTypes.StringLiteral({
820
+ value: node.value,
821
+ });
822
+ }
823
+ else if (node.type === 'NumericLiteral') {
824
+ const literal = new naslTypes.NumericLiteral({
825
+ value: String(node.value),
826
+ typeAnnotation: naslTypes.TypeAnnotation.createPrimitive('Integer'),
827
+ });
828
+ literal.typeAnnotation.typeName = literal.changeType(String(node.value));
829
+ return literal;
830
+ }
831
+ else if (node.type === 'NullLiteral') {
832
+ return new naslTypes.NullLiteral();
833
+ }
834
+ else if (node.type === 'TemplateLiteral') {
835
+ const expressions = [...node.expressions, ...node.quasis.map((element) => ({
836
+ type: 'StringLiteral',
837
+ value: element.value.raw,
838
+ start: element.start,
839
+ end: element.end,
840
+ }))];
841
+ expressions.sort((a, b) => a.start - b.start);
842
+ return new naslTypes.StringInterpolation({
843
+ expressions: expressions.map((item) => transformNode2Expression(item, type)),
844
+ });
845
+ }
846
+ else if (node.type === 'BinaryExpression' || node.type === 'LogicalExpression') {
847
+ if (node.operator === '===')
848
+ node.operator = '==';
849
+ if (node.operator === '!==')
850
+ node.operator = '!=';
851
+ if (['+', '-', '*', '/', '%', '==', '!=', '>', '<', '>=', '<=', '&&', '||', 'startwith', 'endwith', 'like', 'in'].includes(node.operator)) {
852
+ return new naslTypes.BinaryExpression({
853
+ operator: node.operator,
854
+ left: transformNode2Expression(node.left, type),
855
+ right: transformNode2Expression(node.right, type),
856
+ });
857
+ }
858
+ throwError(`Unhandled node ${node.type}`);
859
+ }
860
+ else if (node.type === 'UnaryExpression') {
861
+ if (['!'].includes(node.operator)) {
862
+ return new naslTypes.UnaryExpression({
863
+ operator: node.operator,
864
+ argument: transformNode2Expression(node.argument, type),
865
+ });
866
+ }
867
+ if (['-'].includes(node.operator) && node.argument.type === 'NumericLiteral') {
868
+ return transformNode2Expression({
869
+ type: 'NumericLiteral',
870
+ value: -node.argument.value,
871
+ }, type);
872
+ }
873
+ throwError(`Unhandled node ${node.type}`);
874
+ }
875
+ else if (node.type === 'UpdateExpression') {
876
+ if (node.operator === '++' || node.operator === '--') {
877
+ return new naslTypes.Assignment({
878
+ left: transformNode2Expression(node.argument, type),
879
+ right: new naslTypes.BinaryExpression({
880
+ operator: node.operator[0],
881
+ left: transformNode2Expression(node.argument, type),
882
+ right: new naslTypes.NumericLiteral({
883
+ value: '1',
884
+ typeAnnotation: naslTypes.TypeAnnotation.createPrimitive('Integer'),
885
+ }),
886
+ }),
887
+ });
888
+ }
889
+ }
890
+ else if (node.type === 'ReturnStatement') {
891
+ if (node?.ends) {
892
+ return new naslTypes.End();
893
+ }
894
+ }
895
+ else if (node.type === 'EmptyStatement') {
896
+ return node.leadingComments && new naslTypes.Comment({
897
+ value: String(node.leadingComments[0].value),
898
+ });
899
+ }
900
+ else if (node.type === 'BlockStatement') {
901
+ return transformNode2Expression(node?.body?.[0], type);
902
+ }
903
+ else if (node.type === 'ObjectExpression' && node?.properties?.length > 0) {
904
+ const properties = [];
905
+ const rights = [];
906
+ const structureProperties = [];
907
+ const assignmentLines = [];
908
+ node?.properties?.forEach((arg, index) => {
909
+ properties.push(transformNode2Expression(arg.key, type));
910
+ rights.push(new naslTypes.SelectMembers({
911
+ expression: transformNode2Expression(arg?.value, type)
912
+ }));
913
+ if (arg?.value) {
914
+ assignmentLines.push(new naslTypes.AssignmentLine({
915
+ leftIndex: [0, index],
916
+ rightIndex: [index],
917
+ }));
918
+ }
919
+ structureProperties.push(new naslTypes.StructureProperty({
920
+ name: arg?.key?.name,
921
+ typeAnnotation: null
922
+ }));
923
+ });
924
+ return new naslTypes.NewComposite({
925
+ typeAnnotation: naslTypes.TypeAnnotation.createTypeAnonymousStructure(structureProperties),
926
+ properties,
927
+ rights,
928
+ assignmentLines
929
+ });
930
+ }
931
+ else {
932
+ throwError(`Unhandled node ${node.type}`);
933
+ }
934
+ }
935
+ // 处理逻辑
936
+ function transformNode2Logic(node, name) {
937
+ const parameters = node.params;
938
+ const statements = node.body.body;
939
+ const curLogic = new naslTypes.Logic({ name: name ?? node.id.name });
940
+ parameters.forEach((item) => {
941
+ const param = transformParam(item);
942
+ if (param && param.name !== 'event' && !curLogic.params.find((_) => _.name === param.name))
943
+ curLogic.addParam(param);
944
+ });
945
+ statements.forEach((item, index) => {
946
+ if (item.type === 'ReturnStatement' && item?.argument) {
947
+ if (!curLogic.returns.length) {
948
+ curLogic.returns.push(new naslTypes.Return({
949
+ name: 'result',
950
+ }));
951
+ }
952
+ const logicItem = new naslTypes.Assignment({
953
+ left: new naslTypes.Identifier({
954
+ name: curLogic.returns[0].name,
955
+ }),
956
+ right: transformNode2Expression(item.argument, 'logic')
957
+ });
958
+ curLogic.insertItemInBodyAt(logicItem, index + 1);
959
+ }
960
+ else {
961
+ let logicItem = transformNode2Expression(item, 'logic');
962
+ if (logicItem) {
963
+ if (logicItem.concept === 'Variable') {
964
+ if (!curLogic.variables.find((_) => _.name === logicItem.name))
965
+ curLogic.addVariable(logicItem);
966
+ logicItem = new naslTypes.Assignment({
967
+ left: new naslTypes.Identifier({ name: logicItem?.name }),
968
+ right: logicItem.defaultValue?.expression || '',
969
+ });
970
+ }
971
+ curLogic.insertItemInBodyAt(logicItem, index + 1);
972
+ }
973
+ }
974
+ });
975
+ return curLogic;
976
+ }
977
+ function transformNode2ViewElement(node, componentName) {
978
+ const viewNode = node.arguments?.[0];
979
+ if (viewNode.type === 'ObjectExpression') {
980
+ const tag = (0, lodash_1.kebabCase)(node?.callee.name);
981
+ const name = componentName?.replace(/-/g, '_');
982
+ const newViewElement = new naslTypes.ViewElement({
983
+ tag,
984
+ name,
985
+ });
986
+ viewNode.properties.forEach((prop, propIndex) => {
987
+ if (prop.value.type === 'ArrayExpression' && ['FunctionExpression', 'ArrowFunctionExpression'].includes(prop.value.elements[0].type)) {
988
+ // 事件逻辑
989
+ const eventName = prop?.key?.name?.replace(/^on/, '')?.toLowerCase();
990
+ const bindEvent = new naslTypes.BindEvent({ name: eventName });
991
+ prop.value.elements.forEach((element) => {
992
+ const logicName = bindEvent.getLogicUniqueName();
993
+ const curLogic = transformNode2Logic(element, logicName);
994
+ bindEvent.addLogic(curLogic);
995
+ });
996
+ newViewElement.addBindEvent(bindEvent);
997
+ }
998
+ else if (['FunctionExpression', 'ArrowFunctionExpression'].includes(prop.value.type) && ['ArrayExpression'].includes(prop.value.body?.type)) {
999
+ // 子组件
1000
+ const slotTarget = prop.key.name.replace(/^slot/, '').toLowerCase();
1001
+ if (slotTarget === 'default') {
1002
+ // 默认插槽,不需要 template
1003
+ if (prop.value.body?.elements?.length) {
1004
+ prop.value.body.elements.forEach((element, index) => {
1005
+ // $ref.componentName = new xxx({}) 形式,这种是标准的
1006
+ if (element.type === 'AssignmentExpression' && element.right?.type === 'NewExpression') {
1007
+ const elementName = element?.left?.property?.name;
1008
+ newViewElement.addViewElement(transformNode2ViewElement(element.right, elementName));
1009
+ }
1010
+ // new xxx({}) 形式,这种是没有组件名称,为了兼容,自己建一个
1011
+ if (element.type === 'NewExpression') {
1012
+ const eleTag = (0, lodash_1.kebabCase)(element?.callee.name);
1013
+ const eleName = `${eleTag}_${index}_${newViewElement.name}`;
1014
+ newViewElement.addViewElement(transformNode2ViewElement(element, eleName));
1015
+ }
1016
+ });
1017
+ }
1018
+ }
1019
+ else {
1020
+ const slotScope = prop.value?.params[0]?.name || '';
1021
+ const newTemplateElement = new naslTypes.ViewElement({
1022
+ tag: 'template',
1023
+ slotTarget,
1024
+ slotScope,
1025
+ });
1026
+ if (prop.value.body?.elements?.length) {
1027
+ prop.value.body.elements.forEach((element, index) => {
1028
+ // $ref.componentName = new xxx({}) 形式,这种是标准的
1029
+ if (element.type === 'AssignmentExpression' && element.right?.type === 'NewExpression') {
1030
+ newTemplateElement.name = `template_${(0, generator_2.genHash)(`${slotTarget}_template_${propIndex}_${name}`)}`;
1031
+ const elementName = element?.left?.property?.name;
1032
+ newTemplateElement.addViewElement(transformNode2ViewElement(element.right, elementName));
1033
+ }
1034
+ // new xxx({}) 形式,这种是没有组件名称,为了兼容,自己建一个
1035
+ if (element.type === 'NewExpression') {
1036
+ newTemplateElement.name = `template_${(0, generator_2.genHash)(`${slotTarget}_template_${propIndex}_${name}`)}`;
1037
+ const eleTag = (0, lodash_1.kebabCase)(element?.callee.name);
1038
+ const eleName = `${eleTag}_${index}_${newTemplateElement.name}`;
1039
+ newTemplateElement.addViewElement(transformNode2ViewElement(element, eleName));
1040
+ }
1041
+ });
1042
+ }
1043
+ newViewElement.addViewElement(newTemplateElement);
1044
+ }
1045
+ }
1046
+ else {
1047
+ // 属性
1048
+ if (['StringLiteral', 'NumericLiteral'].includes(prop.value.type)) {
1049
+ newViewElement.addBindAttribute(new naslTypes.BindAttribute({
1050
+ name: prop.key.name,
1051
+ type: 'string',
1052
+ value: prop.value.value,
1053
+ }));
1054
+ }
1055
+ else if (['ArrowFunctionExpression'].includes(prop.value.type)) {
1056
+ newViewElement.addBindAttribute(new naslTypes.BindAttribute({
1057
+ name: prop.key.name,
1058
+ type: 'string',
1059
+ value: (0, generator_1.default)(prop.value.body.property).code,
1060
+ }));
1061
+ }
1062
+ else {
1063
+ // ['TemplateLiteral', 'BooleanLiteral', 'NullLiteral', 'CallExpression']
1064
+ newViewElement.addBindAttribute(new naslTypes.BindAttribute({
1065
+ name: prop.key.name,
1066
+ type: 'dynamic',
1067
+ expression: transformNode2Expression(prop.value),
1068
+ }));
1069
+ }
1070
+ }
1071
+ });
1072
+ return newViewElement;
1073
+ }
1074
+ }
1075
+ /**
1076
+ * 转换Node为View下的构件
1077
+ */
1078
+ function transformNode2ViewConstruct(node) {
1079
+ // console.log("lemon ~ transformNode2ViewConstruct ~ node:", node);
1080
+ // 变量声明
1081
+ if (node.type === 'VariableDeclaration') {
1082
+ return transformVariableDeclaration(node);
1083
+ }
1084
+ // 页面逻辑
1085
+ if (node.type === 'FunctionDeclaration') {
1086
+ const logicName = node.id.name.replace(/^viewLogic_/, '');
1087
+ return transformNode2Logic(node, logicName);
1088
+ }
1089
+ if (node.type === 'ExpressionStatement') {
1090
+ return transformNode2ViewConstruct(node.expression);
1091
+ }
1092
+ // 组件
1093
+ if (node.type === 'AssignmentExpression' && node.right?.type === 'NewExpression') {
1094
+ const componentName = node?.left?.property?.name;
1095
+ return transformNode2ViewElement(node.right, componentName);
1096
+ }
1097
+ if (node.type === 'ReturnStatement' && node?.argument?.type === 'CallExpression') {
1098
+ return transformNode2ViewConstruct(node.argument.arguments?.[1]);
1099
+ }
1100
+ // throwError(`Unhandled node ${node}`);
1101
+ console.error('warning: Unhandled node', node);
1102
+ return null;
1103
+ }
1104
+ /**
1105
+ * 转换Node为View
1106
+ */
1107
+ function transformNode2View(node, root) {
1108
+ const parameters = node.params;
1109
+ let statements = node.body.body;
1110
+ const currentPositionComment = root?.comments.find((comment) => comment.type === 'CommentLine' && comment.value === ' 当前页面');
1111
+ if (currentPositionComment) {
1112
+ statements = statements.filter((stat) => stat.start > currentPositionComment.start);
1113
+ }
1114
+ const view = new naslTypes.View();
1115
+ parameters.forEach((item) => {
1116
+ const param = transformParam(item);
1117
+ param && view.params.push(param);
1118
+ });
1119
+ statements.forEach((item) => {
1120
+ const viewItem = transformNode2ViewConstruct(item);
1121
+ if (item.type === 'ReturnStatement' && item?.argument?.type === 'CallExpression') {
1122
+ const action = item.argument?.callee?.name;
1123
+ const selectedNodeName = item.argument.arguments?.[0]?.property?.name;
1124
+ view.aiParams = { selectedNodeName, action };
1125
+ }
1126
+ if (viewItem?.concept === 'Variable') {
1127
+ if (!view.variables.find((_) => _.name === viewItem.name))
1128
+ view.addVariable(viewItem);
1129
+ }
1130
+ if (viewItem?.concept === 'Logic') {
1131
+ if (!view.logics.find((_) => _.name === viewItem.name))
1132
+ view.addLogic(viewItem);
1133
+ }
1134
+ if (viewItem?.concept === 'ViewElement') {
1135
+ // viewItem.name = view.getViewElementUniqueName(viewItem.name);
1136
+ view.addViewElement(viewItem);
1137
+ }
1138
+ });
1139
+ // console.log("lemon ~ 转换出的 view:", view);
1140
+ return view;
1141
+ }
1142
+ /**
1143
+ * 转换ts代码为View
1144
+ */
1145
+ const transformTS2View = (tsCode) => {
1146
+ const root = babel.parseSync(tsCode, {
1147
+ filename: 'result.ts',
1148
+ presets: [require('@babel/preset-typescript')],
1149
+ });
1150
+ let func;
1151
+ if (root.program?.body[0]?.type === 'ExportNamedDeclaration') {
1152
+ func = root.program?.body[0]?.declaration;
1153
+ }
1154
+ else {
1155
+ func = root.program?.body[0];
1156
+ }
1157
+ // console.log("lemon ~ 初始 node", func);
1158
+ return transformNode2View(func, root);
1159
+ };
1160
+ function tryTransformTS2UI(tsCode) {
1161
+ if (tsCode.includes('```')) {
1162
+ const cap = tsCode.match(/```.*\n([\s\S]+?)```/);
1163
+ if (cap)
1164
+ tsCode = cap[1].trim();
1165
+ }
1166
+ const view = transformTS2View(tsCode);
1167
+ return {
1168
+ view,
1169
+ ...view.aiParams
1170
+ };
1171
+ }
1172
+ exports.tryTransformTS2UI = tryTransformTS2UI;
1173
+ //# sourceMappingURL=transformTS2UI.js.map