-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathcode.ts
1668 lines (1590 loc) · 44 KB
/
code.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs'
import path from 'path'
import {
camelize,
capitalize,
hasOwn,
isArray,
isPlainObject,
isString,
} from '@vue/shared'
import type {
ArrowFunctionExpression,
BindingIdentifier,
ClassDeclaration,
ClassExpression,
Expression,
FunctionDeclaration,
FunctionExpression,
HasDecorator,
Identifier,
Module,
Param,
Span,
TsFnParameter,
TsInterfaceDeclaration,
TsParameterProperty,
TsType,
TsTypeAliasDeclaration,
TsTypeAnnotation,
TsTypeElement,
VariableDeclaration,
VariableDeclarationKind,
} from '../types/types'
import {
ERR_MSG_PLACEHOLDER,
createResolveTypeReferenceName,
isColorSupported,
parseKotlinPackageWithPluginId,
relative,
} from './utils'
import { normalizePath } from './shared'
import { parseUTSSyntaxError } from './stacktrace'
import type { SyncUniModulesFilePreprocessor } from './uni_modules'
const IOS_HOOK_CLASS = 'UTSiOSHookProxy'
const ANDROID_HOOK_CLASS = 'UTSAndroidHookProxy'
function isHookClass(name: string) {
return name === ANDROID_HOOK_CLASS || name === IOS_HOOK_CLASS
}
export const enum FORMATS {
ES = 'es',
CJS = 'cjs',
}
export interface ClassMeta {
typeParams?: boolean
interfaces: string[]
keepAliveMethods: string[]
}
// 不应该用 class,应该用lit,调整起来影响较多,暂不调整
type Types = {
interface: Record<string, { returned: boolean; decl: TsInterfaceDeclaration }>
class: Record<string, ClassMeta>
fn: Record<string, Param[]>
alias: Record<string, {}>
uni?: string[]
}
interface Meta {
typeParams: string[]
exports: Record<
string,
{
type: 'var' | 'function' | 'class' | 'interface'
params?: Parameter[]
}
>
types: Record<
string,
'function' | 'class' | 'interface' | 'typealias' | string[]
>
components: string[]
customElements: string[]
android?: {
typeParams: string[]
types: Record<
string,
'function' | 'class' | 'interface' | 'typealias' | string[]
>
}
ios?: {
typeParams: string[]
types: Record<
string,
'function' | 'class' | 'interface' | 'typealias' | string[]
>
}
}
export interface GenProxyCodeOptions {
is_uni_modules: boolean
id: string
name: string
extname: string
namespace: string
androidComponents?: Record<string, string>
iosComponents?: Record<string, string>
customElements?: Record<string, string>
format?: FORMATS
inputDir?: string
pluginRelativeDir?: string
moduleName?: string
moduleType?: string
types?: Types
meta?: Meta
isExtApi?: boolean
androidHookClass?: string
iOSHookClass?: string
androidPreprocessor?: SyncUniModulesFilePreprocessor
iosPreprocessor?: SyncUniModulesFilePreprocessor
}
export async function genProxyCode(
module: string,
options: GenProxyCodeOptions
) {
const { name, is_uni_modules, format, moduleName, moduleType } = options
options.inputDir = options.inputDir || process.env.UNI_INPUT_DIR
if (!options.meta) {
options.meta = {
exports: {},
types: {},
typeParams: [],
components: [],
customElements: [],
}
}
options.types = await parseInterfaceTypes(module, options)
options.meta!.types = parseMetaTypes(options.types)
options.meta!.typeParams = parseTypeParams(options.types)
if (options.androidPreprocessor) {
// 内置 ext-api 需要分平台解析interface
const androidTypes = await parseInterfaceTypes(
module,
options,
options.androidPreprocessor
)
options.meta!.android = {
typeParams: parseTypeParams(androidTypes),
types: parseMetaTypes(androidTypes),
}
}
if (options.iosPreprocessor) {
const iosTypes = await parseInterfaceTypes(
module,
options,
options.iosPreprocessor
)
options.meta!.ios = {
typeParams: parseTypeParams(iosTypes),
types: parseMetaTypes(iosTypes),
}
}
const components = new Set<string>()
// 自动补充 VideoElement 导出
if (options.androidComponents) {
Object.keys(options.androidComponents).forEach((name) => {
const className =
(process.env.UNI_UTS_MODULE_PREFIX ? 'Uni' : '') +
capitalize(camelize(name)) +
'Element'
options.meta!.types[className] = 'class'
if (options.meta?.android?.types) {
options.meta.android.types[className] = 'class'
}
components.add(name)
})
}
if (options.iosComponents) {
Object.keys(options.iosComponents).forEach((name) => {
const className =
(process.env.UNI_UTS_MODULE_PREFIX ? 'Uni' : '') +
capitalize(camelize(name)) +
'Element'
options.meta!.types[className] = 'class'
if (options.meta?.ios?.types) {
options.meta.ios.types[className] = 'class'
}
components.add(name)
})
}
options.meta.components = [...components]
const decls = await parseModuleDecls(module, options)
normalizeInterfaceKeepAlive(decls, options.types)
return `
const { registerUTSInterface, initUTSProxyClass, initUTSProxyFunction, initUTSPackageName, initUTSIndexClassName, initUTSClassName } = uni
const name = '${name}'
const moduleName = '${moduleName || ''}'
const moduleType = '${moduleType || ''}'
const errMsg = \`${ERR_MSG_PLACEHOLDER}\`
const is_uni_modules = ${is_uni_modules}
const pkg = /*#__PURE__*/ initUTSPackageName(name, is_uni_modules)
const cls = /*#__PURE__*/ initUTSIndexClassName(name, is_uni_modules)
${
format === FORMATS.CJS
? `
const exports = { __esModule: true }
`
: ''
}
${genComponentsCode(
format,
options.androidComponents || {},
options.iosComponents || {}
)}${genCustomElementsCode(format, options.customElements || {})}
${genModuleCode(decls, format, options.pluginRelativeDir!, options.meta!)}
`
}
// 查找实现该interface的class中是否有keepAlive方法,有则标记为keepAlive
function normalizeInterfaceKeepAlive(decls: ProxyDecl[], types: Types) {
const classTypes = types.class
if (!classTypes) {
return
}
const classNames = Object.keys(classTypes)
decls.forEach((decl) => {
if (decl.type === 'InterfaceDeclaration') {
classNames.find((n) => {
const classMeta = classTypes[n]
if (classMeta.interfaces && classMeta.interfaces.includes(decl.cls)) {
classMeta.keepAliveMethods.forEach((method) => {
const jsMethod = method + 'ByJs'
if (decl.options.methods[jsMethod]) {
decl.options.methods[jsMethod].keepAlive = true
}
})
}
})
}
})
}
function parseMetaTypes(types: Types) {
let res: Meta['types'] = {
uni: types.uni || [],
}
Object.keys(types.class).forEach((n) => {
res[n] = 'class'
})
Object.keys(types.fn).forEach((n) => {
res[n] = 'function'
})
Object.keys(types.interface).forEach((n) => {
res[n] = 'interface'
})
Object.keys(types.alias).forEach((n) => {
res[n] = 'typealias'
})
return res
}
function parseTypeParams(types: Types) {
let res: Meta['typeParams'] = []
Object.keys(types.class).forEach((n) => {
if (types.class[n].typeParams) {
res.push(n)
}
})
return res
}
function genComponentsCode(
format: FORMATS = FORMATS.ES,
androidComponents: Record<string, string>,
iosComponents: Record<string, string>
) {
const codes: string[] = []
Object.keys(Object.assign({}, androidComponents, iosComponents)).forEach(
(name) => {
if (format === FORMATS.CJS) {
codes.push(`exports.${capitalize(camelize(name))}Component = {}`)
} else {
codes.push(`export const ${capitalize(camelize(name))}Component = {}`)
}
}
)
return codes.join('\n')
}
function genCustomElementsCode(
format: FORMATS = FORMATS.ES,
customElements: Record<string, string>
) {
const codes: string[] = []
Object.keys(customElements).forEach((name) => {
if (format === FORMATS.CJS) {
codes.push(`exports.${capitalize(camelize(name))}Element = {}`)
} else {
codes.push(`export const ${capitalize(camelize(name))}Element = {}`)
}
})
if (codes.length) {
codes.unshift('\n')
}
return codes.join('\n')
}
export function resolveRootIndex(module: string, options: GenProxyCodeOptions) {
const filename = path.resolve(
module,
options.is_uni_modules ? 'utssdk' : '',
`index${options.extname}`
)
return fs.existsSync(filename) ? filename : ''
}
export function resolveRootInterface(
module: string,
options: GenProxyCodeOptions
) {
const filename = path.resolve(
module,
options.is_uni_modules ? 'utssdk' : '',
`interface${options.extname}`
)
return fs.existsSync(filename) ? filename : ''
}
export function resolvePlatformIndexFilename(
platform: 'app-android' | 'app-ios',
module: string,
options: GenProxyCodeOptions
) {
return path.resolve(
module,
options.is_uni_modules ? 'utssdk' : '',
platform,
`index${options.extname}`
)
}
export function resolvePlatformIndex(
platform: 'app-android' | 'app-ios',
module: string,
options: GenProxyCodeOptions
) {
const filename = resolvePlatformIndexFilename(platform, module, options)
return fs.existsSync(filename) ? filename : ''
}
function exportDefaultCode(format: FORMATS) {
return format === FORMATS.ES
? 'export default /*#__PURE__*/ '
: 'exports.default = '
}
function exportVarCode(format: FORMATS, kind: VariableDeclarationKind) {
if (format === FORMATS.ES) {
return `export ${kind} `
}
return `exports.`
}
function isClassReturnOptions(value: unknown): value is { options: string } {
return (
isPlainObject(value) &&
(value as any).type === 'interface' &&
isString((value as any).options)
)
}
function genClassOptionsCode(
options: ProxyClass['options'] | ProxyInterface['options']
): string {
return JSON.stringify(options, (key, value) => {
if (key === 'return' && isClassReturnOptions(value)) {
return { type: 'interface', options: `${value.options}Options` }
}
return value
})
}
function genModuleCode(
decls: ProxyDecl[],
format: FORMATS = FORMATS.ES,
pluginRelativeDir: string,
meta: Meta
) {
const codes: string[] = []
const exportDefault = exportDefaultCode(format)
const exportConst = exportVarCode(format, 'const')
decls.forEach((decl) => {
if (decl.type === 'InterfaceDeclaration') {
meta.exports[decl.cls] = {
type: 'interface',
}
codes.push(
`registerUTSInterface('${
decl.cls
}Options',Object.assign({ moduleName, moduleType, errMsg, package: pkg, class: initUTSClassName(name, '${
decl.cls
}ByJsProxy', is_uni_modules) }, ${genClassOptionsCode(decl.options)} ))`
)
} else if (decl.type === 'Class') {
meta.exports[decl.cls] = {
type: decl.isVar ? 'var' : 'class',
}
if (decl.isDefault) {
codes.push(
`${exportDefault}initUTSProxyClass(Object.assign({ moduleName, moduleType, errMsg, package: pkg, class: initUTSClassName(name, '${
decl.cls
}ByJs', is_uni_modules) }, ${genClassOptionsCode(decl.options)} ))`
)
} else {
codes.push(
`${exportConst}${
decl.cls
} = /*#__PURE__*/ initUTSProxyClass(Object.assign({ moduleName, moduleType, errMsg, package: pkg, class: initUTSClassName(name, '${
decl.cls
}ByJs', is_uni_modules) }, ${genClassOptionsCode(decl.options)} ))`
)
}
} else if (decl.type === 'FunctionDeclaration') {
meta.exports[decl.method] = {
type: decl.isVar ? 'var' : 'function',
params: decl.params,
}
const returnOptions = decl.return
? { type: decl.return.type, options: decl.return.options + 'Options' }
: ''
if (decl.isDefault) {
codes.push(
`${exportDefault}initUTSProxyFunction(${
decl.async
}, { moduleName, moduleType, errMsg, main: true, package: pkg, class: cls, name: '${
decl.method
}ByJs', keepAlive: ${decl.keepAlive}, params: ${JSON.stringify(
decl.params
)}, return: ${JSON.stringify(returnOptions)}})`
)
} else {
codes.push(
`${exportConst}${decl.method} = /*#__PURE__*/ initUTSProxyFunction(${
decl.async
}, { moduleName, moduleType, errMsg, main: true, package: pkg, class: cls, name: '${
decl.method
}ByJs', keepAlive: ${decl.keepAlive}, params: ${JSON.stringify(
decl.params
)}, return: ${JSON.stringify(returnOptions)}})`
)
}
} else if (decl.type === 'VariableDeclaration') {
decl.declarations.forEach((d) => {
meta.exports[(d.id as Identifier).value] = {
type: 'var',
}
})
if (format === FORMATS.ES) {
codes.push(
`export ${decl.kind} ${decl.declarations
.map(
(d) => `${(d.id as Identifier).value} = ${genInitCode(d.init!)}`
)
.join(', ')}`
)
} else if (format === FORMATS.CJS) {
codes.push(
`${decl.kind} ${decl.declarations
.map(
(d) => `${(d.id as Identifier).value} = ${genInitCode(d.init!)}`
)
.join(', ')}`
)
const exportVar = exportVarCode(format, decl.kind)
decl.declarations.forEach((d) => {
const name = (d.id as Identifier).value
codes.push(`${exportVar}${name} = ${name}`)
})
}
}
})
if (format === FORMATS.CJS) {
codes.push(
`uni.registerUTSPlugin('${normalizePath(pluginRelativeDir)}', exports)`
)
}
return codes.join(`\n`)
}
/**
* 解析接口文件中定义的类型信息
* @param module
* @param options
* @returns
*/
export async function parseInterfaceTypes(
module: string,
options: GenProxyCodeOptions,
preprocessor?: SyncUniModulesFilePreprocessor
): Promise<Types> {
const interfaceFilename = resolveRootInterface(module, options)
if (!interfaceFilename) {
return {
interface: {},
class: {},
fn: {},
alias: {},
uni: [],
}
}
// 懒加载 uts 编译器
// eslint-disable-next-line no-restricted-globals
const { parse } = require('@dcloudio/uts')
let ast: Module | null = null
try {
const code = fs.readFileSync(interfaceFilename, 'utf8')
ast = await parse(
preprocessor ? await preprocessor(code, interfaceFilename) : code,
{
filename: relative(interfaceFilename, options.inputDir!),
noColor: !isColorSupported(),
}
)
} catch (e) {
console.error(parseUTSSyntaxError(e, options.inputDir!))
}
return parseAstTypes(ast, true)
}
function parseAstTypes(ast: Module | null, isInterface: boolean) {
const interfaceTypes: Types['interface'] = {}
const classTypes: Types['class'] = {}
const fnTypes: Types['fn'] = {}
const aliasTypes: Types['alias'] = {}
const uniMethods: string[] = []
const exportNamed: string[] = []
if (ast) {
if (isInterface) {
ast.body.filter((node) => {
if (node.type === 'ExportNamedDeclaration') {
node.specifiers.forEach((s) => {
if (s.type === 'ExportSpecifier') {
if (s.exported) {
if (s.exported.type === 'Identifier') {
exportNamed.push(s.exported.value)
}
} else {
exportNamed.push(s.orig.value)
}
}
})
}
})
}
ast.body.filter((node) => {
if (node.type === 'ExportDeclaration') {
if (node.declaration.type === 'TsTypeAliasDeclaration') {
parseTypes(node.declaration, classTypes, fnTypes, aliasTypes)
} else if (node.declaration.type === 'TsInterfaceDeclaration') {
interfaceTypes[node.declaration.id.value] = {
returned: false,
decl: node.declaration,
}
if (node.declaration.id.value === 'Uni') {
node.declaration.body.body.forEach((item) => {
if (
item.type === 'TsMethodSignature' &&
item.key.type === 'Identifier'
) {
uniMethods.push(item.key.value)
} else if (
item.type === 'TsPropertySignature' &&
item.key.type === 'Identifier'
) {
uniMethods.push(item.key.value)
}
})
}
} else if (node.declaration.type === 'ClassDeclaration') {
classTypes[node.declaration.identifier.value] = {
interfaces: parseImplements(node.declaration),
keepAliveMethods: parseKeepAliveMethods(node.declaration),
}
}
} else if (node.type === 'TsTypeAliasDeclaration') {
if (!isInterface || exportNamed.includes(node.id.value)) {
parseTypes(node, classTypes, fnTypes, aliasTypes)
}
} else if (node.type === 'TsInterfaceDeclaration') {
interfaceTypes[node.id.value] = {
returned: false,
decl: node,
}
} else if (node.type === 'ClassDeclaration') {
classTypes[node.identifier.value] = {
interfaces: parseImplements(node),
keepAliveMethods: parseKeepAliveMethods(node),
}
}
})
}
return {
interface: interfaceTypes,
class: classTypes,
fn: fnTypes,
alias: aliasTypes,
uni: uniMethods,
}
}
function parseImplements(node: ClassDeclaration | ClassExpression): string[] {
const interfaces: string[] = []
node.implements.forEach((implement) => {
if (implement.expression.type === 'Identifier') {
interfaces.push(implement.expression.value)
}
})
return interfaces
}
function parseKeepAliveMethods(
node: ClassDeclaration | ClassExpression
): string[] {
const keepAliveMethods: string[] = []
node.body.forEach((method) => {
if (method.type === 'ClassMethod' && method.key.type === 'Identifier') {
if (parseKeepAlive(method.function)) {
keepAliveMethods.push(method.key.value)
}
}
})
return keepAliveMethods
}
function parseTypes(
decl: TsTypeAliasDeclaration,
classTypes: Record<string, ClassMeta>,
fnTypes: Record<string, Param[]>,
aliasTypes: Record<string, {}>
) {
switch (decl.typeAnnotation.type) {
// export type ShowLoading = ()=>void
case 'TsFunctionType':
const params = createParams(decl.typeAnnotation.params)
if (params.length) {
fnTypes[decl.id.value] = params
} else {
fnTypes[decl.id.value] = []
}
break
// export type ShowLoadingOptions = {}
// export type RequestMethod = 'GET' | 'POST'
case 'TsTypeLiteral':
case 'TsUnionType':
classTypes[decl.id.value] = {
typeParams: !!decl.typeParams,
interfaces: [],
keepAliveMethods: [],
}
break
default:
aliasTypes[decl.id.value] = {}
}
}
function createParams(tsParams: TsFnParameter[]) {
const params: Param[] = []
tsParams.forEach((pat) => {
if (pat.type === 'Identifier') {
params.push({
type: 'Parameter',
pat,
span: {} as Span,
})
}
})
return params
}
async function parseModuleDecls(module: string, options: GenProxyCodeOptions) {
// 优先合并 ios + android,如果没有,查找根目录 index.uts
const iosDecls = (
await parseFile(
resolvePlatformIndex('app-ios', module, options),
options,
options.iosPreprocessor
)
).filter((decl) => {
if (decl.type === 'Class') {
if (decl.isHook) {
options.iOSHookClass = options.namespace + capitalize(decl.cls)
return false
}
}
return true
})
const androidDecls = (
await parseFile(
resolvePlatformIndex('app-android', module, options),
options,
options.androidPreprocessor
)
).filter((decl) => {
if (decl.type === 'Class') {
if (decl.isHook) {
options.androidHookClass =
parseKotlinPackageWithPluginId(options.id, options.is_uni_modules) +
'.' +
decl.cls
return false
}
}
return true
})
// 优先使用 app-ios,因为 app-ios 平台函数类型需要正确的参数列表
const decls = mergeDecls(androidDecls, iosDecls)
// 如果没有平台特有,查找 root index.uts
if (!decls.length) {
return await parseFile(resolveRootIndex(module, options), options)
}
return decls
}
function mergeRecord(from: Record<string, any>, to: Record<string, any>) {
Object.keys(from).forEach((key) => {
if (!hasOwn(to, key)) {
to[key] = from[key]
}
})
}
function mergeArray(from: any[], to: any[]) {
from.forEach((item) => {
if (!to.includes(item)) {
to.push(item)
}
})
}
function mergeDecls(from: ProxyDecl[], to: ProxyDecl[]) {
from.forEach((item) => {
if (item.type === 'InterfaceDeclaration') {
const decl = to.find(
(toItem) =>
toItem.type === 'InterfaceDeclaration' && toItem.cls === item.cls
) as ProxyInterface | undefined
if (!decl) {
to.push(item)
} else {
mergeRecord(item.options.methods, decl.options.methods)
mergeArray(item.options.props, decl.options.props)
}
} else if (item.type === 'Class') {
const decl = to.find(
(toItem) =>
toItem.type === 'Class' &&
toItem.cls === item.cls &&
toItem.isDefault === item.isDefault
) as ProxyClass | undefined
if (!decl) {
to.push(item)
} else {
mergeRecord(item.options.methods, decl.options.methods)
mergeRecord(item.options.staticMethods, decl.options.staticMethods)
mergeArray(item.options.props, decl.options.props)
mergeArray(item.options.staticProps, decl.options.staticProps)
}
} else if (item.type === 'FunctionDeclaration') {
if (
!to.find(
(toItem) =>
toItem.type === 'FunctionDeclaration' &&
toItem.method === item.method &&
toItem.isDefault === item.isDefault
)
) {
to.push(item)
}
} else if (
item.type === 'VariableDeclaration' &&
item.declarations.length === 1
) {
if (
!to.find((toItem) => {
if (
toItem.type === 'VariableDeclaration' &&
toItem.declarations.length === 1
) {
const toDecl = toItem.declarations[0].id
const decl = item.declarations[0].id
return (
toDecl.type === 'Identifier' &&
decl.type === 'Identifier' &&
toDecl.value === decl.value
)
}
return false
})
) {
to.push(item)
}
}
})
return to
}
async function parseFile(
filename: string | undefined | false,
options: GenProxyCodeOptions,
preprocessor?: SyncUniModulesFilePreprocessor
): Promise<ProxyDecl[]> {
if (filename) {
// 暂时不从uvue目录读取了,就读取原始文件
// filename = resolveUVueFileName(filename)
if (fs.existsSync(filename)) {
const code = fs.readFileSync(filename, 'utf8')
return parseCode(
preprocessor ? await preprocessor(code, filename) : code,
options.namespace,
options.types!,
filename,
options.inputDir!
)
}
}
return []
}
async function parseCode(
code: string,
namespace: string,
types: Types,
filename: string,
inputDir: string
): Promise<ProxyDecl[]> {
// 懒加载 uts 编译器
// eslint-disable-next-line no-restricted-globals
const { parse } = require('@dcloudio/uts')
try {
const ast = await parse(code, {
filename: relative(filename, inputDir),
noColor: !isColorSupported(),
})
return parseAst(
ast,
createResolveTypeReferenceName(namespace, ast, types.class),
types
)
} catch (e: any) {
console.error(parseUTSSyntaxError(e, inputDir))
}
return []
}
type ProxyDecl =
| ProxyInterface
| ProxyFunctionDeclaration
| ProxyClass
| VariableDeclaration
interface ProxyInterface {
type: 'InterfaceDeclaration'
cls: string
options: {
methods: {
[name: string]: ProxyClassMethod
}
props: string[]
setters: Record<string, Parameter>
}
}
interface ProxyFunctionDeclaration {
type: 'FunctionDeclaration'
method: string
keepAlive: boolean
async: boolean
params: Parameter[]
isDefault: boolean
isVar: boolean
return?: {
type: 'interface'
options: string
}
}
interface ProxyFunctionReturnOptions {
type: 'interface'
options: string
}
interface ProxyClassMethod {
async?: boolean
keepAlive: boolean
params: Parameter[]
return?: ProxyFunctionReturnOptions
}
interface ProxyClass {
type: 'Class'
cls: string
options: {
constructor: { params: Parameter[] }
methods: {
[name: string]: ProxyClassMethod
}
staticMethods: {
[name: string]: ProxyClassMethod
}
props: string[]
staticProps: string[]
setters: Record<string, Parameter>
staticSetters: Record<string, Parameter>
}
isDefault: boolean
isVar: boolean
isHook: boolean
interfaces: string[]
}
function mergeAstTypes(to: Types, from: Types) {
if (Object.keys(from.class).length) {
for (const name in from.class) {
if (!hasOwn(to.class, name)) {
to.class[name] = from.class[name]
}
}
}
if (Object.keys(from.fn).length) {
for (const name in from.fn) {
if (!hasOwn(to.fn, name)) {
to.fn[name] = from.fn[name]
}
}
}
if (Object.keys(from.interface).length) {
for (const name in from.interface) {
if (!hasOwn(to.interface, name)) {
to.interface[name] = from.interface[name]
}
}
}
}
function parseAst(
ast: Module,
resolveTypeReferenceName: ResolveTypeReferenceName,
types: Types
): ProxyDecl[] {
const decls: ProxyDecl[] = []
mergeAstTypes(types, parseAstTypes(ast, false))
ast.body.forEach((item) => {
if (item.type === 'ExportDeclaration') {
const decl = item.declaration
switch (decl.type) {
case 'FunctionDeclaration':
decls.push(
genFunctionDeclaration(types, decl, resolveTypeReferenceName, false)
)
break
case 'ClassDeclaration':
decls.push(
genClassDeclaration(types, decl, resolveTypeReferenceName, false)
)
break
case 'VariableDeclaration':
const varDecl = genVariableDeclaration(
types,
decl,
resolveTypeReferenceName
)
if (varDecl) {
decls.push(varDecl)
}
break
}
} else if (item.type === 'ExportDefaultDeclaration') {
const decl = item.decl
if (decl.type === 'ClassExpression') {
if (decl.identifier) {
// export default class test{}
decls.push(
genClassDeclaration(types, decl, resolveTypeReferenceName, true)
)
}
} else if (decl.type === 'FunctionExpression') {