miniprogram-ci 2.1.8 → 2.1.10
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/CHANGELOG.md +4 -0
- package/README.md +153 -0
- package/dist/@types/config/config.d.ts +1 -1
- package/dist/@types/modules/nativecompiler/ios/buildCloud.d.ts +3 -1
- package/dist/@types/modules/nativecompiler/ios/index.d.ts +1 -0
- package/dist/@types/project/baseProject.d.ts +1 -0
- package/dist/@types/types/miniapp/index.d.ts +2 -0
- package/dist/config/config.js +1 -1
- package/dist/modules/corecompiler/original/workerThread/index.js +1 -1
- package/dist/modules/corecompiler/summerCompiler.js +1 -1
- package/dist/modules/nativecompiler/ios/buildCloud.js +1 -1
- package/dist/modules/nativecompiler/ios/index.js +1 -1
- package/dist/project/baseProject.js +1 -1
- package/dist/project/ciProject.js +1 -1
- package/dist/utils/debug.js +1 -1
- package/dist/utils/subprocess/processManager.js +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
|
@@ -7,6 +7,10 @@ miniprogram-ci 是从[微信开发者工具](https://developers.weixin.qq.com/mi
|
|
|
7
7
|
miniprogram-ci 从 1.0.28 开始支持第三方平台开发的上传和预览,调用方式与普通开发模式无异。[查看详情](#第三方平台开发)
|
|
8
8
|
|
|
9
9
|
## 最近变更
|
|
10
|
+
#### 2.1.10
|
|
11
|
+
- `fix` 修复 packOptions 不生效的问题
|
|
12
|
+
#### 2.1.9
|
|
13
|
+
- `fix` 修复 miniprogramRoot 结尾没有 / 会影响babel编译的问题
|
|
10
14
|
#### 2.1.7
|
|
11
15
|
- `fix` 修复 同进程构建 Ipa 与 Apk 时条件编译错误
|
|
12
16
|
#### 2.1.6
|
|
@@ -783,6 +787,155 @@ const ci = require('miniprogram-ci')
|
|
|
783
787
|
ci.proxy('YOUR_PROXY_URL')
|
|
784
788
|
```
|
|
785
789
|
|
|
790
|
+
### 构建 Apk
|
|
791
|
+
```js
|
|
792
|
+
const ci = require('miniprogram-ci')
|
|
793
|
+
;(async () => {
|
|
794
|
+
const project = new ci.Project({
|
|
795
|
+
appid: 'wxsomeappid',
|
|
796
|
+
type: 'miniProgram',
|
|
797
|
+
projectPath: 'the/project/path',
|
|
798
|
+
privateKeyPath: 'the/path/to/privatekey',
|
|
799
|
+
ignores: ['node_modules/**/*'],
|
|
800
|
+
})
|
|
801
|
+
const buildResult = await ci.buildApk({
|
|
802
|
+
project,
|
|
803
|
+
keyAlias: 'keyAlias',
|
|
804
|
+
keyPass: 'keyPass',
|
|
805
|
+
keyStore: 'the/path/to/keystore',
|
|
806
|
+
storePass: 'storePass',
|
|
807
|
+
output: '/the/path/to/output',
|
|
808
|
+
desc: 'build apk from ci',
|
|
809
|
+
setting: {
|
|
810
|
+
es6: true,
|
|
811
|
+
},
|
|
812
|
+
})
|
|
813
|
+
console.log(uploadResult)
|
|
814
|
+
})()
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
#### 参数
|
|
818
|
+
|
|
819
|
+
同时支持传入 [ci.upload](#上传) 的参数
|
|
820
|
+
|
|
821
|
+
| 键 | 类型 | 必填 | 说明 |
|
|
822
|
+
| ---------------- | -------- | ---- | ------------------------------------- |
|
|
823
|
+
| project | IProject | 是 | [项目对象](#项目对象) |
|
|
824
|
+
| keyStore | string | 是 | 证书文件绝对路径 |
|
|
825
|
+
| keyPass | string | 是 | 证书密码 |
|
|
826
|
+
| storePass | string | 是 | 证书文件密码 |
|
|
827
|
+
| keyAlias | string | 是 | 证书别名 |
|
|
828
|
+
| output | string | 是 | 构建产物的保存路径,需要为系统绝对路径 |
|
|
829
|
+
| useAab | boolean | 否 | 默认 false |
|
|
830
|
+
| desc | string | 否 | 版本描述 |
|
|
831
|
+
| isUploadResourceBundle | boolean | 否 | 是否上传资源包 |
|
|
832
|
+
| resourceBundleVersion | string | 否 | 资源包版本号 |
|
|
833
|
+
| resourceBundleDesc | string | 否 | 资源包项目备注 |
|
|
834
|
+
| disableCache | boolean | 否 | 是否清除构建缓存 |
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
#### 返回
|
|
838
|
+
|
|
839
|
+
| 键 | 类型 | 必填 | 说明 |
|
|
840
|
+
| ----------| -------- | ---- | ----------------------- |
|
|
841
|
+
| errmsg | string | | 构建信息 |
|
|
842
|
+
| success | boolean | | 构建是否成功 |
|
|
843
|
+
|
|
844
|
+
### 构建 Ipa
|
|
845
|
+
|
|
846
|
+
支持本地构建与远程构建。本地构建 Ipa 仅支持在 macOS 上使用 codesign 进行签名,因此开发者需要确保 keychains 中包含自己的证书信息。windows 可以使用远程构建。
|
|
847
|
+
|
|
848
|
+
```js
|
|
849
|
+
const ci = require('miniprogram-ci')
|
|
850
|
+
;(async () => {
|
|
851
|
+
const project = new ci.Project({
|
|
852
|
+
appid: 'wxsomeappid',
|
|
853
|
+
type: 'miniProgram',
|
|
854
|
+
projectPath: 'the/project/path',
|
|
855
|
+
privateKeyPath: 'the/path/to/privatekey',
|
|
856
|
+
ignores: ['node_modules/**/*'],
|
|
857
|
+
})
|
|
858
|
+
const buildResult = await ci.buildIpa({
|
|
859
|
+
project,
|
|
860
|
+
output: '/the/path/to/output', // 构建产物的保存路径,需要为系统绝对路径
|
|
861
|
+
profilePath: '/the/path/to/profile', // profile 文件地址,文件格式为 mobileprovision,相对项目根路径的相对路径
|
|
862
|
+
certificateName: 'Apple Develop', // 签名证书名
|
|
863
|
+
tpnsProfilePath: '/the/path/to/tnpsprofile', // tpnsProfile 文件路径,相对项目根路径的相对路径
|
|
864
|
+
})
|
|
865
|
+
console.log(uploadResult)
|
|
866
|
+
})()
|
|
867
|
+
|
|
868
|
+
```
|
|
869
|
+
|
|
870
|
+
#### 参数
|
|
871
|
+
|
|
872
|
+
同时支持传入 [ci.upload](#上传) 的参数
|
|
873
|
+
|
|
874
|
+
| 键 | 类型 | 必填 | 说明 |
|
|
875
|
+
| ---------------- | -------- | ---- | ------------------------------------- |
|
|
876
|
+
| project | IProject | 是 | [项目对象](#项目对象) |
|
|
877
|
+
| output | string | 是 | 构建产物的保存路径,需要为系统绝对路径 |
|
|
878
|
+
| isDistribute | string | 否 | 是否使用分发证书 |
|
|
879
|
+
| profilePath | string | 是 | profile 文件地址,文件格式为 mobileprovision,相对项目根路径的相对路径|
|
|
880
|
+
| certificateName | string | 是 | 证书别名 |
|
|
881
|
+
| tpnsProfilePath | string | 否 | tpnsProfile 文件路径,相对项目根路径的相对路径 |
|
|
882
|
+
| p12Path | string | 否 | p12 文件路径,文件格式为 p12,相对项目根路径的相对路径。使用远程构建时必填 |
|
|
883
|
+
| p12Password | string | 否 | p12 密码。使用远程构建时必填 |
|
|
884
|
+
| desc | string | 否 | 版本描述 |
|
|
885
|
+
| isUploadResourceBundle | boolean | 否 | 是否上传资源包 |
|
|
886
|
+
| resourceBundleVersion | string | 否 | 资源包版本号 |
|
|
887
|
+
| resourceBundleDesc | string | 否 | 资源包项目备注 |
|
|
888
|
+
| disableCache | boolean | 否 | 是否清除构建缓存 |
|
|
889
|
+
| isRemoteBuild | boolean | 否 | 是否使用远程构建 |
|
|
890
|
+
|
|
891
|
+
#### 返回
|
|
892
|
+
| 键 | 类型 | 必填 | 说明 |
|
|
893
|
+
| ----------| -------- | ---- | ----------------------- |
|
|
894
|
+
| errmsg | string | | 构建信息 |
|
|
895
|
+
| success | boolean | | 构建是否成功 |
|
|
896
|
+
|
|
897
|
+
### 上传多端资源包
|
|
898
|
+
|
|
899
|
+
```js
|
|
900
|
+
const ci = require('miniprogram-ci')
|
|
901
|
+
;(async () => {
|
|
902
|
+
const project = new ci.Project({
|
|
903
|
+
appid: 'wxsomeappid',
|
|
904
|
+
type: 'miniProgram',
|
|
905
|
+
projectPath: 'the/project/path',
|
|
906
|
+
privateKeyPath: 'the/path/to/privatekey',
|
|
907
|
+
ignores: ['node_modules/**/*'],
|
|
908
|
+
})
|
|
909
|
+
const uploadResult = await ci.miniappCloudUpload({
|
|
910
|
+
project,
|
|
911
|
+
version: '0.1.24',
|
|
912
|
+
androidPlatform: false,
|
|
913
|
+
setting: {
|
|
914
|
+
es6: true,
|
|
915
|
+
},
|
|
916
|
+
})
|
|
917
|
+
console.log(uploadResult)
|
|
918
|
+
})()
|
|
919
|
+
```
|
|
920
|
+
|
|
921
|
+
#### 参数
|
|
922
|
+
|
|
923
|
+
同时支持传入 [ci.upload](#上传) 的参数
|
|
924
|
+
|
|
925
|
+
| 键 | 类型 | 必填 | 说明 |
|
|
926
|
+
| ---------------- | -------- | ---- | ------------------------------------- |
|
|
927
|
+
| project | IProject | 是 | [项目对象](#项目对象) |
|
|
928
|
+
| version | string | 是 | 版本号 |
|
|
929
|
+
| desc | string | 否 | 版本描述 |
|
|
930
|
+
| iOSPlatform | boolean | 否 | 适用平台 iOS,默认为 true |
|
|
931
|
+
| androidPlatform | boolean | 否 | 适用平台 Android,默认为 true |
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
#### 返回
|
|
935
|
+
| 键 | 类型 | 必填 | 说明 |
|
|
936
|
+
| ----------| -------- | ---- | ----------------------- |
|
|
937
|
+
| errmsg | string | | 构建信息 |
|
|
938
|
+
| success | boolean | | 构建是否成功 |
|
|
786
939
|
|
|
787
940
|
## 命令行调用
|
|
788
941
|
|
|
@@ -32,7 +32,7 @@ declare class buildCloudManager {
|
|
|
32
32
|
updateIOSAppConfigPlistInfo(projectPath: string, bindAppInfo: MiniProgramCore.IStringKeyMap, demoIpaPath: string, iosMiniappJson: MiniProgramCore.IStringKeyMap, sdkPath: string, isSimulator: boolean, recorder: Recorder, theme: ITheme | undefined, i18nInfo: II18NInfo): Promise<void>;
|
|
33
33
|
updateIOSAppexInfoPlistInfo(bindAppInfo: MiniProgramCore.IStringKeyMap, demoIpaPath: string, iosMiniappJson: MiniProgramCore.IStringKeyMap, CFBundleVersion: number, recorder: Recorder): Promise<void>;
|
|
34
34
|
private updateBundleIcons;
|
|
35
|
-
updateIOSIcons(projectPath: string, demoIpaPath: string, miniappCacheDirPath: string, iosMiniappJson: MiniProgramCore.IStringKeyMap, isPublish: boolean, recorder: Recorder): Promise<void>;
|
|
35
|
+
updateIOSIcons(projectPath: string, demoIpaPath: string, miniappCacheDirPath: string, iosMiniappJson: MiniProgramCore.IStringKeyMap, isPublish: boolean, recorder: Recorder, inLandun?: boolean, cacheAssetCarPath?: string): Promise<void>;
|
|
36
36
|
replaceLaunchScreenImage(storyboardPath: string, newScreenImagePath: string, oldScreenImageName: string, recorder: Recorder, projectPath: string, demoIpaPath: string): string | undefined;
|
|
37
37
|
updateSplashScreen(projectPath: string, demoIpaPath: string, iosMiniappJson: MiniProgramCore.IStringKeyMap, recorder: Recorder, theme: ITheme | undefined, i18nInfo: II18NInfo): Promise<void>;
|
|
38
38
|
genUseExtendedSdk(iosMiniappJson: MiniProgramCore.IStringKeyMap, debugInfo?: IMiniApp.IDebugInfo): MiniProgramCore.IStringKeyMap<any>;
|
|
@@ -60,6 +60,8 @@ declare class buildCloudManager {
|
|
|
60
60
|
buildCloud(args: IMiniApp.IIOSBuildCloudArgs, recorder: Recorder): Promise<IBuildCloudResult>;
|
|
61
61
|
writeI18NInfoFile(demoIpaPath: string, i18nInfo: II18NInfo, iosI18NField: Record<string, string>): Promise<void>;
|
|
62
62
|
getMaterialFilePath(projectPath: string, relativeTargetPath: string): string;
|
|
63
|
+
updateIOSAppResource(projectPath: string, demoIpaPath: string, iosMiniappJson: MiniProgramCore.IStringKeyMap, recorder: Recorder): void;
|
|
64
|
+
copyDirectory(sourceDir: string, targetDir: string, overWrite?: boolean): void;
|
|
63
65
|
}
|
|
64
66
|
declare const _default: buildCloudManager;
|
|
65
67
|
export default _default;
|
|
@@ -49,6 +49,7 @@ export declare abstract class BaseProject extends WaitAble implements MiniProgra
|
|
|
49
49
|
ready(): Promise<void>;
|
|
50
50
|
protected getProjectType(attr: any, compileType: MiniProgramCore.ProjectType): import("../types").MiniProgramCI.ProjectType;
|
|
51
51
|
getProjectConfig(): ProjectConfigJSON.IProjectConfigJSON;
|
|
52
|
+
normalizeRootPath: (pathName?: string) => string;
|
|
52
53
|
serialize(): Promise<MiniProgramCore.IProjectSerializeInfo>;
|
|
53
54
|
abstract init(...args: any[]): void;
|
|
54
55
|
abstract updateFileAndDirs(...args: any[]): void;
|
|
@@ -101,6 +101,7 @@ export declare namespace IMiniApp {
|
|
|
101
101
|
theme: ITheme;
|
|
102
102
|
i18nInfo: II18NInfo;
|
|
103
103
|
debugInfo?: IDebugInfo;
|
|
104
|
+
cacheAssetCarPath?: string;
|
|
104
105
|
}
|
|
105
106
|
type IIOSRunCloudArgs = IIOSRunCloudSimpleArgs & {
|
|
106
107
|
projectPath: string;
|
|
@@ -151,6 +152,7 @@ export declare namespace IMiniApp {
|
|
|
151
152
|
theme: ITheme;
|
|
152
153
|
i18nInfo: II18NInfo;
|
|
153
154
|
debugInfo?: IDebugInfo;
|
|
155
|
+
cacheAssetCarPath?: string;
|
|
154
156
|
};
|
|
155
157
|
type IIOSBuildCloudArgs = IIOSBuildCloudSimpleArgs & {
|
|
156
158
|
projectPath: string;
|
package/dist/config/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var COMPILE_TYPE,AstType,EFilterCode;function getDefaultIgnores(e){const _=["node_modules/**/*","**/node_modules/**","**/.git/**",".git/**/*","**/.svn/**",".svn/**/*",".DS_Store","**/.DS_Store"];return"multiPlatform"===e.projectArchitecture&&_.push(exports.multiPlatformRoot+"/**/*"),_}Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_CODE_LENGTH=exports.EFilterCode=exports.AstType=exports.compileTypeConfig=exports.getDefaultIgnores=exports.FullPkg=exports.MainPkg=exports.multiPlatformRoot=exports.extendedLibMap=exports.jsonVariablePropertyWhiteList=exports.DefaultProjectAttr=exports.TABBAR_ICON_WHITE_LIST=exports.COMPILE_TYPE=exports.APP_TYPE=exports.MINI_GAME_WORKERS_PACKAGE_ROOT=exports.MINI_GAME_MAIN_PACKAGE_ROOT=exports.MINI_PROGRAM_MAIN_PACKAGE_ROOT=exports.PROJECT_TYPE_ERROR=exports.GET_LATEST_VERSION_CGI_ERR=exports.UPLOAD_JS_SERVER_CGI_ERR=exports.CODE_PROTECT_TRANSLATE_FILENAME=exports.UPLOAD_CGI_ERR=exports.GENERATE_LOCAL_SIGNATURE_ERR=exports.GET_SIGNATURE_RAND_STRING_ERR=exports.APP_JSON_NOT_FOUND=exports.JSON_CONTENT_ERR=exports.FILE_NOT_UTF8=exports.JSON_PARSE_ERR=exports.FILE_NOT_FOUND=exports.PLUGIN_JSON_PARSE_ERR=exports.PLUGIN_JSON_CONTENT_ERR=exports.PLUGIN_JSON_FILE_NOT_FOUND=exports.GAME_PLUGIN_LIB_MD5_NOT_MATCH=exports.SUMMER_PLUGIN_CODE_ERR=exports.SUMMER_PLUGIN_ERR=exports.MINIFY_WXML_ERR=exports.POST_WXSS_ERR=exports.FILE_FLAT_ERR=exports.JS_ES6_ERR=exports.BABILI_JS_ERR=exports.UGLIFY_JS_ERR=exports.BABEL_TRANS_JS_ERR=exports.JS_NOT_FOUND=exports.WXML_NOT_FOUND=exports.PARAM_ERROR=exports.CI_VERSION=void 0,exports.CI_VERSION="2.1.
|
|
1
|
+
"use strict";var COMPILE_TYPE,AstType,EFilterCode;function getDefaultIgnores(e){const _=["node_modules/**/*","**/node_modules/**","**/.git/**",".git/**/*","**/.svn/**",".svn/**/*",".DS_Store","**/.DS_Store"];return"multiPlatform"===e.projectArchitecture&&_.push(exports.multiPlatformRoot+"/**/*"),_}Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_CODE_LENGTH=exports.EFilterCode=exports.AstType=exports.compileTypeConfig=exports.getDefaultIgnores=exports.FullPkg=exports.MainPkg=exports.multiPlatformRoot=exports.extendedLibMap=exports.jsonVariablePropertyWhiteList=exports.DefaultProjectAttr=exports.TABBAR_ICON_WHITE_LIST=exports.COMPILE_TYPE=exports.APP_TYPE=exports.MINI_GAME_WORKERS_PACKAGE_ROOT=exports.MINI_GAME_MAIN_PACKAGE_ROOT=exports.MINI_PROGRAM_MAIN_PACKAGE_ROOT=exports.PROJECT_TYPE_ERROR=exports.GET_LATEST_VERSION_CGI_ERR=exports.UPLOAD_JS_SERVER_CGI_ERR=exports.CODE_PROTECT_TRANSLATE_FILENAME=exports.UPLOAD_CGI_ERR=exports.GENERATE_LOCAL_SIGNATURE_ERR=exports.GET_SIGNATURE_RAND_STRING_ERR=exports.APP_JSON_NOT_FOUND=exports.JSON_CONTENT_ERR=exports.FILE_NOT_UTF8=exports.JSON_PARSE_ERR=exports.FILE_NOT_FOUND=exports.PLUGIN_JSON_PARSE_ERR=exports.PLUGIN_JSON_CONTENT_ERR=exports.PLUGIN_JSON_FILE_NOT_FOUND=exports.GAME_PLUGIN_LIB_MD5_NOT_MATCH=exports.SUMMER_PLUGIN_CODE_ERR=exports.SUMMER_PLUGIN_ERR=exports.MINIFY_WXML_ERR=exports.POST_WXSS_ERR=exports.FILE_FLAT_ERR=exports.JS_ES6_ERR=exports.BABILI_JS_ERR=exports.UGLIFY_JS_ERR=exports.BABEL_TRANS_JS_ERR=exports.JS_NOT_FOUND=exports.WXML_NOT_FOUND=exports.PARAM_ERROR=exports.CI_VERSION=void 0,exports.CI_VERSION="2.1.10",exports.PARAM_ERROR=1e4,exports.WXML_NOT_FOUND=10007,exports.JS_NOT_FOUND=10008,exports.BABEL_TRANS_JS_ERR=10032,exports.UGLIFY_JS_ERR=10033,exports.BABILI_JS_ERR=10034,exports.JS_ES6_ERR=10035,exports.FILE_FLAT_ERR=10036,exports.POST_WXSS_ERR=10037,exports.MINIFY_WXML_ERR=10038,exports.SUMMER_PLUGIN_ERR=10045,exports.SUMMER_PLUGIN_CODE_ERR=10046,exports.GAME_PLUGIN_LIB_MD5_NOT_MATCH=10081,exports.PLUGIN_JSON_FILE_NOT_FOUND=10091,exports.PLUGIN_JSON_CONTENT_ERR=10092,exports.PLUGIN_JSON_PARSE_ERR=10093,exports.FILE_NOT_FOUND=10005,exports.JSON_PARSE_ERR=10006,exports.FILE_NOT_UTF8=10031,exports.JSON_CONTENT_ERR=10009,exports.APP_JSON_NOT_FOUND=2e4,exports.GET_SIGNATURE_RAND_STRING_ERR=20001,exports.GENERATE_LOCAL_SIGNATURE_ERR=20002,exports.UPLOAD_CGI_ERR=20003,exports.CODE_PROTECT_TRANSLATE_FILENAME=20004,exports.UPLOAD_JS_SERVER_CGI_ERR=20005,exports.GET_LATEST_VERSION_CGI_ERR=20006,exports.PROJECT_TYPE_ERROR=3e4,exports.MINI_PROGRAM_MAIN_PACKAGE_ROOT="__APP__",exports.MINI_GAME_MAIN_PACKAGE_ROOT="__GAME__",exports.MINI_GAME_WORKERS_PACKAGE_ROOT="workers.js",exports.APP_TYPE={NORMAL:0,PLUGIN:1,SHOP:2,MINISHOP:3,GAME:4,CARD:5,NATIVE:7},function(e){e.miniProgram="miniProgram",e.miniProgramPlugin="miniProgramPlugin",e.miniGame="miniGame",e.miniGamePlugin="miniGamePlugin"}(COMPILE_TYPE=exports.COMPILE_TYPE||(exports.COMPILE_TYPE={})),exports.TABBAR_ICON_WHITE_LIST=[".png",".jpg",".jpeg"],exports.DefaultProjectAttr={platform:!1,appType:0,isSandbox:!1,released:!1,setting:{MaxCodeSize:2,MaxSubpackageSubCodeSize:2,MaxSubpackageFullCodeSize:12,NavigateMiniprogramLimit:10,MaxSubPackageLimit:100,MinTabbarCount:2,MaxTabbarCount:5,MaxCustomTabbarCount:10,MaxTabbarIconSize:40}},exports.jsonVariablePropertyWhiteList={windowPropertWhiteList:["navigationBarBackgroundColor","navigationBarTextStyle","backgroundColor","backgroundTextStyle","backgroundColorTop","backgroundColorBottom","backgroundColorContent"],tabBarPropertyWhiteList:["color","selectedColor","backgroundColor","borderStyle"],tabbarListItemPropertyWhiteList:["iconPath","selectedIconPath"]},exports.extendedLibMap={kbone:{packages:["miniprogram-element","miniprogram-render"]},weui:{packages:["weui-miniprogram"]}},exports.multiPlatformRoot="miniapp",exports.MainPkg="__APP__",exports.FullPkg="__FULL__",exports.getDefaultIgnores=getDefaultIgnores,exports.compileTypeConfig={weapp:"weapp",game:"game",plugin:"plugin",gamePlugin:"gamePlugin"},function(e){e.Babel="babel",e.Acorn="acorn"}(AstType=exports.AstType||(exports.AstType={})),function(e){e[e.Include=0]="Include",e[e.PackOptionsIgnore=1]="PackOptionsIgnore",e[e.AnalyseNoUse=2]="AnalyseNoUse",e[e.PartialCompileNoUse=3]="PartialCompileNoUse"}(EFilterCode=exports.EFilterCode||(exports.EFilterCode={})),exports.MAX_CODE_LENGTH=2048e3;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.abortTask=exports.runTask=void 0;const tslib_1=require("tslib"),logger_1=require("../utils/logger"),workerManager_1=require("./workerManager"),childprocessManager_1=require("./childprocessManager"),index_1=tslib_1.__importDefault(require("./task/index"));tslib_1.__exportStar(require("./config"),exports);const isDevtools=void 0!==process.env.__nwjs;async function runTask(r,e,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.abortTask=exports.runTask=void 0;const tslib_1=require("tslib"),logger_1=require("../utils/logger"),workerManager_1=require("./workerManager"),childprocessManager_1=require("./childprocessManager"),index_1=tslib_1.__importDefault(require("./task/index"));tslib_1.__exportStar(require("./config"),exports);const isDevtools=void 0!==process.env.__nwjs;async function runTask(r,e,o=(()=>{})){var a;if(logger_1.logger.info("runTask",r,e.filePath),global.__MINIPROGRAM_CI_TEST__||"true"===(null===(a=null===process||void 0===process?void 0:process.env)||void 0===a?void 0:a.__MINIPROGRAM_CI_TEST__))return(0,index_1.default)(r,e);try{if(process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname)return await childprocessManager_1.childProcessManager.runTask(r,e,o);const a=(0,workerManager_1.getWorkerManager)(isDevtools);return await a.runTask(r,e,o)}catch(o){if(o===workerManager_1.AbortEvent)throw o;if(logger_1.logger.error(`runTask ${r}, ${e.filePath} catch error ${o}`),o instanceof childprocessManager_1.ChildProcessCrashedError)throw new Error(`runTask ${r}, ${e.filePath} catch error ${o}`);return(0,index_1.default)(r,e)}}function abortTask(r){(0,workerManager_1.getWorkerManager)(isDevtools).abort(r)}exports.runTask=runTask,exports.abortTask=abortTask;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SummerCompiler=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),lodash_1=tslib_1.__importDefault(require("lodash")),locales_1=tslib_1.__importDefault(require("../../utils/locales/locales")),request_1=require("../../utils/request"),common_1=require("./original/compile/common"),tools_1=require("../../utils/tools"),white_ext_list_1=require("../../utils/white_ext_list"),config_1=require("../../config/config"),processManager_1=require("../../utils/subprocess/processManager"),messageHub_1=require("../../utils/messageHub"),singletontask_1=require("../../utils/singletontask"),uglifyfilenames_1=require("./original/protect/uglifyfilenames"),baseCompiler_1=require("./baseCompiler"),packOptionsHelper_1=tslib_1.__importDefault(require("../../utils/packOptionsHelper")),miniProgram=config_1.COMPILE_TYPE.miniProgram,miniGame=config_1.COMPILE_TYPE.miniGame,miniProgramPlugin=config_1.COMPILE_TYPE.miniProgramPlugin,miniGamePlugin=config_1.COMPILE_TYPE.miniGamePlugin;function performanceMark(e,t){}class SummerCompiler extends baseCompiler_1.BaseCoreCompiler{constructor(e,t,i,s,o,a){super(e),this.project=e,this.cachePath=t,this.projectInfo=i,this.devtoolMessagehub=s,this.analyzer=o,this._filterFactory=a,this.isSummer=!0,this.promiseCache=new Map,this._taskCache=new Map,this._status=void 0,this._eventAdded=!1,this._locale="",this.devCodeCacheByPath=new Map,this.onFileChange=(e,t)=>{if("change"!==e||t.endsWith(".json"))for(const e of this.promiseCache.keys())e.startsWith("getConf-")&&this.promiseCache.delete(e);if("change"!==e){for(const e of this.promiseCache.keys())e.startsWith("getPackageFiles-")&&this.promiseCache.delete(e);for(const e of this._taskCache.keys())e.startsWith("getPackageFiles-")&&this._taskCache.delete(e)}this.invalidCodeCache(t),this.subProcessManager.sendEvent("fileChange",{type:e,targetPath:t})},this.onPreCompileOptionsChange=async e=>{await this.clearCache(),this.subProcessManager.sendEvent("precompileOptionsChange",e)},this.onProgressUpdate=(e,t,i)=>{var s;this.messageHub.showBuildLog(""+e,t,i),null===(s=this.progressUpdateFromCompileOptions)||void 0===s||s.call(this,{id:e.toString(),message:i,status:t})},this._getPackageFiles=async(e,t,i="dev")=>{performanceMark("request get getPackageFiles");const s=await this.subProcessManager.runTask("getPackageFiles",{graphId:e,root:t},this.onProgressUpdate);performanceMark("request get getPackageFiles",!0);const o=this.isPluginType(e)?this.project.pluginRoot:this.project.miniprogramRoot,a=await this.filterFactory(i),r={},n=s.filter(t=>{const i=path_1.default.posix.join(o,t.source),s=a(e,i);return s!==config_1.EFilterCode.Include&&(r[s]||(r[s]=[]),r[s].push(i)),s===config_1.EFilterCode.Include}),c={[config_1.EFilterCode.AnalyseNoUse]:locales_1.default.config.UNUSE_FILE_LIST,[config_1.EFilterCode.PackOptionsIgnore]:locales_1.default.config.PACK_OPTIONS_IGNORE_LIST,[config_1.EFilterCode.PartialCompileNoUse]:locales_1.default.config.PARTIAL_COMPILE_IGNORE_LIST};for(const e in r)c[e]?this.onProgressUpdate(e,"warn",c[e].format(r[e].join(","))):this.onProgressUpdate(e,"warn",locales_1.default.config.UNKNOWN_REASON_INGORE_LIST.format(e,r[e].join(",")));return n},performanceMark("create summer compiler"),this.messageHub=new messageHub_1.MessageHub(s),this.ready()}get status(){return this._status}async init(){performanceMark("init summer compiler");const e=path_1.default.posix.join(__dirname,"./summerEntryProcess.js");this.subProcessManager=new processManager_1.SubProcessProxy(this.project,e,{cachePath:this.cachePath},this.projectInfo,8891,this.onProgressUpdate),this.addProjectListener(),this.loadStatus(),performanceMark("init summer compiler",!0)}async loadStatus(){this._status=await this.subProcessManager.runTask("loadStatus")}destroy(){var e;null===(e=this.subProcessManager)||void 0===e||e.destroy(),this.removeProjectListener(),this._checkReadyTask=void 0}async clearCache(){var e;await(null===(e=this.subProcessManager)||void 0===e?void 0:e.runTask("clearCache")),this.promiseCache.clear(),this.devCodeCacheByPath.clear(),this._taskCache.clear()}updateOptions(e){var t;lodash_1.default.isEqual(e,this.projectInfo)||(this.projectInfo=e,this.promiseCache.clear(),this.devCodeCacheByPath.clear(),null===(t=this.subProcessManager)||void 0===t||t.sendEvent("updateOptions",e),this.loadStatus(),this.project.updateOptions(e))}addProjectListener(){var e,t;this._eventAdded&&this.removeProjectListener(),null===(e=this.project.event)||void 0===e||e.on("fileChange",this.onFileChange),null===(t=this.project.event)||void 0===t||t.on("precompileOptionsChange",this.onPreCompileOptionsChange),this._eventAdded=!0}removeProjectListener(){var e,t;null===(e=this.project.event)||void 0===e||e.off("fileChange",this.onFileChange),null===(t=this.project.event)||void 0===t||t.off("precompileOptionsChange",this.onPreCompileOptionsChange),this._eventAdded=!1}invalidCodeCache(e){const t=this.devCodeCacheByPath.get((0,tools_1.sourcePathToTargetPath)(e));t&&(t.isValid=!1)}async getConf(e){var t,i;const s="getConf-"+e;if(this.promiseCache.has(s))return(null===(t=process.env)||void 0===t?void 0:t.isDevtools)&&console.log(s,"hit cache"),this.promiseCache.get(s);(null===(i=process.env)||void 0===i?void 0:i.isDevtools)&&console.log(s,"do request"),performanceMark("request get conf");const o={graphId:e},a=this.subProcessManager.runTask("getConf",o,this.onProgressUpdate);return this.promiseCache.set(s,a),performanceMark("request get conf",!0),a}async getPackageFiles(e,t,i="dev",s=!0){const o=`getPackageFiles-${e}-${t}-${i}`;if(this._taskCache.has(o)&&s){const e=this._taskCache.get(o);return null==e?void 0:e.getResult(!0)}const a=new singletontask_1.SingletonTask(this._getPackageFiles.bind(this,e,t,i),o);return this._taskCache.set(o,a),null==a?void 0:a.getResult(!0)}isMiniappPlatformInclude(e){const t=path_1.default.posix.join(this.project.miniprogramRoot,"app.miniapp.json");return(0,tools_1.isMiniappPlatform)(this.project.targetPlatform)&&t===e}async filterFactory(e){packOptionsHelper_1.default.updateState(this.project),this.onProgressUpdate("initUnusedFiles","doing","analyzing codes..."),await packOptionsHelper_1.default.initUnusedFiles(this.project,this.analyzer,"prod"===e),0!==packOptionsHelper_1.default.getUnusedFiles().size&&this.onProgressUpdate("initUnusedFiles","doing","ignoring files: "+Array.from(packOptionsHelper_1.default.getUnusedFiles()).join(",")),this.onProgressUpdate("initUnusedFiles","success","analyzing codes success");const t=this._filterFactory?await this._filterFactory(e):()=>0;return(i,s)=>{const o=packOptionsHelper_1.default.relativePath(s);return this.isMiniappPlatformInclude(s)||packOptionsHelper_1.default.isFileIncluded(o)?config_1.EFilterCode.Include:packOptionsHelper_1.default.isIgnoredByRules(o)?config_1.EFilterCode.PackOptionsIgnore:i===miniProgram&&packOptionsHelper_1.default.isIgnoreByUnusedFiles(s,"prod"===e)?config_1.EFilterCode.AnalyseNoUse:t(i,s)}}async getCodeByFileList(e,t){const i={},s={},o=this.isPluginType(e)?this.project.pluginRoot:this.project.miniprogramRoot,a=[];for(const e of t){const t=this.devCodeCacheByPath.get(path_1.default.posix.join(o,e)),r=null==t?void 0:t.codeFile;let n=!1;t&&t.isValid&&r&&!("error"in r)||(n=!0,a.push(e)),r&&!("error"in r)&&(n&&(i[e]=r.md5),s[e]=r)}if(a.length>0){const t=await this.subProcessManager.runTask("getDevCodeByFileList",{graphId:e,fileList:a,cacheMd5:i},this.onProgressUpdate);for(const e in t){const i=t[e],a=path_1.default.posix.join(o,e);"error"in i||""!==i.md5?this.devCodeCacheByPath.set(a,{isValid:!0,codeFile:i}):this.devCodeCacheByPath.delete(a),s[e]=i}}return s}async getExtJSON(){return(await this.getConf(miniProgram)).ext}async getAppJSON(){return(await this.getConf(miniProgram)).app}async getGameJSON(){return(await this.getConf(miniGame)).app}async getSiteMapJSON(){return(await this.getConf(miniProgram)).sitemap}async getPageJSON(e){const t=await this.getConf(miniProgram),i=t.pages[e]||t.comps[e];if(!i)throw new Error("summer-compiler 收集json配置有遗漏, "+e);return i}async getAllPageAndComponent(){const e=await this.getConf(miniProgram),t=(await this.getPackageFiles(miniProgram,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".json"));return Object.keys(e.pages).concat(Object.keys(e.comps)).filter(e=>t.includes(e+".json"))}async getAllSortedJSFiles(){const e=await this.getConf(miniProgram),t=Object.keys(e.pages),i=Object.keys(e.comps),s=(await this.getPackageFiles(miniProgram,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".js")),o=t.filter(e=>!i.includes(e)).map(e=>e+".js").filter(e=>s.includes(e)),a=i.map(e=>e+".js").filter(e=>s.includes(e)),r=s.filter(e=>e.endsWith(".js")&&"app.js"!==e&&!o.includes(e)&&!a.includes(e));return{jsPagesFiles:o,components:a,otherJsFiles:r}}async getAllWxmlAndWxsFiles(){const e=(await this.getPackageFiles(miniProgram,config_1.FullPkg)).map(e=>e.path),t=e.filter(e=>e.endsWith(".wxml")),i=e.filter(e=>e.endsWith(".wxs")),s=await this.getCodeByFileList(miniProgram,t.concat(i));return{wxmlFiles:t,wxsFiles:i,content:t.concat(i).reduce((e,t)=>{const i=s[t];if("error"in i)throw i.error;return e[t]=i.code,e["./"+t]=i.code,e},{})}}async getPackageWxmlAndWxsFiles(e){let t=(await this.getPackageFiles(miniProgram,e)).map(e=>e.path);if(e!==config_1.MainPkg&&e!==config_1.FullPkg){const e=(await this.getPackageFiles(miniProgram,config_1.MainPkg)).map(e=>e.path);t=t.concat(e)}const i=t.filter(e=>e.endsWith(".wxml")),s=t.filter(e=>e.endsWith(".wxs")),o=await this.getCodeByFileList(miniProgram,i.concat(s));return{wxmlFiles:i,wxsFiles:s,content:i.concat(s).reduce((e,t)=>{const i=o[t];if(!i)throw`lack of ${t} code`;if("error"in i)throw i.error;return e[t]=i.code,e["./"+t]=i.code,e},{})}}async getPackageWxssFileList(e){let t=(await this.getPackageFiles(miniProgram,e)).map(e=>e.path);if(e!==config_1.MainPkg&&e!==config_1.FullPkg){const e=(await this.getPackageFiles(miniProgram,config_1.MainPkg)).map(e=>e.path);t=t.concat(e)}return t.filter(e=>e.endsWith(".wxss"))}async getPackageWxssFiles(e){const t=await this.getPackageWxssFileList(e),i=await this.getCodeByFileList(miniProgram,t);return{wxssFiles:t,content:t.reduce((e,t)=>{const s=i[t];if(!s)throw`lack of ${t} code`;if("error"in s)throw s.error;return e[t]=s.code,e["./"+t]=s.code,e},{})}}getWxssMap(e,t){t=(0,tools_1.normalizePath)(t),e===miniProgram?t=path_1.default.posix.join(this.project.miniprogramRoot,t):e===miniProgramPlugin&&(t=path_1.default.posix.join(this.project.pluginRoot,t));const i=this.devCodeCacheByPath.get(t),s=null==i?void 0:i.codeFile;if(s&&!("error"in s))return s.map}async getMainPkgSortedJSFiles(){const e=await this.getConf(miniProgram),t=(await this.getPackageFiles(miniProgram,config_1.MainPkg)).map(e=>e.path).filter(e=>e.endsWith(".js")),i=[],s=[],o=[],a=[],r=[];let n=!1;const c={},l=t=>Object.keys(e.packages).find(e=>t.startsWith(e))||config_1.MainPkg;e.app.functionalPages&&t.forEach(e=>{if(e.startsWith("functional-pages/")){const t=e.replace(/\.js$/,"");if(c[t])return;c[t]=!0,r.push(encodeURI(t))}}),e.app.workers&&t.forEach(t=>{if(t.startsWith((0,tools_1.getWorkersPath)(e.app.workers))){const e=t.replace(/\.js$/,"");if(c[e])return;c[e]=!0,a.push(e)}});Object.keys(e.comps).filter(e=>l(e)===config_1.MainPkg).forEach(t=>{if((t.startsWith("miniprogram_npm/weui-miniprogram")||t.startsWith("weui-miniprogram"))&&e.app.useExtendedLib&&e.app.useExtendedLib.weui)return;if(c[t])return;c[t]=!0;const i=encodeURI(t);o.push(""+i)});Object.keys(e.pages).filter(e=>l(e)===config_1.MainPkg).forEach(e=>{if(c[e])return;c[e]=!0;const t=encodeURI(e);i.push(""+t)}),t.forEach(e=>{const t=e.replace(/\.js$/,"");c[t]||(c[t]=!0,"app.js"!==e?s.push(""+encodeURI(t)):n=!0)});const g=[...s,...o,...i];return n&&g.push("app"),{hasAppJS:n,allFiles:g,pageFiles:i,componentFiles:o,workerFiles:a,functionalPageFiles:r,otherFiles:s}}async getSubPkgSortedJSFiles(e){const t=await this.getConf(miniProgram),i=(await this.getPackageFiles(miniProgram,e)).map(e=>e.path).filter(e=>e.endsWith(".js")),s=[],o=[],a=[],r={},n=e=>Object.keys(t.packages).find(t=>e.startsWith(t))||config_1.MainPkg;Object.keys(t.comps).filter(t=>n(t)===e).forEach(e=>{if((e.startsWith("miniprogram_npm/weui-miniprogram")||e.startsWith("weui-miniprogram"))&&t.app.useExtendedLib&&t.app.useExtendedLib.weui)return;if(r[e])return;r[e]=!0;const i=encodeURI(e);a.push(""+i)});Object.keys(t.pages).filter(t=>n(t)===e).forEach(e=>{if(r[e])return;r[e]=!0;const t=encodeURI(e);s.push(""+t)});let c=t.packages[e].entry||"";c&&(c=path_1.default.posix.join(e,c),c=c.replace(/\.js$/,"")),i.forEach(e=>{const t=e.replace(/\.js$/,"");r[t]||(r[t]=!0,t!==c&&o.push(""+encodeURI(t)))});const l=i.map(e=>""+encodeURI(e.replace(/\.js$/,"")));return{entryJS:c,allFiles:l,pageFiles:s,componentFiles:a,otherFiles:o}}async compileJSList(e){const t=this.project.type;let i=config_1.COMPILE_TYPE.miniProgram;i=e.root===this.project.miniprogramRoot?this.isGameType(t)?config_1.COMPILE_TYPE.miniGame:config_1.COMPILE_TYPE.miniProgram:this.isGameType(t)?config_1.COMPILE_TYPE.miniGamePlugin:miniProgramPlugin;const s=await this.getCodeByFileList(i,e.fileList),o=[];for(const e in s){const t=s[e];if("error"in t)throw t.error;o.push(Object.assign({filePath:e,code:t.code,map:t.map,mtime:t.mtime},t.jsTag))}return o}async compileJS(e){const t=this.project.type;let i;if(e.root===this.project.miniprogramRoot){i=(await this.getCodeByFileList(this.isGameType(t)?config_1.COMPILE_TYPE.miniGame:config_1.COMPILE_TYPE.miniProgram,[e.filePath]))[e.filePath]}else{i=(await this.getCodeByFileList(this.isGameType(t)?config_1.COMPILE_TYPE.miniGamePlugin:miniProgramPlugin,[e.filePath]))[e.filePath]}if(!i){const t=new Error(`summer-compiler miss ${e.root} js file, ${e.filePath}`);throw t.code="ENOENT",t}if("error"in i)throw i.error;return Object.assign({filePath:e.filePath,code:i.code,map:i.map,mtime:i.mtime},i.jsTag)}async compile(e){Date.now();this.progressUpdateFromCompileOptions=e.onProgressUpdate;const t=(await this.getPackageFiles(this.isGameType(this.project.type)?miniGame:miniProgram,config_1.FullPkg,e.resultType,e.useCache)).map(e=>e.path),i=await this.subProcessManager.runTask("compileNewLogic",Object.assign(Object.assign({},e),{fileList:t,analyzer:void 0}),this.onProgressUpdate),s=i.app,o=Object.keys(s).filter(e=>e.endsWith(".json")),a=await this.compileOther(this.isGameType(this.project.type)?miniGame:miniProgram,e.resultType||"prod",o);let r={};if(this.isPluginType(this.project.type)){const t=i.plugin,o=Object.keys(t).filter(e=>e.endsWith(".json")),n=await this.compileOther(this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin,e.resultType||"prod",o);Object.keys(a).forEach(e=>{r[path_1.default.posix.join("miniprogram",e)]=a[e]}),Object.keys(n).forEach(e=>{r[path_1.default.posix.join("plugin",e)]=n[e]}),Object.keys(s).forEach(e=>{r[path_1.default.posix.join("miniprogram",e)]=s[e]}),Object.keys(t).forEach(e=>{r[path_1.default.posix.join("plugin",e)]=t[e]}),r["project.config.json"]=JSON.stringify({miniprogramRoot:"miniprogram",pluginRoot:"plugin",__compileDebugInfo__:{useSummer:!0}})}else r=Object.assign(Object.assign({},a),s),r["project.config.json"]=JSON.stringify({miniprogramRoot:"",__compileDebugInfo__:{useSummer:!0}});this.onProgressUpdate(111,"success",locales_1.default.config.SUMMER_PACK_FILES_FINISH.format());for(const e of Object.keys(r))"object"==typeof r[e]&&"Buffer"===r[e].type&&(r[e]=Buffer.from(r[e].data));return r}async compileOther(e,t,i){const s=(0,tools_1.getSupportCodeFileExtSet)(this.project);s.delete(".json");const o=await(0,white_ext_list_1.getWhiteExtList)();let a=o.MiniProgramWhiteList;this.isGameType(this.project.type)&&(a=o.GameWhiteList);const r=this.isPluginType(e)?this.project.pluginRoot:this.project.miniprogramRoot,n=await this.filterFactory(t),c=this.project.getFileList(r,"").filter(t=>{const o=path_1.default.posix.extname(t),c=path_1.default.posix.relative(r,t);return!(!a.has(o)||s.has(o)||i.includes(c))&&n(e,t)===config_1.EFilterCode.Include}),l=await(0,common_1.compileOther)(this.project,c,{onProgressUpdate:()=>{}}),g={};for(const e in l){g[path_1.default.posix.relative(r,e)]=l[e]}return g}async compile2(e){const t=await this.subProcessManager.runTask("compile",e,(t,i,s)=>{var o;null===(o=e.onProgressUpdate)||void 0===o||o.call(e,{id:t.toString(),status:i,message:s})});for(const e of Object.keys(t))"object"==typeof t[e]&&"Buffer"===t[e].type&&(t[e]=Buffer.from(t[e].data));return t}async getPluginJSON(e=""){return(await this.getConf(this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin)).plugin}async getPluginPageJSON(e){const t=await this.getConf(miniProgramPlugin),i=t.pages[e]||t.comps[e];if(!i)throw new Error("summer-compiler 收集plugin json配置有遗漏, "+e);return i}async getPluginComponents(){const e=await this.getConf(miniProgramPlugin),t=new Set(Object.keys(e.pages).concat(Object.keys(e.comps)));return Array.from(t)}async getPluginJSFiles(){const e=this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin,t=(await this.getPackageFiles(e,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".js")),i=await this.getCodeByFileList(e,t);return{jsFiles:t,content:t.reduce((e,t)=>{const s=i[t];if(!s)throw`lack of ${t} code`;if("error"in s)throw s.error;return e[t]=s.code,e["./"+t]=s.code,e},{})}}async getPluginWxssFiles(){const e=(await this.getPackageFiles(miniProgramPlugin,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".wxss")),t=await this.getCodeByFileList(miniProgramPlugin,e);return{wxssFiles:e,content:e.reduce((e,i)=>{const s=t[i];if(!s)throw`lack of ${i} code`;if("error"in s)throw s.error;return e[i]=s.code,e["./"+i]=s.code,e},{})}}async getPluginWxmlAndWxsFiles(){const e=(await this.getPackageFiles(miniProgramPlugin,config_1.FullPkg)).map(e=>e.path),t=e.filter(e=>e.endsWith(".wxml")),i=e.filter(e=>e.endsWith(".wxs")),s=await this.getCodeByFileList(miniProgramPlugin,t.concat(i));return{wxmlFiles:t,wxsFiles:i,content:t.concat(i).reduce((e,t)=>{const i=s[t];if(!i)throw`lack of ${t} code`;if("error"in i)throw i.error;return e[t]=i.code,e["./"+t]=i.code,e},{})}}async checkThemeJSON(e){return(await this.getConf(miniProgram)).theme}setProxy(e){(0,request_1.setCiProxy)(e)}setLocale(e){this._locale!==e&&(this._locale=e,this.subProcessManager.runTask("setLocale",e))}async uglifyFileNames(e,t,i){return await(0,uglifyfilenames_1.uglifyFileNames)(e,t,i)}async getMPFileInfo(){return this.subProcessManager.runTask("getLocalFileList",miniProgram)}async getPluginFileInfo(){return this.subProcessManager.runTask("getLocalFileList",miniProgramPlugin)}async getCompAndPagesOfConf(){const e=await this.getConf(miniProgram);return{pages:e.pages,comps:e.comps}}async getFiltedFileListReason(e){const t=this.project.getFileList(this.project.miniprogramRoot),i=[],s=await this.filterFactory(e),o=this.isGameType(this.project.type)?miniGame:miniProgram;for(const e of t){const t=s(o,e);t!==config_1.EFilterCode.Include&&i.push({file:e,code:t})}if(this.isPluginType(this.project.type)){const e=this.project.getFileList(this.project.pluginRoot),t=this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin;for(const o of e){const e=s(t,o);e!==config_1.EFilterCode.Include&&i.push({file:o,code:e})}}return i}}exports.SummerCompiler=SummerCompiler;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SummerCompiler=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),lodash_1=tslib_1.__importDefault(require("lodash")),locales_1=tslib_1.__importDefault(require("../../utils/locales/locales")),request_1=require("../../utils/request"),common_1=require("./original/compile/common"),tools_1=require("../../utils/tools"),white_ext_list_1=require("../../utils/white_ext_list"),config_1=require("../../config/config"),processManager_1=require("../../utils/subprocess/processManager"),messageHub_1=require("../../utils/messageHub"),singletontask_1=require("../../utils/singletontask"),uglifyfilenames_1=require("./original/protect/uglifyfilenames"),baseCompiler_1=require("./baseCompiler"),packOptionsHelper_1=tslib_1.__importDefault(require("../../utils/packOptionsHelper")),miniProgram=config_1.COMPILE_TYPE.miniProgram,miniGame=config_1.COMPILE_TYPE.miniGame,miniProgramPlugin=config_1.COMPILE_TYPE.miniProgramPlugin,miniGamePlugin=config_1.COMPILE_TYPE.miniGamePlugin;function performanceMark(e,t){}class SummerCompiler extends baseCompiler_1.BaseCoreCompiler{constructor(e,t,i,s,o,a){super(e),this.project=e,this.cachePath=t,this.projectInfo=i,this.devtoolMessagehub=s,this.analyzer=o,this._filterFactory=a,this.isSummer=!0,this.promiseCache=new Map,this._taskCache=new Map,this._status=void 0,this._eventAdded=!1,this._locale="",this.devCodeCacheByPath=new Map,this.onFileChange=(e,t)=>{if("change"!==e||t.endsWith(".json"))for(const e of this.promiseCache.keys())e.startsWith("getConf-")&&this.promiseCache.delete(e);if("change"!==e){for(const e of this.promiseCache.keys())e.startsWith("getPackageFiles-")&&this.promiseCache.delete(e);for(const e of this._taskCache.keys())e.startsWith("getPackageFiles-")&&this._taskCache.delete(e)}this.invalidCodeCache(t),this.subProcessManager.sendEvent("fileChange",{type:e,targetPath:t})},this.onPreCompileOptionsChange=async e=>{await this.clearCache(),this.subProcessManager.sendEvent("precompileOptionsChange",e)},this.onProgressUpdate=(e,t,i)=>{var s;this.messageHub.showBuildLog(""+e,t,i),null===(s=this.progressUpdateFromCompileOptions)||void 0===s||s.call(this,{id:e.toString(),message:i,status:t})},this._getPackageFiles=async(e,t,i="dev")=>{performanceMark("request get getPackageFiles");const s=await this.subProcessManager.runTask("getPackageFiles",{graphId:e,root:t},this.onProgressUpdate);performanceMark("request get getPackageFiles",!0);const o=this.isPluginType(e)?this.project.pluginRoot:this.project.miniprogramRoot,a=await this.filterFactory(i),r={},n=s.filter(t=>{const i=path_1.default.posix.join(o,t.source),s=a(e,i);return s!==config_1.EFilterCode.Include&&(r[s]||(r[s]=[]),r[s].push(i)),s===config_1.EFilterCode.Include}),c={[config_1.EFilterCode.AnalyseNoUse]:locales_1.default.config.UNUSE_FILE_LIST,[config_1.EFilterCode.PackOptionsIgnore]:locales_1.default.config.PACK_OPTIONS_IGNORE_LIST,[config_1.EFilterCode.PartialCompileNoUse]:locales_1.default.config.PARTIAL_COMPILE_IGNORE_LIST};for(const e in r)c[e]?this.onProgressUpdate(e,"warn",c[e].format(r[e].join(","))):this.onProgressUpdate(e,"warn",locales_1.default.config.UNKNOWN_REASON_INGORE_LIST.format(e,r[e].join(",")));return n},performanceMark("create summer compiler"),this.messageHub=new messageHub_1.MessageHub(s),this.ready()}get status(){return this._status}async init(){performanceMark("init summer compiler");const e=path_1.default.posix.join(__dirname,"./summerEntryProcess.js");this.subProcessManager=new processManager_1.SubProcessProxy(this.project,e,{cachePath:this.cachePath},this.projectInfo,8891,this.onProgressUpdate),this.addProjectListener(),this.loadStatus(),performanceMark("init summer compiler",!0)}async loadStatus(){this._status=await this.subProcessManager.runTask("loadStatus")}destroy(){var e;null===(e=this.subProcessManager)||void 0===e||e.destroy(),this.removeProjectListener(),this._checkReadyTask=void 0}async clearCache(){var e;await(null===(e=this.subProcessManager)||void 0===e?void 0:e.runTask("clearCache")),this.promiseCache.clear(),this.devCodeCacheByPath.clear(),this._taskCache.clear()}updateOptions(e){var t;lodash_1.default.isEqual(e,this.projectInfo)||(this.projectInfo=e,this.promiseCache.clear(),this.devCodeCacheByPath.clear(),null===(t=this.subProcessManager)||void 0===t||t.sendEvent("updateOptions",e),this.loadStatus(),this.project.updateOptions(e))}addProjectListener(){var e,t;this._eventAdded&&this.removeProjectListener(),null===(e=this.project.event)||void 0===e||e.on("fileChange",this.onFileChange),null===(t=this.project.event)||void 0===t||t.on("precompileOptionsChange",this.onPreCompileOptionsChange),this._eventAdded=!0}removeProjectListener(){var e,t;null===(e=this.project.event)||void 0===e||e.off("fileChange",this.onFileChange),null===(t=this.project.event)||void 0===t||t.off("precompileOptionsChange",this.onPreCompileOptionsChange),this._eventAdded=!1}invalidCodeCache(e){const t=this.devCodeCacheByPath.get((0,tools_1.sourcePathToTargetPath)(e));t&&(t.isValid=!1)}async getConf(e){var t,i;const s="getConf-"+e;if(this.promiseCache.has(s))return(null===(t=process.env)||void 0===t?void 0:t.isDevtools)&&console.log(s,"hit cache"),this.promiseCache.get(s);(null===(i=process.env)||void 0===i?void 0:i.isDevtools)&&console.log(s,"do request"),performanceMark("request get conf");const o={graphId:e},a=this.subProcessManager.runTask("getConf",o,this.onProgressUpdate);return this.promiseCache.set(s,a),performanceMark("request get conf",!0),a}async getPackageFiles(e,t,i="dev",s=!0){const o=`getPackageFiles-${e}-${t}-${i}`;if(this._taskCache.has(o)&&s){const e=this._taskCache.get(o);return null==e?void 0:e.getResult(!0)}const a=new singletontask_1.SingletonTask(this._getPackageFiles.bind(this,e,t,i),o);return this._taskCache.set(o,a),null==a?void 0:a.getResult(!0)}isMiniappPlatformInclude(e){const t=path_1.default.posix.join(this.project.miniprogramRoot,"app.miniapp.json");return(0,tools_1.isMiniappPlatform)(this.project.targetPlatform)&&t===e}async filterFactory(e){packOptionsHelper_1.default.updateState(this.project),this.onProgressUpdate("initUnusedFiles","doing","analyzing codes..."),await packOptionsHelper_1.default.initUnusedFiles(this.project,this.analyzer,"prod"===e),0!==packOptionsHelper_1.default.getUnusedFiles().size&&this.onProgressUpdate("initUnusedFiles","doing","ignoring files: "+Array.from(packOptionsHelper_1.default.getUnusedFiles()).join(",")),this.onProgressUpdate("initUnusedFiles","success","analyzing codes success");const t=this._filterFactory?await this._filterFactory(e):()=>0;return(i,s)=>{const o=packOptionsHelper_1.default.relativePath(s);return this.isMiniappPlatformInclude(s)||packOptionsHelper_1.default.isFileIncluded(o)?config_1.EFilterCode.Include:packOptionsHelper_1.default.isIgnoredByRules(o)?config_1.EFilterCode.PackOptionsIgnore:i===miniProgram&&packOptionsHelper_1.default.isIgnoreByUnusedFiles(s,"prod"===e)?config_1.EFilterCode.AnalyseNoUse:t(i,s)}}async getCodeByFileList(e,t){const i={},s={},o=this.isPluginType(e)?this.project.pluginRoot:this.project.miniprogramRoot,a=[];for(const e of t){const t=this.devCodeCacheByPath.get(path_1.default.posix.join(o,e)),r=null==t?void 0:t.codeFile;let n=!1;t&&t.isValid&&r&&!("error"in r)||(n=!0,a.push(e)),r&&!("error"in r)&&(n&&(i[e]=r.md5),s[e]=r)}if(a.length>0){const t=await this.subProcessManager.runTask("getDevCodeByFileList",{graphId:e,fileList:a,cacheMd5:i},this.onProgressUpdate);for(const e in t){const i=t[e],a=path_1.default.posix.join(o,e);"error"in i||""!==i.md5?this.devCodeCacheByPath.set(a,{isValid:!0,codeFile:i}):this.devCodeCacheByPath.delete(a),s[e]=i}}return s}async getExtJSON(){return(await this.getConf(miniProgram)).ext}async getAppJSON(){return(await this.getConf(miniProgram)).app}async getGameJSON(){return(await this.getConf(miniGame)).app}async getSiteMapJSON(){return(await this.getConf(miniProgram)).sitemap}async getPageJSON(e){const t=await this.getConf(miniProgram),i=t.pages[e]||t.comps[e];if(!i)throw new Error("summer-compiler 收集json配置有遗漏, "+e);return i}async getAllPageAndComponent(){const e=await this.getConf(miniProgram),t=(await this.getPackageFiles(miniProgram,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".json"));return Object.keys(e.pages).concat(Object.keys(e.comps)).filter(e=>t.includes(e+".json"))}async getAllSortedJSFiles(){var e,t,i,s;const o=this.isGameType(this.project.type),a=o?miniGame:miniProgram,r=await this.getConf(a),n=Object.keys(null!==(e=r.pages)&&void 0!==e?e:{}),c=Object.keys(null!==(t=r.comps)&&void 0!==t?t:{}),l=await this.getPackageFiles(a,config_1.FullPkg),g=null!==(i=null==l?void 0:l.map(e=>e.path).filter(e=>e.endsWith(".js")))&&void 0!==i?i:[],p=null!==(s=null==n?void 0:n.filter(e=>!c.includes(e)).map(e=>e+".js").filter(e=>g.includes(e)))&&void 0!==s?s:[],h=c.map(e=>e+".js").filter(e=>g.includes(e)),m=g.filter(e=>e.endsWith(".js")&&e!==(o?"game.js":"app.js")&&!p.includes(e)&&!h.includes(e));return{jsPagesFiles:p,components:h,otherJsFiles:m}}async getAllWxmlAndWxsFiles(){const e=(await this.getPackageFiles(miniProgram,config_1.FullPkg)).map(e=>e.path),t=e.filter(e=>e.endsWith(".wxml")),i=e.filter(e=>e.endsWith(".wxs")),s=await this.getCodeByFileList(miniProgram,t.concat(i));return{wxmlFiles:t,wxsFiles:i,content:t.concat(i).reduce((e,t)=>{const i=s[t];if("error"in i)throw i.error;return e[t]=i.code,e["./"+t]=i.code,e},{})}}async getPackageWxmlAndWxsFiles(e){let t=(await this.getPackageFiles(miniProgram,e)).map(e=>e.path);if(e!==config_1.MainPkg&&e!==config_1.FullPkg){const e=(await this.getPackageFiles(miniProgram,config_1.MainPkg)).map(e=>e.path);t=t.concat(e)}const i=t.filter(e=>e.endsWith(".wxml")),s=t.filter(e=>e.endsWith(".wxs")),o=await this.getCodeByFileList(miniProgram,i.concat(s));return{wxmlFiles:i,wxsFiles:s,content:i.concat(s).reduce((e,t)=>{const i=o[t];if(!i)throw`lack of ${t} code`;if("error"in i)throw i.error;return e[t]=i.code,e["./"+t]=i.code,e},{})}}async getPackageWxssFileList(e){let t=(await this.getPackageFiles(miniProgram,e)).map(e=>e.path);if(e!==config_1.MainPkg&&e!==config_1.FullPkg){const e=(await this.getPackageFiles(miniProgram,config_1.MainPkg)).map(e=>e.path);t=t.concat(e)}return t.filter(e=>e.endsWith(".wxss"))}async getPackageWxssFiles(e){const t=await this.getPackageWxssFileList(e),i=await this.getCodeByFileList(miniProgram,t);return{wxssFiles:t,content:t.reduce((e,t)=>{const s=i[t];if(!s)throw`lack of ${t} code`;if("error"in s)throw s.error;return e[t]=s.code,e["./"+t]=s.code,e},{})}}getWxssMap(e,t){t=(0,tools_1.normalizePath)(t),e===miniProgram?t=path_1.default.posix.join(this.project.miniprogramRoot,t):e===miniProgramPlugin&&(t=path_1.default.posix.join(this.project.pluginRoot,t));const i=this.devCodeCacheByPath.get(t),s=null==i?void 0:i.codeFile;if(s&&!("error"in s))return s.map}async getMainPkgSortedJSFiles(){const e=await this.getConf(miniProgram),t=(await this.getPackageFiles(miniProgram,config_1.MainPkg)).map(e=>e.path).filter(e=>e.endsWith(".js")),i=[],s=[],o=[],a=[],r=[];let n=!1;const c={},l=t=>Object.keys(e.packages).find(e=>t.startsWith(e))||config_1.MainPkg;e.app.functionalPages&&t.forEach(e=>{if(e.startsWith("functional-pages/")){const t=e.replace(/\.js$/,"");if(c[t])return;c[t]=!0,r.push(encodeURI(t))}}),e.app.workers&&t.forEach(t=>{if(t.startsWith((0,tools_1.getWorkersPath)(e.app.workers))){const e=t.replace(/\.js$/,"");if(c[e])return;c[e]=!0,a.push(e)}});Object.keys(e.comps).filter(e=>l(e)===config_1.MainPkg).forEach(t=>{if((t.startsWith("miniprogram_npm/weui-miniprogram")||t.startsWith("weui-miniprogram"))&&e.app.useExtendedLib&&e.app.useExtendedLib.weui)return;if(c[t])return;c[t]=!0;const i=encodeURI(t);o.push(""+i)});Object.keys(e.pages).filter(e=>l(e)===config_1.MainPkg).forEach(e=>{if(c[e])return;c[e]=!0;const t=encodeURI(e);i.push(""+t)}),t.forEach(e=>{const t=e.replace(/\.js$/,"");c[t]||(c[t]=!0,"app.js"!==e?s.push(""+encodeURI(t)):n=!0)});const g=[...s,...o,...i];return n&&g.push("app"),{hasAppJS:n,allFiles:g,pageFiles:i,componentFiles:o,workerFiles:a,functionalPageFiles:r,otherFiles:s}}async getSubPkgSortedJSFiles(e){const t=await this.getConf(miniProgram),i=(await this.getPackageFiles(miniProgram,e)).map(e=>e.path).filter(e=>e.endsWith(".js")),s=[],o=[],a=[],r={},n=e=>Object.keys(t.packages).find(t=>e.startsWith(t))||config_1.MainPkg;Object.keys(t.comps).filter(t=>n(t)===e).forEach(e=>{if((e.startsWith("miniprogram_npm/weui-miniprogram")||e.startsWith("weui-miniprogram"))&&t.app.useExtendedLib&&t.app.useExtendedLib.weui)return;if(r[e])return;r[e]=!0;const i=encodeURI(e);a.push(""+i)});Object.keys(t.pages).filter(t=>n(t)===e).forEach(e=>{if(r[e])return;r[e]=!0;const t=encodeURI(e);s.push(""+t)});let c=t.packages[e].entry||"";c&&(c=path_1.default.posix.join(e,c),c=c.replace(/\.js$/,"")),i.forEach(e=>{const t=e.replace(/\.js$/,"");r[t]||(r[t]=!0,t!==c&&o.push(""+encodeURI(t)))});const l=i.map(e=>""+encodeURI(e.replace(/\.js$/,"")));return{entryJS:c,allFiles:l,pageFiles:s,componentFiles:a,otherFiles:o}}async compileJSList(e){const t=this.project.type;let i=config_1.COMPILE_TYPE.miniProgram;i=e.root===this.project.miniprogramRoot?this.isGameType(t)?config_1.COMPILE_TYPE.miniGame:config_1.COMPILE_TYPE.miniProgram:this.isGameType(t)?config_1.COMPILE_TYPE.miniGamePlugin:miniProgramPlugin;const s=await this.getCodeByFileList(i,e.fileList),o=[];for(const e in s){const t=s[e];if("error"in t)throw t.error;o.push(Object.assign({filePath:e,code:t.code,map:t.map,mtime:t.mtime},t.jsTag))}return o}async compileJS(e){const t=this.project.type;let i;if(e.root===this.project.miniprogramRoot){i=(await this.getCodeByFileList(this.isGameType(t)?config_1.COMPILE_TYPE.miniGame:config_1.COMPILE_TYPE.miniProgram,[e.filePath]))[e.filePath]}else{i=(await this.getCodeByFileList(this.isGameType(t)?config_1.COMPILE_TYPE.miniGamePlugin:miniProgramPlugin,[e.filePath]))[e.filePath]}if(!i){const t=new Error(`summer-compiler miss ${e.root} js file, ${e.filePath}`);throw t.code="ENOENT",t}if("error"in i)throw i.error;return Object.assign({filePath:e.filePath,code:i.code,map:i.map,mtime:i.mtime},i.jsTag)}async compile(e){Date.now();this.progressUpdateFromCompileOptions=e.onProgressUpdate;const t=(await this.getPackageFiles(this.isGameType(this.project.type)?miniGame:miniProgram,config_1.FullPkg,e.resultType,e.useCache)).map(e=>e.path),i=await this.subProcessManager.runTask("compileNewLogic",Object.assign(Object.assign({},e),{fileList:t,analyzer:void 0}),this.onProgressUpdate),s=i.app,o=Object.keys(s).filter(e=>e.endsWith(".json")),a=await this.compileOther(this.isGameType(this.project.type)?miniGame:miniProgram,e.resultType||"prod",o);let r={};if(this.isPluginType(this.project.type)){const t=i.plugin,o=Object.keys(t).filter(e=>e.endsWith(".json")),n=await this.compileOther(this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin,e.resultType||"prod",o);Object.keys(a).forEach(e=>{r[path_1.default.posix.join("miniprogram",e)]=a[e]}),Object.keys(n).forEach(e=>{r[path_1.default.posix.join("plugin",e)]=n[e]}),Object.keys(s).forEach(e=>{r[path_1.default.posix.join("miniprogram",e)]=s[e]}),Object.keys(t).forEach(e=>{r[path_1.default.posix.join("plugin",e)]=t[e]}),r["project.config.json"]=JSON.stringify({miniprogramRoot:"miniprogram",pluginRoot:"plugin",__compileDebugInfo__:{useSummer:!0}})}else r=Object.assign(Object.assign({},a),s),r["project.config.json"]=JSON.stringify({miniprogramRoot:"",__compileDebugInfo__:{useSummer:!0}});this.onProgressUpdate(111,"success",locales_1.default.config.SUMMER_PACK_FILES_FINISH.format());for(const e of Object.keys(r))"object"==typeof r[e]&&"Buffer"===r[e].type&&(r[e]=Buffer.from(r[e].data));return r}async compileOther(e,t,i){const s=(0,tools_1.getSupportCodeFileExtSet)(this.project);s.delete(".json");const o=await(0,white_ext_list_1.getWhiteExtList)();let a=o.MiniProgramWhiteList;this.isGameType(this.project.type)&&(a=o.GameWhiteList);const r=this.isPluginType(e)?this.project.pluginRoot:this.project.miniprogramRoot,n=await this.filterFactory(t),c=this.project.getFileList(r,"").filter(t=>{const o=path_1.default.posix.extname(t),c=path_1.default.posix.relative(r,t);return!(!a.has(o)||s.has(o)||i.includes(c))&&n(e,t)===config_1.EFilterCode.Include}),l=await(0,common_1.compileOther)(this.project,c,{onProgressUpdate:()=>{}}),g={};for(const e in l){g[path_1.default.posix.relative(r,e)]=l[e]}return g}async compile2(e){const t=await this.subProcessManager.runTask("compile",e,(t,i,s)=>{var o;null===(o=e.onProgressUpdate)||void 0===o||o.call(e,{id:t.toString(),status:i,message:s})});for(const e of Object.keys(t))"object"==typeof t[e]&&"Buffer"===t[e].type&&(t[e]=Buffer.from(t[e].data));return t}async getPluginJSON(e=""){return(await this.getConf(this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin)).plugin}async getPluginPageJSON(e){const t=await this.getConf(miniProgramPlugin),i=t.pages[e]||t.comps[e];if(!i)throw new Error("summer-compiler 收集plugin json配置有遗漏, "+e);return i}async getPluginComponents(){const e=await this.getConf(miniProgramPlugin),t=new Set(Object.keys(e.pages).concat(Object.keys(e.comps)));return Array.from(t)}async getPluginJSFiles(){const e=this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin,t=(await this.getPackageFiles(e,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".js")),i=await this.getCodeByFileList(e,t);return{jsFiles:t,content:t.reduce((e,t)=>{const s=i[t];if(!s)throw`lack of ${t} code`;if("error"in s)throw s.error;return e[t]=s.code,e["./"+t]=s.code,e},{})}}async getPluginWxssFiles(){const e=(await this.getPackageFiles(miniProgramPlugin,config_1.FullPkg)).map(e=>e.path).filter(e=>e.endsWith(".wxss")),t=await this.getCodeByFileList(miniProgramPlugin,e);return{wxssFiles:e,content:e.reduce((e,i)=>{const s=t[i];if(!s)throw`lack of ${i} code`;if("error"in s)throw s.error;return e[i]=s.code,e["./"+i]=s.code,e},{})}}async getPluginWxmlAndWxsFiles(){const e=(await this.getPackageFiles(miniProgramPlugin,config_1.FullPkg)).map(e=>e.path),t=e.filter(e=>e.endsWith(".wxml")),i=e.filter(e=>e.endsWith(".wxs")),s=await this.getCodeByFileList(miniProgramPlugin,t.concat(i));return{wxmlFiles:t,wxsFiles:i,content:t.concat(i).reduce((e,t)=>{const i=s[t];if(!i)throw`lack of ${t} code`;if("error"in i)throw i.error;return e[t]=i.code,e["./"+t]=i.code,e},{})}}async checkThemeJSON(e){return(await this.getConf(miniProgram)).theme}setProxy(e){(0,request_1.setCiProxy)(e)}setLocale(e){this._locale!==e&&(this._locale=e,this.subProcessManager.runTask("setLocale",e))}async uglifyFileNames(e,t,i){return await(0,uglifyfilenames_1.uglifyFileNames)(e,t,i)}async getMPFileInfo(){return this.subProcessManager.runTask("getLocalFileList",miniProgram)}async getPluginFileInfo(){return this.subProcessManager.runTask("getLocalFileList",miniProgramPlugin)}async getCompAndPagesOfConf(){const e=await this.getConf(miniProgram);return{pages:e.pages,comps:e.comps}}async getFiltedFileListReason(e){const t=this.project.getFileList(this.project.miniprogramRoot),i=[],s=await this.filterFactory(e),o=this.isGameType(this.project.type)?miniGame:miniProgram;for(const e of t){const t=s(o,e);t!==config_1.EFilterCode.Include&&i.push({file:e,code:t})}if(this.isPluginType(this.project.type)){const e=this.project.getFileList(this.project.pluginRoot),t=this.isGameType(this.project.type)?miniGamePlugin:miniProgramPlugin;for(const o of e){const e=s(t,o);e!==config_1.EFilterCode.Include&&i.push({file:o,code:e})}}return i}}exports.SummerCompiler=SummerCompiler;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.remoteBuildProjectMaterialAbsoluteCacheDir=void 0;const tslib_1=require("tslib"),child_process=tslib_1.__importStar(require("child_process")),path_1=tslib_1.__importDefault(require("path")),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),glob_1=tslib_1.__importDefault(require("glob")),env_1=require("../../../utils/env"),miniapp_builder_1=require("../../../utils/miniapp-builder"),codesign_1=require("../../../utils/codesign"),miniappJson_1=require("../../../utils/miniappJson"),lodash_1=require("lodash"),tools_1=require("../../../utils/tools"),uuidv4=require("uuid/v4"),sizeOf=require("image-size"),plist=require("simple-plist"),errorIOSSdkVersions=["1.0.19"],APPEX_PROFILES_MAPS_FILE="__appexProfilesCacheDir__/profilesMap.json",APPEX_PROFILES_MAPS_FOR_SHELL_FILE="__appexProfilesCacheDir__/profilesMapForShell.txt",defaultIconDirPath=path_1.default.join(__dirname,"../../../static/images/"),getDepReg=e=>new RegExp(`s.subspec '${e}'.*\n(?:.*\n)*?(?:.*sp.vendored_frameworks = \\[\n)((?:.*'.*?'.*\n)*?)(?:.*\\]\n)`,"m"),allowTheme=["Light","LightSpecial","Dark","DarkSpecial","Default"];exports.remoteBuildProjectMaterialAbsoluteCacheDir="__absoluteFile";const iconInfoMap={appStore1024:{size:[1024,1024],scale:1,idiom:"ios-marketing",required:!0},appStore1024Other:{size:[1024,1024],scale:1,idiom:"ios-marketing-other"},mainIcon120:{size:[60,60],scale:2,idiom:"iphone",required:!0},mainIcon180:{size:[60,60],scale:3,idiom:"iphone"},spotlightIcon80:{size:[40,40],scale:2,idiom:"iphone"},spotlightIcon120:{size:[40,40],scale:3,idiom:"iphone"},settingsIcon58:{size:[29,29],scale:2,idiom:"iphone"},settingsIcon87:{size:[29,29],scale:3,idiom:"iphone"},notificationIcon40:{size:[20,20],scale:2,idiom:"iphone"},notificationIcon60:{size:[20,20],scale:3,idiom:"iphone"},ipadMainIcon152:{size:[76,76],scale:2,idiom:"ipad"},ipadMainIcon167:{size:[83.5,83.5],scale:2,idiom:"ipad"},ipadSpotlightIcon40:{size:[40,40],scale:1,idiom:"ipad"},ipadSpotlightIcon80:{size:[40,40],scale:2,idiom:"ipad"},ipadSettingsIcon29:{size:[29,29],scale:1,idiom:"ipad"},ipadSpotlightIcon58:{size:[29,29],scale:2,idiom:"ipad"},ipadNotificationIcon20:{size:[20,20],scale:1,idiom:"ipad"},ipadNotificationIcon40:{size:[20,20],scale:2,idiom:"ipad"}};class buildCloudManager{generateTempDemoIpaPath(e){const i=path_1.default.join(e,"../.."),n=path_1.default.basename(i),t=path_1.default.dirname(i),a=path_1.default.join(t,n+"-operateDir");fs_extra_1.default.existsSync(a)&&fs_extra_1.default.removeSync(a),fs_extra_1.default.ensureDirSync(a);const s=path_1.default.join(a,"Payload/demo.app");return fs_extra_1.default.copySync(e,s),s}generateInfoPlistCFBundleURLTypesItem(e){const i={};return e.CFBundleURLName&&(i.CFBundleURLName=e.CFBundleURLName),e.CFBundleURLSchemes&&(i.CFBundleURLSchemes=[e.CFBundleURLSchemes]),e.CFBundleTypeRole&&(i.CFBundleTypeRole=e.CFBundleTypeRole),i}updatePrivacyBackgroundImage(e,i,n,t,a){n.message("doing","updatePrivacyBackgroundImage "+t);if(fs_extra_1.default.readdirSync(i).forEach(e=>{"privacy_"+t===path_1.default.basename(e,path_1.default.extname(e))&&fs_extra_1.default.removeSync(path_1.default.join(i,e))}),!a)return;path_1.default.isAbsolute(a)||(a=path_1.default.join(e,a)),a=this.getMaterialFilePath(e,a);const s=path_1.default.extname(a),o=path_1.default.join(i,`privacy_${t}${s}`);try{fs_extra_1.default.copyFileSync(a,o)}catch(e){throw n.message("error",`copy privacy image failed: ${t}, ${a} to ${o}`),e}}async updateIOSInfoPlistInfo(e,i,n,t,a,s){var o,r,l,d,p,u,c,f,_,h,g;a.progress("update app base info...");const{mobileapp_info:m={}}=i,y=m.mobileapp_id,I=path_1.default.join(n,"Info.plist"),S={},v=(e,i)=>{var n,t;if((null==i?void 0:i.startsWith("%"))&&(null==i?void 0:i.endsWith("%"))){const o=i.slice(1,-1);S[e]=o;const r=(null===(t=null===(n=null==s?void 0:s.base)||void 0===n?void 0:n.ios)||void 0===t?void 0:t[o])||"";return r||a.message("error",`未在国际化配置 base.json 中找到字段 ${o},请检查`),r}return i};v("UISplashScreenImageName",null===(o=null==t?void 0:t.splashscreen)||void 0===o?void 0:o.customImage),v("UILaunchStoryboardName",null===(r=null==t?void 0:t.splashscreen)||void 0===r?void 0:r.customImage);const x=plist.readFileSync(I);if(x.CFBundleName=v("CFBundleName",t.name),x.CFBundleDisplayName=v("CFBundleDisplayName",t.name),x.CFBundleShortVersionString=t.version,"number"==typeof t.versionCode?x.CFBundleVersion=parseInt(t.versionCode.toString(),10).toString():x.CFBundleVersion=(parseInt(x.CFBundleVersion,10)+1).toString(),x.CFBundleIdentifier=this.getBundleIdentifier(m),Array.isArray(null==t?void 0:t.openMimeTypes)&&this.validateCFBundleDocumentTypes(t.openMimeTypes,a)&&(x.CFBundleDocumentTypes=t.openMimeTypes,a.message("doing","openMimeTypes 应用成功")),Array.isArray(x.CFBundleURLTypes)||(x.CFBundleURLTypes=[]),(null===(d=null===(l=x.CFBundleURLTypes)||void 0===l?void 0:l[0])||void 0===d?void 0:d.CFBundleURLSchemes)&&(x.CFBundleURLTypes[0].CFBundleURLSchemes=[y]),x.CFBundleURLTypes[0]&&(x.CFBundleURLTypes=[x.CFBundleURLTypes[0]]),Object.keys(miniappJson_1.iosPrivacyDescObj).forEach(e=>{var i,n;(null===(i=null==t?void 0:t.privateDescriptions)||void 0===i?void 0:i[e])?x[e]=v(e,null===(n=t.privateDescriptions)||void 0===n?void 0:n[e]):delete x[e]}),!0===(null===(p=null==t?void 0:t.infoPlist)||void 0===p?void 0:p.DisableAppUsesNonExemptEncryption)?x.ITSAppUsesNonExemptEncryption=!1:delete x.ITSAppUsesNonExemptEncryption,x.UIBackgroundModes=[],!0===(null===(u=null==t?void 0:t.infoPlist)||void 0===u?void 0:u.AudioInBackgroundMode)&&x.UIBackgroundModes.push("audio"),!0===(null===(c=null==t?void 0:t.infoPlist)||void 0===c?void 0:c.LocationInBackgroundMode)&&x.UIBackgroundModes.push("location"),!0===(null===(f=null==t?void 0:t.infoPlist)||void 0===f?void 0:f.requiresFullScreen)?x.UIRequiresFullScreen=!0:delete x.UIRequiresFullScreen,"object"==typeof(null===(_=null==t?void 0:t.infoPlist)||void 0===_?void 0:_.CFBundleURLTypes)){const e=this.generateInfoPlistCFBundleURLTypesItem(t.infoPlist.CFBundleURLTypes);x.CFBundleURLTypes.push(e);const{additionalCFBundleURLTypes:i}=t.infoPlist.CFBundleURLTypes;Array.isArray(i)&&i.forEach(e=>{if("object"==typeof e){const i=this.generateInfoPlistCFBundleURLTypesItem(e);x.CFBundleURLTypes.push(i)}})}if(null===(h=null==t?void 0:t.useExtendedSdk)||void 0===h?void 0:h.WeAppGoogleLogin){if(!(null==t?void 0:t.googleLoginClientID)||!(null==t?void 0:t.googleLoginBundleUrlType))throw new Error("勾选了 Google Login 拓展模块但未填写 googleLoginClientID 或 googleLoginBundleUrlType 将导致拓展模块无法使用");x.GIDClientID=t.googleLoginClientID,Array.isArray(x.CFBundleURLTypes)?x.CFBundleURLTypes.push({CFBundleURLSchemes:[t.googleLoginBundleUrlType]}):x.CFBundleURLTypes=[{CFBundleURLSchemes:[t.googleLoginBundleUrlType]}]}if(!0===t.enableIpad&&((0,miniappJson_1.iOSAppJsonIsUsingIPadResizable)(e)?(x["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],a.progress("ipad is support Landscape")):(x["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown"],a.progress("ipad is not support Landscape"))),null===(g=t.infoPlist)||void 0===g?void 0:g.LSApplicationQueriesSchemes){const e=t.infoPlist.LSApplicationQueriesSchemes.split(",");e.length&&x.LSApplicationQueriesSchemes.push(...e.filter(e=>e))}return plist.writeFileSync(I,x),await this.writeI18NInfoFile(n,s,S),x.CFBundleVersion}getBundleIdentifier(e){return e.ios_flag&&e.bundle_id||e.debug_ios_bundle_id}validateCFBundleDocumentTypes(e,i){const n=["Owner","Default"," Alternate","None"],t=["Editor","Viewer"," Shell","None"],a=new Set;for(const s of e){if(a.has(s.CFBundleTypeName))return i.message("error","openMimeTypes 应用失败,存在重复定义的 CFBundleTypeName: "+s.CFBundleTypeName),!1;if(a.add(s.CFBundleTypeName),!n.includes(s.LSHandlerRank))return i.message("error","openMimeTypes 应用失败,存在不合法的 LSHandlerRank: "+s.LSHandlerRank),!1;if(!t.includes(s.CFBundleTypeRole))return i.message("error","openMimeTypes 应用失败,存在不合法的 CFBundleTypeRole: "+s.CFBundleTypeRole),!1;if(!Array.isArray(s.LSItemContentTypes))return i.message("error","openMimeTypes 应用失败,LSItemContentTypes 类型不合法"),!1}return!0}useGDT(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingGDT)(e)}async updateIOSAppConfigPlistInfo(e,i,n,t,a,s,o,r="Dark",l){var d,p,u,c;o.progress("update app module info...");const{module_info:f={},cpa_info:_={},cpa_package_info:h={enable_remove_watermark:!1}}=i;if(!_.sdk_key||!_.sdk_key_secret)throw new Error("sdkKey and sdkSecret not found");const g=path_1.default.join(n,"MiniApp.bundle"),m=path_1.default.join(g,"AppConfig.plist"),y=plist.readFileSync(m);h.enable_remove_watermark?y.enableRemoveWatermark=!0:y.splashscreenTheme=r,y.miniModuleId=f.module_id,y.sdkKey=_.sdk_key,y.sdkSecret=_.sdk_key_secret;const{privacy:I={}}=t;y.privacy||(y.privacy={}),y.privacy.enable=!!I.enable;const S=path_1.default.posix.join(g,"configs/privacy.json"),{contentViewImage:v,cancelButtonImage:x,confirmButtonImage:b,template:F}=I;if(I.enable){let i=F||"";if(fs_extra_1.default.ensureDirSync(path_1.default.posix.join(g,"configs")),i.startsWith("%")&&i.endsWith("%")){const n=F.slice(1,-1);i=(null===(p=null===(d=null==l?void 0:l.base)||void 0===d?void 0:d.ios)||void 0===p?void 0:p[n])||"",i||o.message("error",`未在国际化配置 base.json 中找到字段 ${n},请检查`),Object.keys(l).forEach(i=>{var t,a;if("base"===i)return;let s=null===(a=null===(t=l[i])||void 0===t?void 0:t.ios)||void 0===a?void 0:a[n];if(s){s=this.getMaterialFilePath(e,s);const n=`configs/privacy-${i}.json`,t=path_1.default.posix.join(g,n);fs_extra_1.default.existsSync(s)?fs_extra_1.default.copyFileSync(s,t):o.message("error",`未找到隐私协议在国际化配置 ${i}.json 中配置的文件 ${s},请检查`)}})}i?(i=this.getMaterialFilePath(e,i),fs_extra_1.default.existsSync(i)?(fs_extra_1.default.copyFileSync(i,S),y.privacy.template="configs/privacy.json"):(o.message("error",`未找到隐私协议中配置的文件 ${i},请检查`),y.privacy.template="configs/defaultPrivacy.json")):y.privacy.template="configs/defaultPrivacy.json",!0===I.enableNativePlugin&&"string"==typeof I.nativePluginId&&I.nativePluginId.length>2&&(y.privacy.plugin={pluginId:I.nativePluginId,enable:!0})}else y.privacy.template="",fs_extra_1.default.removeSync(S);this.updatePrivacyBackgroundImage(e,n,o,"contentViewImage",v),this.updatePrivacyBackgroundImage(e,n,o,"confirmButtonImage",b),this.updatePrivacyBackgroundImage(e,n,o,"cancelButtonImage",x);const{appMenuEnable:P=!0}=t;y.appMenuEnable=P;const{enableVConsole:B="undefined"}=t;y.enableVConsole=B;const{tpush:j}=t;let C=!1;if("object"==typeof j){const e=path_1.default.posix.join(n,"PlugIns/TPNSService.appex"),i=path_1.default.posix.join(e,"AppConfig.plist");if(this.useTpush(t)){y.TPNSAccessID=j.accessID,y.TPNSAccessKey=j.accessKey,j.clusterDomainName?y.clusterDomainName=j.clusterDomainName:delete y.clusterDomainName;const n=s?"x86_64":"arm64",t=path_1.default.join(a,`appex/${n}/TPNSService.appex`);if(!fs_extra_1.default.existsSync(t))throw new Error("can not found extendsdk: "+t);try{fs_extra_1.default.copySync(t,e),plist.writeFileSync(i,y),C=!0}catch(e){throw new Error("copy TPNSService.appex to app failed: "+e)}}}if(!C)try{const e=path_1.default.posix.join(n,"PlugIns");fs_extra_1.default.existsSync(e)?(fs_extra_1.default.removeSync(e),o.progress("removed PlugIns folder...")):o.progress("no PlugIns folder...")}catch(e){throw new Error("remove TPNSService.appex from app failed: "+e)}if(null===(u=t.useExtendedSdk)||void 0===u?void 0:u.WeAppLBS){if(!t.qmapAPIKey)throw new Error("You need to provide the Tencent Location Service API Key when using LBS SDK.");y.qmapAPIKey=t.qmapAPIKey}const{gdt:L}=t,w=this.useGDT(t);if(y.GDTAd=w?{appid:L.appid,enable:!0,SplashAd:{placementId:L.splashAd_placementId,fetchDelay:L.splashAd_fetchDelay||3,defaultEnable:null===(c=L.splashAd_defaultEnable)||void 0===c||c}}:{appid:"",enable:!1,SplashAd:{placementId:"",fetchDelay:3}},t["mini-plugin"]&&Array.isArray(t["mini-plugin"].ios)){const e=t["mini-plugin"].ios.filter(e=>!!(e.open&&e.pluginId&&e.loadWhenStart)).map(e=>e.pluginId);y.plugins={loadWhenStart:e}}const{enableDebugLog:D=!1}=t;y.enableDebugLog=D;const{debugLogSizeLimit:A=10}=t;isNaN(Number(A))?o.message("error",`ios debugLogSizeLimit ${A} is NaN`):y.debugLogSizeLimit=Number(A);const{enableOpenUrlNavigate:$=!1}=t;y.enableOpenUrlNavigate=$,plist.writeFileSync(m,y)}async updateIOSAppexInfoPlistInfo(e,i,n,t,a){if(this.useTpush(n)){a.progress("update appex for notification base info...");const{mobileapp_info:s={}}=e,o=path_1.default.join(i,"PlugIns/TPNSService.appex"),r=path_1.default.join(o,"Info.plist"),l=plist.readFileSync(r);l.CFBundleShortVersionString=n.version,a.progress("update appex for CFBundleVersion: "+t),l.CFBundleVersion=t;const d=s.ios_flag&&s.bundle_id||s.debug_ios_bundle_id;l.CFBundleIdentifier=n.tpush.serviceBundleId||d+".service",a.progress("update appex bundle identifier for infoPlist : "+l.CFBundleIdentifier),plist.writeFileSync(r,l)}else a.progress("not using tpush...")}updateBundleIcons(e,i,n,t,a){const s=[],o=[],r=[];for(const l in n){if(!n[l])continue;const d=this.getMaterialFilePath(e,n[l]);if(!d)return void a.message("error","getMatrialFailed: "+n[l]);const p=iconInfoMap[l];try{const e=sizeOf(d),i=p.size[0]*p.scale,t=p.size[1]*p.scale;if(e.width!==i||e.height!==t){a.progress(`check ${l} size failed, require [${i}, ${t}] but [${e.width}, ${e.height}] ingore ${n[l]} `);continue}}catch(e){a.progress(`get ${l} info failed, ingore ${n[l]}(e: ${e.message})`);continue}const u=path_1.default.extname(d),c=1===p.scale?"":`@${p.scale}x`,f=`${p.size[0]}x${p.size[1]}`,_=l.startsWith("ipad"),h="appStore1024"===l||"appStore1024Other"===l,g="appStore1024Other"===l?t+"Other":t,m=path_1.default.join(i,`${g}${f}${c}${_?"~ipad":""}${u}`),y={from:d,to:m,filename:path_1.default.basename(m),size:f,scale:p.scale+"x",idiom:p.idiom,key:l};s.push(y),h||(_?r.includes(`${g}${f}`)||r.push(`${g}${f}${c}`):o.includes(`${g}${f}`)||o.push(`${g}${f}${c}`))}return{iphoneBundleIconFiles:o,ipadBundleIconFiles:r,addFiles:s}}async updateIOSIcons(e,i,n,t,a,s){s.progress("update app icons...");const{icons:o={}}=t,r=a&&!env_1.isWin&&!!n;s.progress("genAssetCar: "+r);const l=glob_1.default.sync("AppIcon*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).map(e=>path_1.default.join(i,e)),d="AppIcon-"+uuidv4().slice(0,8),p=this.updateBundleIcons(e,i,o,d,s);if(!p)throw new Error("updateBundleIcons failed");const{iphoneBundleIconFiles:u=[],ipadBundleIconFiles:c=[],addFiles:f=[]}=p,_={};for(const e in iconInfoMap){if(!iconInfoMap[e].required||o[e])continue;const i=iconInfoMap[e].size[0]*iconInfoMap[e].scale,n=iconInfoMap[e].size[1]*iconInfoMap[e].scale;if(_[e]=path_1.default.join(defaultIconDirPath,`donut-icon${i}x${n}.png`),s.progress(`using default app icons when ${e} is not config...`),!fs_extra_1.default.existsSync(_[e]))throw new Error(`required ${e} but not default or set`)}const h=this.updateBundleIcons(e,i,_,d,s);if(!h)throw new Error("updateBundleIcons WithDefaultIcon failed");const{iphoneBundleIconFiles:g,ipadBundleIconFiles:m,addFiles:y}=h;if(u.push(...g),c.push(...m),f.push(...y),!u.length&&!c.length)return;l.forEach(e=>{fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e)});const I=path_1.default.join(n,"__assetCarOperateDir/assetsCar/"),S=path_1.default.join(I,`Assets.xcassets/${d}.appiconset/`);r&&(fs_extra_1.default.ensureDirSync(S),fs_extra_1.default.emptyDirSync(S));const v=[];let x=!1;if(f.forEach(e=>{fs_extra_1.default.existsSync(e.to)&&fs_extra_1.default.removeSync(e.to),fs_extra_1.default.copyFileSync(e.from,e.to),r&&(fs_extra_1.default.copySync(e.from,path_1.default.join(S,e.filename)),"ios-marketing-other"===e.idiom&&(x=!0),v.push({filename:e.filename,size:e.size,scale:e.scale,idiom:e.idiom}))}),r&&fs_extra_1.default.writeJsonSync(path_1.default.join(S,"Contents.json"),{images:v,info:{author:"xcode",version:1}},{spaces:"\t"}),r){const e=path_1.default.join(__dirname,"../../../static/scripts/assetsCar/"),n=path_1.default.join(I,"createAssetsCar");fs_extra_1.default.copySync(e,I);try{await(0,codesign_1.checkXcodeEnv)(s),child_process.execSync(`"${n}" ${d}`,{env:(0,env_1.getProcessEnv)()})}catch(e){s.progress("createAssetsCar failed "+(e.message||""))}const t=path_1.default.join(I,"build/Assets.car"),a=path_1.default.join(i,"Assets.car");fs_extra_1.default.copyFileSync(t,a)}else{const e=path_1.default.join(i,"Assets.car");fs_extra_1.default.removeSync(e)}const b=path_1.default.join(i,"Info.plist"),F=plist.readFileSync(b);if(!F.CFBundleIcons){const e={CFBundlePrimaryIcon:{}};F.CFBundleIcons=e}x&&(F.CFBundleIcons.CFBundleAlternateIcons={OtherAppStoreIcon:{CFBundleIconFiles:[d+"Other"],CFBundleIconName:"OtherAppStoreIcon"}}),F.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconName=d,F.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles=u,F["CFBundleIcons~ipad"]||(F["CFBundleIcons~ipad"]={CFBundlePrimaryIcon:{}}),F["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconName=d,F["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconFiles=c,F.NSAppTransportSecurity={NSAllowsArbitraryLoads:!0},plist.writeFileSync(b,F)}replaceLaunchScreenImage(e,i,n,t,a,s){const o=path_1.default.join(e,"01J-lp-oVM-view-Ze5-6b-2t3.nib");let r=fs_extra_1.default.readFileSync(o).toString("hex");if(!i.endsWith(".png"))return void t.message("error","IOS 启动页图片配置格式错误,必须为 PNG 格式, 错误配置:"+i);const l=this.getMaterialFilePath(a,i),d=n+".png",p="LaunchScreen-"+uuidv4().slice(0,12),u=p+".png",c=path_1.default.join(s,u);fs_extra_1.default.copyFileSync(l,c);const f=Buffer.from(d,"utf-8").toString("hex"),_=Buffer.from(u,"utf-8").toString("hex");return-1!==r.indexOf(f)?(r=r.replace(f,_),console.log("replace storyboard customImage success")):console.log("replace storyboard customImage fail"),fs_extra_1.default.writeFileSync(o,Buffer.from(r,"hex")),p}async updateSplashScreen(e,i,n,t,a="Dark",s){var o,r,l;let d;t.progress("update splashscreen image..."),allowTheme.includes(a)&&(d=path_1.default.join(i,`/Base.lproj/LaunchScreen${a}.storyboardc`)),d&&fs_extra_1.default.existsSync(d)&&fs_extra_1.default.copySync(d,path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc")),allowTheme.forEach(e=>{const n=path_1.default.join(i,`/Base.lproj/LaunchScreen${e}.storyboardc`);fs_extra_1.default.existsSync(n)&&fs_extra_1.default.removeSync(n)});let p=null===(o=null==n?void 0:n.splashscreen)||void 0===o?void 0:o.customImage;if(!p)return;const u=path_1.default.join(i,"Info.plist"),c=plist.readFileSync(u),f=c.UISplashScreenImageName;if(glob_1.default.sync("LaunchScreen-*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).forEach(e=>{const n=path_1.default.join(i,e);fs_extra_1.default.removeSync(n)}),p.startsWith("%")&&(null==p?void 0:p.endsWith("%"))){const n=p.slice(1,-1),a=(null===(l=null===(r=null==s?void 0:s.base)||void 0===r?void 0:r.ios)||void 0===l?void 0:l[n])||"";if(!a)return void t.message("error",`未在国际化配置 base.json 中找到字段 ${n},请检查,启动页国际化配置失败`);p=a,Object.keys(s).forEach(a=>{var o,r;if("base"===a)return;const l=null===(r=null===(o=s[a])||void 0===o?void 0:o.ios)||void 0===r?void 0:r[n];if(l){const n=path_1.default.join(i,`/${a}.lproj/LaunchScreen_${a}.storyboardc`);fs_extra_1.default.ensureDirSync(path_1.default.join(n,"..")),fs_extra_1.default.copySync(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),n);const s=this.replaceLaunchScreenImage(n,this.getMaterialFilePath(e,l),f,t,e,i);t.progress(`update ${a} splashscreen image...`);const o=fs_extra_1.default.readFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),"utf8");let r="";r=s?o.replace("__UISplashScreenImageName__",`UISplashScreenImageName = "${s}";\n`).replace("__UILaunchStoryboardName__",`UILaunchStoryboardName = "LaunchScreen_${a}";\n`):o.replace("__UISplashScreenImageName__","").replace("__UILaunchStoryboardName__",""),fs_extra_1.default.writeFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),r),t.progress(`update ${a} splashscreen image success`)}})}t.progress("update base splashscreen image...");const _=this.replaceLaunchScreenImage(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),this.getMaterialFilePath(e,p),f,t,e,i);t.progress("update base splashscreen image success"),_&&(c.UISplashScreenImageName=_,c.UILaunchStoryboardName="LaunchScreen",plist.writeFileSync(u,c))}genUseExtendedSdk(e,i){const n=Object.assign({},e.useExtendedSdk||{});for(const i in e)if("object"==typeof e[i])for(const t in e[i])if(t.startsWith("useExtendedLib_WeApp")&&!0===e[i][t]){n[t.slice("useExtendedLib_".length)]=!0}return!n.WeAppLBS||n.WeAppOpenFuns||n.WeAppOpenFuns_HasPay||(n.WeAppOpenFuns=!0),"RemoteDebug"===(null==i?void 0:i.debugType)&&(n.WeAppUSB=!0),n}async updateExtendedSdk(e,i,n,t,a,s,o){const r=path_1.default.join(i,"Frameworks");fs_extra_1.default.ensureDirSync(r),o.progress("update extendsdk...");const l=path_1.default.join(n,"WeAppSDK.podspec"),d=fs_extra_1.default.readFileSync(l,"utf-8"),p=this.genUseExtendedSdk(a,s);o.progress("useExtendedSdks: "+JSON.stringify(p));const{mobileapp_info:u={}}=e,c=this.getBundleIdentifier(u);if(p.WeAppOpenFuns&&p.WeAppOpenFuns_HasPay)throw new Error("OpenFuncs SDK 只可勾选使用一个,请按需勾选使用");const f={};for(const e in p){if(!p[e])continue;const i=getDepReg(e),a=d.match(i);if(!(null==a?void 0:a[1])){if("WeAppUSB"===e)continue;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://dev.weixin.qq.com/docs/framework/dev/sdk/difflog.html`)}const s=[];if(a[1].split("\n").forEach(e=>{const i=e.match(/.*'(.*?)',/);if(null==i?void 0:i[1]){const e=i[1].split("/").pop(),a=path_1.default.join(n,"Libs",t,e);if(!fs_extra_1.default.existsSync(a)){if("WeAppUSB.framework"===e)return;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://dev.weixin.qq.com/docs/framework/dev/sdk/difflog.html`)}const o=path_1.default.join(r,e);fs_extra_1.default.copySync(a,o),s.push(path_1.default.basename(e));const l=path_1.default.join(o,"info.plist");if(!fs_extra_1.default.existsSync(l))throw new Error("can not found extendsdk info.plist: "+e);this.changeExtendSDKInfoplistBundleId(l,c,e)}}),s.length){f[s.shift()]=s}}const _=path_1.default.join(i,"DyFrameworks.plist");fs_extra_1.default.existsSync(_)&&fs_extra_1.default.removeSync(_),plist.writeFileSync(_,f)}async updatePrivacyInfo(e,i,n){var t;const a=null===(t=null==i?void 0:i.privacy)||void 0===t?void 0:t.privacyInfo;a&&(a.endsWith("PrivacyInfo.xcprivacy")?fs_extra_1.default.existsSync(a)?(fs_extra_1.default.copySync(a,path_1.default.join(e,"/PrivacyInfo.xcprivacy")),n.progress("隐私清单文件替换成功")):n.message("error","隐私清单文件替换失败,文件不存在,将使用默认文件"):n.message("error","隐私清单文件替换失败,文件名必须为 PrivacyInfo.xcprivacy,将使用默认文件"))}async updatePlugin(e,i,n,t,a,s,o,r){const l={},d={},p=[];if(t["mini-plugin"]&&Array.isArray(t["mini-plugin"].ios)){t["mini-plugin"].ios.forEach(e=>{e.open&&e.pluginId?("string"==typeof e.resourcePath&&e.resourcePath.length>0&&(l[e.pluginId]=e.resourcePath),"object"==typeof e.resourceObjects&&Object.keys(e.resourceObjects).length>0&&(d[e.pluginId]=e.resourceObjects)):p.push(e.pluginId)})}if(p.length>0&&r.message("warn","下列插件未启用,请确认project.miniapp.json中的配置:"+p.join(", ")),!i.length)return;const u=path_1.default.join(e,"Frameworks"),c=path_1.default.join(e,"PlugIns");fs_extra_1.default.ensureDirSync(u),r.progress("update plugin...");const f=this.prepareAppexProfileConfig(i,t,n,a,s,o,t.version,r);if(!f)throw new Error("依赖的多端插件需要配置对应的profile");i.forEach(i=>{const{pluginId:t}=i,a=i.dir,s=t+".framework",o=path_1.default.join(u,s);if(-1!==a.indexOf("local-miniapp-plugin")){const e=fs_extra_1.default.statSync(a),{mtime:i}=e;r.progress(`${t}.framework 正在使用本地版本,修改时间为 ${i}`)}fs_extra_1.default.existsSync(o)&&fs_extra_1.default.removeSync(o);const p=path_1.default.join(a,s);if(fs_extra_1.default.existsSync(p)){fs_extra_1.default.copySync(p,o),this.copyResourcesToMainBundle(p,e),this.copyUserResourcePathIntoPlugins(t,n,l[t],d[t],path_1.default.join(o,"MiniPlugin.bundle"),r);fs_extra_1.default.readdirSync(a).forEach(i=>{if(i.endsWith(".appex")){const s=path_1.default.parse(i).name,o=f[s],p=path_1.default.join(c,i);if(!o||!0!==o.enable)return;r.progress(`${t} 插件使用 appex 中 : ${i}`),fs_extra_1.default.existsSync(p)&&fs_extra_1.default.removeSync(p),fs_extra_1.default.ensureDirSync(p);const u=path_1.default.join(a,i);fs_extra_1.default.copySync(u,p),(null==o?void 0:o.profilePath)&&fs_extra_1.default.copySync(o.profilePath,path_1.default.join(p,"embedded.mobileprovision")),this.copyResourcesToMainBundle(u,e),this.copyUserResourcePathIntoPlugins(t,n,l[t],d[t],path_1.default.join(p,"MiniPlugin.bundle"),r)}else if(i.endsWith("framework")&&i!==s){const e=path_1.default.join(u,i),n=path_1.default.join(a,i);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.copySync(n,e)}})}else fs_extra_1.default.copySync(a,o),this.copyResourcesToMainBundle(a,e),this.copyUserResourcePathIntoPlugins(t,n,l[t],d[t],path_1.default.join(o,"MiniPlugin.bundle"),r)})}copyUserResourcePathIntoPlugins(e,i,n,t,a,s){const o=a;if(n){const t=path_1.default.basename(n),a=this.getMaterialFilePath(i,n);if(a){s.progress(`${e}.framework 正在拷贝配置的资源:${n}`);const i=fs_extra_1.default.lstatSync(a);fs_extra_1.default.ensureDirSync(o),i.isDirectory()?fs_extra_1.default.copySync(a,o):i.isFile()&&fs_extra_1.default.copyFileSync(a,path_1.default.join(o,t))}}if(t){s.progress(e+".framework 正在写入配置的资源"),fs_extra_1.default.ensureDirSync(o);for(const e in t){const i=t[e],n=path_1.default.join(o,e);fs_extra_1.default.ensureDirSync(o),fs_extra_1.default.ensureFileSync(n),fs_extra_1.default.writeFileSync(n,i)}}}copyResourcesToMainBundle(e,i){const n=path_1.default.join(e,"MiniPlugin.bundle"),t=path_1.default.join(n,"PluginConfig.plist");if(fs_extra_1.default.existsSync(t)){const e=plist.readFileSync(t).CopyResourcesToMainBundle;(null==e?void 0:e.length)&&e.forEach(e=>{const t=path_1.default.join(n,e);fs_extra_1.default.existsSync(t)&&fs_extra_1.default.copySync(t,path_1.default.join(i,e))})}}prepareAppexProfileConfig(e,i,n,t,a,s,o,r){if(!t)return void r.message("doing","miniappCacheDirPath is missing");let l=!1;const d={};if(i["mini-plugin"]&&Array.isArray(i["mini-plugin"].ios)){i["mini-plugin"].ios.forEach(e=>{if(e.open&&e.pluginId&&"object"==typeof e.appexProfiles)for(const i in e.appexProfiles){r.message("doing",`检查插件 ${e.pluginId} ${i} appex 配置中 ...`);const t=e.appexProfiles[i];if(!0===t.enable){const s=`${e.pluginId}_${i}`;d[s]={enable:!0};let o=t.profilePath;if(a&&(o=t.distributeProfilePath),t.bundleID&&o){const a=path_1.default.join(n,o);fs_extra_1.default.existsSync(a)?(d[s].bundleID=t.bundleID,d[s].profilePath=path_1.default.join(n,o)):(l=!0,r.message("error",`${e.pluginId} 中 ${i} 的 profilePath 无法找到对应的文件:${a}(需要在小程序项目路径下,填入相对于项目根目录的路径)`))}else l=!0,r.message("error",`${e.pluginId}中${i} 是 无效的appexProfiles配置。需要配置 bundleID,profilePath,distributeProfilePath。profile 文件需要放置在小程序项目内,然后配置相对于小程序项目根目录的相对路径。分发证书构建的情况下, 一定需要配置distributeProfilePath。查看文档了解详情。`)}}})}if(e.forEach(e=>{fs_extra_1.default.readdirSync(e.dir).forEach(i=>{if(i.endsWith(".appex")){const n=path_1.default.parse(i).name,t=d[n];if(t&&!0===t.enable)if(t.bundleID&&t.profilePath){if(t.bundleID&&t.profilePath){const n=path_1.default.join(e.dir,i,"info.plist"),a=t.bundleID;this.changeInfoplistBundleId(n,a),this.changeInfoplistBundleVersion(n,s,o),r.message("doing",`${e.pluginId} ${i} ${a} ${n} 处理 appex bundle ID 中`)}}else l=!0,r.message("error",`${e.pluginId} 的 多端插件包含了${n.slice(e.pluginId.length+1)} 的 appex。开发者需要在project.miniapp.json 中 mini-plugin 配置下对应合理的 profile 文件。查看文档了解详情。`)}})}),l)return!1;if(!(0,lodash_1.isEmpty)(d)){const e=path_1.default.join(t,APPEX_PROFILES_MAPS_FILE);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.ensureFileSync(e);const i={};for(const e in d)i[e]={bundleID:d[e].bundleID,profilePath:d[e].profilePath};fs_extra_1.default.writeFileSync(e,JSON.stringify(i));const n=path_1.default.join(t,APPEX_PROFILES_MAPS_FOR_SHELL_FILE);fs_extra_1.default.existsSync(n)&&fs_extra_1.default.removeSync(n),fs_extra_1.default.ensureFileSync(n);const a=Object.keys(d).map(e=>{const i=d[e];return`pluginAppexName:${e};_;_;bundleID:${i.bundleID};_;_;profile:${i.profilePath}\n\n`}).join("");fs_extra_1.default.writeFileSync(n,a)}return d}changeExtendSDKInfoplistBundleId(e,i,n){const t=`${i}.${path_1.default.parse(n).name.replace(/_/g,"")}`;return this.changeInfoplistBundleId(e,t)}changeInfoplistBundleId(e,i){const n=plist.readFileSync(e);return n.CFBundleIdentifier=i,plist.writeFileSync(e,n),n.CFBundleIdentifier}changeInfoplistBundleVersion(e,i,n){const t=plist.readFileSync(e);return t.CFBundleVersion=i,t.CFBundleShortVersionString=n,plist.writeFileSync(e,t),t.CFBundleIdentifier}async getEntitlements(e,i,n,t){const{mobileapp_info:a={}}=e;let s=a.ios_universal_link||a.debug_ios_universal_link;if((s.startsWith("https://")||s.startsWith("http://"))&&(s=s.replace(/^http(s)?:\/\//g,"applinks:")),Array.isArray(n.__customAssociatedDomains)){const e=n.__customAssociatedDomains.filter(e=>"string"==typeof e&&e.length>0);if(e.length>0){e.splice(0,0,s);return{"com.apple.developer.associated-domains":e.join("_$_ULinK_$_")}}}return{"com.apple.developer.associated-domains":s}}useTpush(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingTpush)(e)}async buildCloud(e,i){const{projectPath:n,demoIpaPath:t,sdkPath:a,arch:s="arm64",bindingInfo:o,certificateInfo:r,output:l,miniappCacheDirPath:d,pluginDirList:p,inLandun:u,theme:c,i18nInfo:f,debugInfo:_,CILocalBuild:h}=e,g=this.generateTempDemoIpaPath(t),{selfCertificate:m={}}=r,y=(null==m?void 0:m.isPublish)||!1,I=(0,miniappJson_1.tryGetIOSMiniappJson)(n),S=this.useTpush(I);if((0,lodash_1.isEmpty)(I))throw new Error("获取project.miniapp.json失败");if(errorIOSSdkVersions.includes(I.sdkVersion))throw new Error("当前 mini-ios.sdkVersion 存在缺陷,请参考更新日志进行修改");let v=o;if(r.signType===miniapp_builder_1.miniappSinTypes.appleId.type){const{mobileapp_info:e={}}=v;v=Object.assign(Object.assign({},v),{mobileapp_info:Object.assign(Object.assign({},e),{bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID,debug_ios_bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID})})}const x=await this.updateIOSInfoPlistInfo(n,v,g,I,i,f);await this.updateIOSAppConfigPlistInfo(n,v,g,I,a,!1,i,c,f),await this.updateIOSAppexInfoPlistInfo(v,g,I,x,i),await this.updateIOSIcons(n,g,d,I,y,i),await this.updateSplashScreen(n,g,I,i,c,f),await this.updateExtendedSdk(v,g,a,s,I,_,i),await this.updatePlugin(g,p,n,I,d,y,x,i),await this.updatePrivacyInfo(g,I,i);const b=await this.getEntitlements(v,g,I,i),{mobileapp_info:F={}}=v;let P;P=r.signType===miniapp_builder_1.miniappSinTypes.appleId.type?miniapp_builder_1.DEFAULT_BUNDLE_ID:F.ios_flag&&F.bundle_id||F.debug_ios_bundle_id;const B={bundleId:P,output:l,entitlements:b};if(I.buildCloud&&(I.buildCloud.certificate&&"string"==typeof I.buildCloud.certificate&&(B.certificate=I.buildCloud.certificate),I.buildCloud.profile&&"string"==typeof I.buildCloud.profile&&(B.profile=path_1.default.join(n,I.buildCloud.profile)),S&&I.buildCloud.tpnsProfile&&"string"==typeof I.buildCloud.tpnsProfile&&(B.tpnsProfile=path_1.default.join(n,I.buildCloud.tpnsProfile))),h&&(B.profile=m.profilePath,B.certificate=m.certificateName),m.isPublish||h){const e=await(0,codesign_1.codesignAndExport)(n,g,d||"",B,i,S,!0===u);if(!0!==e.success)throw new Error("Build ipa failed:"+(e.errMsg||"codesignAndExport failed"))}return{projectPath:n,demoIpaPath:g,opts:B,iosMiniappJson:I,isPublish:y}}async writeI18NInfoFile(e,i,n){Object.keys(i).forEach(t=>{if("base"===t)return;let a="";Object.keys(n).forEach(e=>{var s,o,r,l;"UISplashScreenImageName"!==e?"UILaunchStoryboardName"!==e?(null===(o=null===(s=i[t])||void 0===s?void 0:s.ios)||void 0===o?void 0:o[n[e]])&&(a+=`${e} = "${null===(l=null===(r=i[t])||void 0===r?void 0:r.ios)||void 0===l?void 0:l[n[e]]}";\n`):a+="__UILaunchStoryboardName__\n":a+="__UISplashScreenImageName__\n"}),a&&(fs_extra_1.default.ensureDirSync(path_1.default.join(e,t+".lproj")),fs_extra_1.default.writeFileSync(path_1.default.join(e,t+".lproj/InfoPlist.strings"),a))})}getMaterialFilePath(e,i){if(!i)return"";let n=i;if(path_1.default.isAbsolute(i)||(n=path_1.default.join(e,i)),fs_extra_1.default.existsSync(n))return n;const t=(0,tools_1.generateMD5)(i),a=path_1.default.basename(i),s=path_1.default.join(e,exports.remoteBuildProjectMaterialAbsoluteCacheDir,`${t}_${a}`);return fs_extra_1.default.existsSync(s)?s:""}}exports.default=new buildCloudManager;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.remoteBuildProjectMaterialAbsoluteCacheDir=void 0;const tslib_1=require("tslib"),child_process=tslib_1.__importStar(require("child_process")),path_1=tslib_1.__importDefault(require("path")),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),glob_1=tslib_1.__importDefault(require("glob")),env_1=require("../../../utils/env"),miniapp_builder_1=require("../../../utils/miniapp-builder"),codesign_1=require("../../../utils/codesign"),miniappJson_1=require("../../../utils/miniappJson"),lodash_1=require("lodash"),tools_1=require("../../../utils/tools"),uuidv4=require("uuid/v4"),sizeOf=require("image-size"),plist=require("simple-plist"),errorIOSSdkVersions=["1.0.19"],APPEX_PROFILES_MAPS_FILE="__appexProfilesCacheDir__/profilesMap.json",APPEX_PROFILES_MAPS_FOR_SHELL_FILE="__appexProfilesCacheDir__/profilesMapForShell.txt",defaultIconDirPath=path_1.default.join(__dirname,"../../../static/images/"),getDepReg=e=>new RegExp(`s.subspec '${e}'.*\n(?:.*\n)*?(?:.*sp.vendored_frameworks = \\[\n)((?:.*'.*?'.*\n)*?)(?:.*\\]\n)`,"m"),allowTheme=["Light","LightSpecial","Dark","DarkSpecial","Default"];exports.remoteBuildProjectMaterialAbsoluteCacheDir="__absoluteFile";const iconInfoMap={appStore1024:{size:[1024,1024],scale:1,idiom:"ios-marketing",required:!0},appStore1024Other:{size:[1024,1024],scale:1,idiom:"ios-marketing-other"},mainIcon120:{size:[60,60],scale:2,idiom:"iphone",required:!0},mainIcon180:{size:[60,60],scale:3,idiom:"iphone"},spotlightIcon80:{size:[40,40],scale:2,idiom:"iphone"},spotlightIcon120:{size:[40,40],scale:3,idiom:"iphone"},settingsIcon58:{size:[29,29],scale:2,idiom:"iphone"},settingsIcon87:{size:[29,29],scale:3,idiom:"iphone"},notificationIcon40:{size:[20,20],scale:2,idiom:"iphone"},notificationIcon60:{size:[20,20],scale:3,idiom:"iphone"},ipadMainIcon152:{size:[76,76],scale:2,idiom:"ipad"},ipadMainIcon167:{size:[83.5,83.5],scale:2,idiom:"ipad"},ipadSpotlightIcon40:{size:[40,40],scale:1,idiom:"ipad"},ipadSpotlightIcon80:{size:[40,40],scale:2,idiom:"ipad"},ipadSettingsIcon29:{size:[29,29],scale:1,idiom:"ipad"},ipadSpotlightIcon58:{size:[29,29],scale:2,idiom:"ipad"},ipadNotificationIcon20:{size:[20,20],scale:1,idiom:"ipad"},ipadNotificationIcon40:{size:[20,20],scale:2,idiom:"ipad"}};class buildCloudManager{generateTempDemoIpaPath(e){const i=path_1.default.join(e,"../.."),t=path_1.default.basename(i),n=path_1.default.dirname(i),a=path_1.default.join(n,t+"-operateDir");fs_extra_1.default.existsSync(a)&&fs_extra_1.default.removeSync(a),fs_extra_1.default.ensureDirSync(a);const s=path_1.default.join(a,"Payload/demo.app");return fs_extra_1.default.copySync(e,s),s}generateInfoPlistCFBundleURLTypesItem(e){const i={};return e.CFBundleURLName&&(i.CFBundleURLName=e.CFBundleURLName),e.CFBundleURLSchemes&&(i.CFBundleURLSchemes=[e.CFBundleURLSchemes]),e.CFBundleTypeRole&&(i.CFBundleTypeRole=e.CFBundleTypeRole),i}updatePrivacyBackgroundImage(e,i,t,n,a){t.message("doing","updatePrivacyBackgroundImage "+n);if(fs_extra_1.default.readdirSync(i).forEach(e=>{"privacy_"+n===path_1.default.basename(e,path_1.default.extname(e))&&fs_extra_1.default.removeSync(path_1.default.join(i,e))}),!a)return;path_1.default.isAbsolute(a)||(a=path_1.default.join(e,a)),a=this.getMaterialFilePath(e,a);const s=path_1.default.extname(a),o=path_1.default.join(i,`privacy_${n}${s}`);try{fs_extra_1.default.copyFileSync(a,o)}catch(e){throw t.message("error",`copy privacy image failed: ${n}, ${a} to ${o}`),e}}async updateIOSInfoPlistInfo(e,i,t,n,a,s){var o,r,l,p,d,u,c,f,_,h,g;a.progress("update app base info...");const{mobileapp_info:y={}}=i,m=y.mobileapp_id,S=path_1.default.join(t,"Info.plist"),I={},x=(e,i)=>{var t,n;if((null==i?void 0:i.startsWith("%"))&&(null==i?void 0:i.endsWith("%"))){const o=i.slice(1,-1);I[e]=o;const r=(null===(n=null===(t=null==s?void 0:s.base)||void 0===t?void 0:t.ios)||void 0===n?void 0:n[o])||"";return r||a.message("error",`未在国际化配置 base.json 中找到字段 ${o},请检查`),r}return i};x("UISplashScreenImageName",null===(o=null==n?void 0:n.splashscreen)||void 0===o?void 0:o.customImage),x("UILaunchStoryboardName",null===(r=null==n?void 0:n.splashscreen)||void 0===r?void 0:r.customImage);const v=plist.readFileSync(S);if("object"==typeof n.customInfoPlist&&!Array.isArray(n.customInfoPlist)){a.progress("initiating user custom info.plist config");const e=n.customInfoPlist;for(const i in e)v[i]=e[i]}if(v.CFBundleName=x("CFBundleName",n.name),v.CFBundleDisplayName=x("CFBundleDisplayName",n.name),v.CFBundleShortVersionString=n.version,"number"==typeof n.versionCode?v.CFBundleVersion=parseInt(n.versionCode.toString(),10).toString():v.CFBundleVersion=(parseInt(v.CFBundleVersion,10)+1).toString(),v.CFBundleIdentifier=this.getBundleIdentifier(y),Array.isArray(null==n?void 0:n.openMimeTypes)&&this.validateCFBundleDocumentTypes(n.openMimeTypes,a)&&(v.CFBundleDocumentTypes=n.openMimeTypes,a.message("doing","openMimeTypes 应用成功")),Array.isArray(v.CFBundleURLTypes)||(v.CFBundleURLTypes=[]),(null===(p=null===(l=v.CFBundleURLTypes)||void 0===l?void 0:l[0])||void 0===p?void 0:p.CFBundleURLSchemes)&&(v.CFBundleURLTypes[0].CFBundleURLSchemes=[m]),v.CFBundleURLTypes[0]&&(v.CFBundleURLTypes=[v.CFBundleURLTypes[0]]),Object.keys(miniappJson_1.iosPrivacyDescObj).forEach(e=>{var i,t;(null===(i=null==n?void 0:n.privateDescriptions)||void 0===i?void 0:i[e])?v[e]=x(e,null===(t=n.privateDescriptions)||void 0===t?void 0:t[e]):delete v[e]}),!0===(null===(d=null==n?void 0:n.infoPlist)||void 0===d?void 0:d.DisableAppUsesNonExemptEncryption)?v.ITSAppUsesNonExemptEncryption=!1:delete v.ITSAppUsesNonExemptEncryption,v.UIBackgroundModes=[],!0===(null===(u=null==n?void 0:n.infoPlist)||void 0===u?void 0:u.AudioInBackgroundMode)&&v.UIBackgroundModes.push("audio"),!0===(null===(c=null==n?void 0:n.infoPlist)||void 0===c?void 0:c.LocationInBackgroundMode)&&v.UIBackgroundModes.push("location"),!0===(null===(f=null==n?void 0:n.infoPlist)||void 0===f?void 0:f.requiresFullScreen)?v.UIRequiresFullScreen=!0:delete v.UIRequiresFullScreen,"object"==typeof(null===(_=null==n?void 0:n.infoPlist)||void 0===_?void 0:_.CFBundleURLTypes)){const e=this.generateInfoPlistCFBundleURLTypesItem(n.infoPlist.CFBundleURLTypes);v.CFBundleURLTypes.push(e);const{additionalCFBundleURLTypes:i}=n.infoPlist.CFBundleURLTypes;Array.isArray(i)&&i.forEach(e=>{if("object"==typeof e){const i=this.generateInfoPlistCFBundleURLTypesItem(e);v.CFBundleURLTypes.push(i)}})}if(null===(h=null==n?void 0:n.useExtendedSdk)||void 0===h?void 0:h.WeAppGoogleLogin){if(!(null==n?void 0:n.googleLoginClientID)||!(null==n?void 0:n.googleLoginBundleUrlType))throw new Error("勾选了 Google Login 拓展模块但未填写 googleLoginClientID 或 googleLoginBundleUrlType 将导致拓展模块无法使用");v.GIDClientID=n.googleLoginClientID,Array.isArray(v.CFBundleURLTypes)?v.CFBundleURLTypes.push({CFBundleURLSchemes:[n.googleLoginBundleUrlType]}):v.CFBundleURLTypes=[{CFBundleURLSchemes:[n.googleLoginBundleUrlType]}]}if(!0===n.enableIpad&&((0,miniappJson_1.iOSAppJsonIsUsingIPadResizable)(e)?(v["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],a.progress("ipad is support Landscape")):(v["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown"],a.progress("ipad is not support Landscape"))),null===(g=n.infoPlist)||void 0===g?void 0:g.LSApplicationQueriesSchemes){const e=n.infoPlist.LSApplicationQueriesSchemes.split(",");e.length&&v.LSApplicationQueriesSchemes.push(...e.filter(e=>e))}try{plist.writeFileSync(S,v)}catch(e){throw new Error("write info.plist failed!!"+e.messenge)}return await this.writeI18NInfoFile(t,s,I),v.CFBundleVersion}getBundleIdentifier(e){return e.ios_flag&&e.bundle_id||e.debug_ios_bundle_id}validateCFBundleDocumentTypes(e,i){const t=["Owner","Default"," Alternate","None"],n=["Editor","Viewer"," Shell","None"],a=new Set;for(const s of e){if(a.has(s.CFBundleTypeName))return i.message("error","openMimeTypes 应用失败,存在重复定义的 CFBundleTypeName: "+s.CFBundleTypeName),!1;if(a.add(s.CFBundleTypeName),!t.includes(s.LSHandlerRank))return i.message("error","openMimeTypes 应用失败,存在不合法的 LSHandlerRank: "+s.LSHandlerRank),!1;if(!n.includes(s.CFBundleTypeRole))return i.message("error","openMimeTypes 应用失败,存在不合法的 CFBundleTypeRole: "+s.CFBundleTypeRole),!1;if(!Array.isArray(s.LSItemContentTypes))return i.message("error","openMimeTypes 应用失败,LSItemContentTypes 类型不合法"),!1}return!0}useGDT(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingGDT)(e)}async updateIOSAppConfigPlistInfo(e,i,t,n,a,s,o,r="Dark",l){var p,d,u,c,f,_;o.progress("update app module info...");const{module_info:h={},cpa_info:g={},cpa_package_info:y={enable_remove_watermark:!1}}=i;if(!g.sdk_key||!g.sdk_key_secret)throw new Error("sdkKey and sdkSecret not found");const m=path_1.default.join(t,"MiniApp.bundle"),S=path_1.default.join(m,"AppConfig.plist"),I=plist.readFileSync(S);y.enable_remove_watermark?I.enableRemoveWatermark=!0:I.splashscreenTheme=r,I.miniModuleId=h.module_id,I.sdkKey=g.sdk_key,I.sdkSecret=g.sdk_key_secret;const{privacy:x={}}=n;I.privacy||(I.privacy={}),I.privacy.enable=!!x.enable,I.privacy.enableViewOnly=!!x.enableViewOnly;const v=path_1.default.posix.join(m,"configs/privacy.json"),{contentViewImage:b,cancelButtonImage:F,confirmButtonImage:P,template:j}=x;if(x.enable){let i=j||"";if(fs_extra_1.default.ensureDirSync(path_1.default.posix.join(m,"configs")),i.startsWith("%")&&i.endsWith("%")){const t=j.slice(1,-1);i=(null===(d=null===(p=null==l?void 0:l.base)||void 0===p?void 0:p.ios)||void 0===d?void 0:d[t])||"",i||o.message("error",`未在国际化配置 base.json 中找到字段 ${t},请检查`),Object.keys(l).forEach(i=>{var n,a;if("base"===i)return;let s=null===(a=null===(n=l[i])||void 0===n?void 0:n.ios)||void 0===a?void 0:a[t];if(s){s=this.getMaterialFilePath(e,s);const t=`configs/privacy-${i}.json`,n=path_1.default.posix.join(m,t);fs_extra_1.default.existsSync(s)?fs_extra_1.default.copyFileSync(s,n):o.message("error",`未找到隐私协议在国际化配置 ${i}.json 中配置的文件 ${s},请检查`)}})}i?(i=this.getMaterialFilePath(e,i),fs_extra_1.default.existsSync(i)?(fs_extra_1.default.copyFileSync(i,v),I.privacy.template="configs/privacy.json"):(o.message("error",`未找到隐私协议中配置的文件 ${i},请检查`),I.privacy.template="configs/defaultPrivacy.json")):I.privacy.template="configs/defaultPrivacy.json",!0===x.enableNativePlugin&&"string"==typeof x.nativePluginId&&x.nativePluginId.length>2&&(I.privacy.plugin={pluginId:x.nativePluginId,enable:!0})}else I.privacy.template="",fs_extra_1.default.removeSync(v);this.updatePrivacyBackgroundImage(e,t,o,"contentViewImage",b),this.updatePrivacyBackgroundImage(e,t,o,"confirmButtonImage",P),this.updatePrivacyBackgroundImage(e,t,o,"cancelButtonImage",F);const{appMenuEnable:B=!0}=n;I.appMenuEnable=B;const{enableVConsole:C="undefined"}=n;I.enableVConsole=C;const{tpush:L}=n;let w=!1;if("object"==typeof L){const e=path_1.default.posix.join(t,"PlugIns/TPNSService.appex"),i=path_1.default.posix.join(e,"AppConfig.plist");if(this.useTpush(n)){I.TPNSAccessID=L.accessID,I.TPNSAccessKey=L.accessKey,L.clusterDomainName?I.clusterDomainName=L.clusterDomainName:delete I.clusterDomainName;const t=s?"x86_64":"arm64",n=path_1.default.join(a,`appex/${t}/TPNSService.appex`);if(!fs_extra_1.default.existsSync(n))throw new Error("can not found extendsdk: "+n);try{fs_extra_1.default.copySync(n,e),plist.writeFileSync(i,I),w=!0}catch(e){throw new Error("copy TPNSService.appex to app failed: "+e)}}}if(!w)try{const e=path_1.default.posix.join(t,"PlugIns");fs_extra_1.default.existsSync(e)?(fs_extra_1.default.removeSync(e),o.progress("removed PlugIns folder...")):o.progress("no PlugIns folder...")}catch(e){throw new Error("remove TPNSService.appex from app failed: "+e)}if(null===(u=n.useExtendedSdk)||void 0===u?void 0:u.WeAppLBS){if(!n.qmapAPIKey)throw new Error("You need to provide the Tencent Location Service API Key when using LBS SDK.");I.qmapAPIKey=n.qmapAPIKey}const{gdt:A}=n,D=this.useGDT(n);if(I.GDTAd=D?{appid:A.appid,enable:!0,SplashAd:{placementId:A.splashAd_placementId,fetchDelay:A.splashAd_fetchDelay||3,defaultEnable:null===(c=A.splashAd_defaultEnable)||void 0===c||c}}:{appid:"",enable:!1,SplashAd:{placementId:"",fetchDelay:3}},n["mini-plugin"]&&Array.isArray(n["mini-plugin"].ios)){const e=n["mini-plugin"].ios,i=e.filter(e=>!!(e.open&&e.pluginId&&e.loadWhenStart)).map(e=>e.pluginId),t=e.map(e=>e.open?{pluginId:e.pluginId,version:e.isFromLocal?"dev":e.pluginVersion}:void 0).filter(e=>e);I.plugins={loadWhenStart:i,pluginInfoList:t}}const{enableDebugLog:E=!1}=n;I.enableDebugLog=E;const{debugLogSizeLimit:$=10}=n;isNaN(Number($))?o.message("error",`ios debugLogSizeLimit ${$} is NaN`):I.debugLogSizeLimit=Number($);const{enableOpenUrlNavigate:U=!1}=n;I.enableOpenUrlNavigate=U;const T=path_1.default.posix.join(m,"configs/locales");if(fs_extra_1.default.ensureDirSync(T),null===(_=null===(f=null==l?void 0:l.base)||void 0===f?void 0:f.ios)||void 0===_?void 0:_.LOCALES){const i=this.getMaterialFilePath(e,l.base.ios.LOCALES);fs_extra_1.default.existsSync(i)?(fs_extra_1.default.copyFileSync(i,path_1.default.posix.join(T,"common-base.json")),o.progress("复制基础语言 locales 配置成功")):o.message("error","未找到基础语言 locales 配置文件: "+i)}Object.keys(l).forEach(i=>{var t,n;if("base"===i)return;const a=null===(n=null===(t=l[i])||void 0===t?void 0:t.ios)||void 0===n?void 0:n.LOCALES;if(a){const t=this.getMaterialFilePath(e,a);fs_extra_1.default.existsSync(t)?(fs_extra_1.default.copyFileSync(t,path_1.default.posix.join(T,`common-${i}.json`)),o.progress(`复制 ${i} 语言 locales 配置成功`)):o.message("error",`未找到 ${i} 语言 locales 配置文件: ${t}`)}}),plist.writeFileSync(S,I)}async updateIOSAppexInfoPlistInfo(e,i,t,n,a){if(this.useTpush(t)){a.progress("update appex for notification base info...");const{mobileapp_info:s={}}=e,o=path_1.default.join(i,"PlugIns/TPNSService.appex"),r=path_1.default.join(o,"Info.plist"),l=plist.readFileSync(r);l.CFBundleShortVersionString=t.version,a.progress("update appex for CFBundleVersion: "+n),l.CFBundleVersion=n;const p=s.ios_flag&&s.bundle_id||s.debug_ios_bundle_id;l.CFBundleIdentifier=t.tpush.serviceBundleId||p+".service",a.progress("update appex bundle identifier for infoPlist : "+l.CFBundleIdentifier),plist.writeFileSync(r,l)}else a.progress("not using tpush...")}updateBundleIcons(e,i,t,n,a){const s=[],o=[],r=[];for(const l in t){if(!t[l])continue;const p=this.getMaterialFilePath(e,t[l]);if(!p)return void a.message("error","getMatrialFailed: "+t[l]);const d=iconInfoMap[l];try{const e=sizeOf(p),i=d.size[0]*d.scale,n=d.size[1]*d.scale;if(e.width!==i||e.height!==n){a.progress(`check ${l} size failed, require [${i}, ${n}] but [${e.width}, ${e.height}] ingore ${t[l]} `);continue}}catch(e){a.progress(`get ${l} info failed, ingore ${t[l]}(e: ${e.message})`);continue}const u=path_1.default.extname(p),c=1===d.scale?"":`@${d.scale}x`,f=`${d.size[0]}x${d.size[1]}`,_=l.startsWith("ipad"),h="appStore1024"===l||"appStore1024Other"===l,g="appStore1024Other"===l?n+"Other":n,y=path_1.default.join(i,`${g}${f}${c}${_?"~ipad":""}${u}`),m={from:p,to:y,filename:path_1.default.basename(y),size:f,scale:d.scale+"x",idiom:d.idiom,key:l};s.push(m),h||(_?r.includes(`${g}${f}`)||r.push(`${g}${f}${c}`):o.includes(`${g}${f}`)||o.push(`${g}${f}${c}`))}return{iphoneBundleIconFiles:o,ipadBundleIconFiles:r,addFiles:s}}async updateIOSIcons(e,i,t,n,a,s,o=!1,r=""){s.progress("update app icons...");const{icons:l={}}=n,p=(o||a)&&!!t;s.progress("genAssetCar: "+p);const d=glob_1.default.sync("AppIcon*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).map(e=>path_1.default.join(i,e)),u="AppIcon-"+uuidv4().slice(0,8),c=this.updateBundleIcons(e,i,l,u,s);if(!c)throw new Error("updateBundleIcons failed");const{iphoneBundleIconFiles:f=[],ipadBundleIconFiles:_=[],addFiles:h=[]}=c,g={};for(const e in iconInfoMap){if(!iconInfoMap[e].required||l[e])continue;const i=iconInfoMap[e].size[0]*iconInfoMap[e].scale,t=iconInfoMap[e].size[1]*iconInfoMap[e].scale;if(g[e]=path_1.default.join(defaultIconDirPath,`donut-icon${i}x${t}.png`),s.progress(`using default app icons when ${e} is not config...`),!fs_extra_1.default.existsSync(g[e]))throw new Error(`required ${e} but not default or set`)}const y=this.updateBundleIcons(e,i,g,u,s);if(!y)throw new Error("updateBundleIcons WithDefaultIcon failed");const{iphoneBundleIconFiles:m,ipadBundleIconFiles:S,addFiles:I}=y;if(f.push(...m),_.push(...S),h.push(...I),!f.length&&!_.length)return;d.forEach(e=>{fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e)});const x=path_1.default.join(t,"__assetCarOperateDir/assetsCar/"),v=path_1.default.join(x,`Assets.xcassets/${u}.appiconset/`);p&&(fs_extra_1.default.ensureDirSync(v),fs_extra_1.default.emptyDirSync(v));const b=[];let F=!1;if(h.forEach(e=>{fs_extra_1.default.existsSync(e.to)&&fs_extra_1.default.removeSync(e.to),fs_extra_1.default.copyFileSync(e.from,e.to),p&&(fs_extra_1.default.copySync(e.from,path_1.default.join(v,e.filename)),"ios-marketing-other"===e.idiom&&(F=!0),b.push({filename:e.filename,size:e.size,scale:e.scale,idiom:e.idiom}))}),p&&fs_extra_1.default.writeJsonSync(path_1.default.join(v,"Contents.json"),{images:b,info:{author:"xcode",version:1}},{spaces:"\t"}),p){const e=path_1.default.join(__dirname,"../../../static/scripts/assetsCar/"),t=path_1.default.join(x,"createAssetsCar");fs_extra_1.default.copySync(e,x);try{await(0,codesign_1.checkXcodeEnv)(s),child_process.execSync(`"${t}" ${u}`,{env:(0,env_1.getProcessEnv)()})}catch(e){throw new Error("createAssetsCar failed "+(e.message||""))}const n=path_1.default.join(x,"build/Assets.car"),a=path_1.default.join(i,"Assets.car");fs_extra_1.default.copyFileSync(n,a)}else if(r&&fs_extra_1.default.existsSync(r))s.message("success","命中缓存,正在使用缓存的 AssetCar"),fs_extra_1.default.copyFileSync(r,path_1.default.join(i,"Assets.car"));else{const e=path_1.default.join(i,"Assets.car");fs_extra_1.default.removeSync(e),s.message("warn","更新 App 图标可能不生效,可使用远程构建验证图标设置;工具将会缓存图标构建结果")}const P=path_1.default.join(i,"Info.plist"),j=plist.readFileSync(P);if(!j.CFBundleIcons){const e={CFBundlePrimaryIcon:{}};j.CFBundleIcons=e}F&&(j.CFBundleIcons.CFBundleAlternateIcons={OtherAppStoreIcon:{CFBundleIconFiles:[u+"Other"],CFBundleIconName:"OtherAppStoreIcon"}}),j.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconName=u,j.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles=f,j["CFBundleIcons~ipad"]||(j["CFBundleIcons~ipad"]={CFBundlePrimaryIcon:{}}),j["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconName=u,j["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconFiles=_,j.NSAppTransportSecurity={NSAllowsArbitraryLoads:!0},plist.writeFileSync(P,j)}replaceLaunchScreenImage(e,i,t,n,a,s){const o=path_1.default.join(e,"01J-lp-oVM-view-Ze5-6b-2t3.nib");let r=fs_extra_1.default.readFileSync(o).toString("hex");if(!i.endsWith(".png"))return void n.message("error","IOS 启动页图片配置格式错误,必须为 PNG 格式, 错误配置:"+i);const l=this.getMaterialFilePath(a,i),p=t+".png",d="LaunchScreen-"+uuidv4().slice(0,12),u=d+".png",c=path_1.default.join(s,u);fs_extra_1.default.copyFileSync(l,c);const f=Buffer.from(p,"utf-8").toString("hex"),_=Buffer.from(u,"utf-8").toString("hex");return-1!==r.indexOf(f)?(r=r.replace(f,_),console.log("replace storyboard customImage success")):console.log("replace storyboard customImage fail"),fs_extra_1.default.writeFileSync(o,Buffer.from(r,"hex")),d}async updateSplashScreen(e,i,t,n,a="Dark",s){var o,r,l;let p;n.progress("update splashscreen image..."),allowTheme.includes(a)&&(p=path_1.default.join(i,`/Base.lproj/LaunchScreen${a}.storyboardc`)),p&&fs_extra_1.default.existsSync(p)&&fs_extra_1.default.copySync(p,path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc")),allowTheme.forEach(e=>{const t=path_1.default.join(i,`/Base.lproj/LaunchScreen${e}.storyboardc`);fs_extra_1.default.existsSync(t)&&fs_extra_1.default.removeSync(t)});let d=null===(o=null==t?void 0:t.splashscreen)||void 0===o?void 0:o.customImage;if(!d)return;const u=path_1.default.join(i,"Info.plist"),c=plist.readFileSync(u),f=c.UISplashScreenImageName;if(glob_1.default.sync("LaunchScreen-*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).forEach(e=>{const t=path_1.default.join(i,e);fs_extra_1.default.removeSync(t)}),d.startsWith("%")&&(null==d?void 0:d.endsWith("%"))){const t=d.slice(1,-1),a=(null===(l=null===(r=null==s?void 0:s.base)||void 0===r?void 0:r.ios)||void 0===l?void 0:l[t])||"";if(!a)return void n.message("error",`未在国际化配置 base.json 中找到字段 ${t},请检查,启动页国际化配置失败`);d=a,Object.keys(s).forEach(a=>{var o,r;if("base"===a)return;const l=null===(r=null===(o=s[a])||void 0===o?void 0:o.ios)||void 0===r?void 0:r[t];if(l){const t=path_1.default.join(i,`/${a}.lproj/LaunchScreen_${a}.storyboardc`);fs_extra_1.default.ensureDirSync(path_1.default.join(t,"..")),fs_extra_1.default.copySync(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),t);const s=this.replaceLaunchScreenImage(t,this.getMaterialFilePath(e,l),f,n,e,i);n.progress(`update ${a} splashscreen image...`);const o=fs_extra_1.default.readFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),"utf8");let r="";r=s?o.replace("__UISplashScreenImageName__",`UISplashScreenImageName = "${s}";\n`).replace("__UILaunchStoryboardName__",`UILaunchStoryboardName = "LaunchScreen_${a}";\n`):o.replace("__UISplashScreenImageName__","").replace("__UILaunchStoryboardName__",""),fs_extra_1.default.writeFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),r),n.progress(`update ${a} splashscreen image success`)}})}n.progress("update base splashscreen image...");const _=this.replaceLaunchScreenImage(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),this.getMaterialFilePath(e,d),f,n,e,i);n.progress("update base splashscreen image success"),_&&(c.UISplashScreenImageName=_,c.UILaunchStoryboardName="LaunchScreen",plist.writeFileSync(u,c))}genUseExtendedSdk(e,i){const t=Object.assign({},e.useExtendedSdk||{});for(const i in e)if("object"==typeof e[i])for(const n in e[i])if(n.startsWith("useExtendedLib_WeApp")&&!0===e[i][n]){t[n.slice("useExtendedLib_".length)]=!0}return!t.WeAppLBS||t.WeAppOpenFuns||t.WeAppOpenFuns_HasPay||(t.WeAppOpenFuns=!0),"RemoteDebug"===(null==i?void 0:i.debugType)&&(t.WeAppUSB=!0),t}async updateExtendedSdk(e,i,t,n,a,s,o){const r=path_1.default.join(i,"Frameworks");fs_extra_1.default.ensureDirSync(r),o.progress("update extendsdk...");const l=path_1.default.join(t,"WeAppSDK.podspec"),p=fs_extra_1.default.readFileSync(l,"utf-8"),d=this.genUseExtendedSdk(a,s);o.progress("useExtendedSdks: "+JSON.stringify(d));const{mobileapp_info:u={}}=e,c=this.getBundleIdentifier(u);if(d.WeAppOpenFuns&&d.WeAppOpenFuns_HasPay)throw new Error("OpenFuncs SDK 只可勾选使用一个,请按需勾选使用");const f={},_=["WeAppUSB"];for(const e in d){if(!d[e])continue;const i=getDepReg(e),a=p.match(i);if(!(null==a?void 0:a[1])){if(_.includes(e))continue;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/miniapp/changelog/difflog.html`)}const s=[];if(a[1].split("\n").forEach(e=>{const i=e.match(/.*'(.*?)',/);if(null==i?void 0:i[1]){const e=i[1].split("/").pop(),a=path_1.default.join(t,"Libs",n,e);if(!fs_extra_1.default.existsSync(a)){if(_.includes(e+".framework"))return;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/miniapp/changelog/difflog.html`)}const o=path_1.default.join(r,e);fs_extra_1.default.copySync(a,o),s.push(path_1.default.basename(e));const l=path_1.default.join(o,"info.plist");if(!fs_extra_1.default.existsSync(l))throw new Error("can not found extendsdk info.plist: "+e);this.changeExtendSDKInfoplistBundleId(l,c,e)}}),s.length){f[s.shift()]=s}}const h=path_1.default.join(i,"DyFrameworks.plist");fs_extra_1.default.existsSync(h)&&fs_extra_1.default.removeSync(h),plist.writeFileSync(h,f)}async updatePrivacyInfo(e,i,t){var n;const a=null===(n=null==i?void 0:i.privacy)||void 0===n?void 0:n.privacyInfo;a&&(a.endsWith("PrivacyInfo.xcprivacy")?fs_extra_1.default.existsSync(a)?(fs_extra_1.default.copySync(a,path_1.default.join(e,"/PrivacyInfo.xcprivacy")),t.progress("隐私清单文件替换成功")):t.message("error","隐私清单文件替换失败,文件不存在,将使用默认文件"):t.message("error","隐私清单文件替换失败,文件名必须为 PrivacyInfo.xcprivacy,将使用默认文件"))}async updatePlugin(e,i,t,n,a,s,o,r){const l={},p={},d=[];if(n["mini-plugin"]&&Array.isArray(n["mini-plugin"].ios)){n["mini-plugin"].ios.forEach(e=>{e.open&&e.pluginId?("string"==typeof e.resourcePath&&e.resourcePath.length>0&&(l[e.pluginId]=e.resourcePath),"object"==typeof e.resourceObjects&&Object.keys(e.resourceObjects).length>0&&(p[e.pluginId]=e.resourceObjects)):d.push(e.pluginId)})}if(d.length>0&&r.message("warn","下列插件未启用,请确认project.miniapp.json中的配置:"+d.join(", ")),!i.length)return;const u=path_1.default.join(e,"Frameworks"),c=path_1.default.join(e,"PlugIns");fs_extra_1.default.ensureDirSync(u),r.progress("update plugin...");const f=this.prepareAppexProfileConfig(i,n,t,a,s,o,n.version,r);if(!f)throw new Error("依赖的多端插件需要配置对应的profile");i.forEach(i=>{const{pluginId:n}=i,a=i.dir,s=n+".framework",o=path_1.default.join(u,s);if(-1!==a.indexOf("local-miniapp-plugin")){const e=fs_extra_1.default.statSync(a),{mtime:i}=e;r.progress(`${n}.framework 正在使用本地版本,修改时间为 ${i}`)}fs_extra_1.default.existsSync(o)&&fs_extra_1.default.removeSync(o);const d=path_1.default.join(a,s);if(fs_extra_1.default.existsSync(d)){fs_extra_1.default.copySync(d,o),this.copyResourcesToMainBundle(d,e),this.copyUserResourcePathIntoPlugins(n,t,l[n],p[n],path_1.default.join(o,"MiniPlugin.bundle"),r);fs_extra_1.default.readdirSync(a).forEach(i=>{if(i.endsWith(".appex")){const s=path_1.default.parse(i).name,o=f[s],d=path_1.default.join(c,i);if(!o||!0!==o.enable)return;r.progress(`${n} 插件使用 appex 中 : ${i}`),fs_extra_1.default.existsSync(d)&&fs_extra_1.default.removeSync(d),fs_extra_1.default.ensureDirSync(d);const u=path_1.default.join(a,i);fs_extra_1.default.copySync(u,d),(null==o?void 0:o.profilePath)&&fs_extra_1.default.copySync(o.profilePath,path_1.default.join(d,"embedded.mobileprovision")),this.copyResourcesToMainBundle(u,e),this.copyUserResourcePathIntoPlugins(n,t,l[n],p[n],path_1.default.join(d,"MiniPlugin.bundle"),r)}else if(i.endsWith("framework")&&i!==s){const e=path_1.default.join(u,i),t=path_1.default.join(a,i);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.copySync(t,e)}})}else fs_extra_1.default.copySync(a,o),this.copyResourcesToMainBundle(a,e),this.copyUserResourcePathIntoPlugins(n,t,l[n],p[n],path_1.default.join(o,"MiniPlugin.bundle"),r)})}copyUserResourcePathIntoPlugins(e,i,t,n,a,s){const o=a;if(t){const n=path_1.default.basename(t),a=this.getMaterialFilePath(i,t);if(a){s.progress(`${e}.framework 正在拷贝配置的资源:${t}`);const i=fs_extra_1.default.lstatSync(a);fs_extra_1.default.ensureDirSync(o),i.isDirectory()?fs_extra_1.default.copySync(a,o):i.isFile()&&fs_extra_1.default.copyFileSync(a,path_1.default.join(o,n))}}if(n){s.progress(e+".framework 正在写入配置的资源"),fs_extra_1.default.ensureDirSync(o);for(const e in n){const i=n[e],t=path_1.default.join(o,e);fs_extra_1.default.ensureDirSync(o),fs_extra_1.default.ensureFileSync(t),fs_extra_1.default.writeFileSync(t,i)}}}copyResourcesToMainBundle(e,i){const t=path_1.default.join(e,"MiniPlugin.bundle"),n=path_1.default.join(t,"PluginConfig.plist");if(fs_extra_1.default.existsSync(n)){const e=plist.readFileSync(n).CopyResourcesToMainBundle;(null==e?void 0:e.length)&&e.forEach(e=>{const n=path_1.default.join(t,e);fs_extra_1.default.existsSync(n)&&fs_extra_1.default.copySync(n,path_1.default.join(i,e))})}}prepareAppexProfileConfig(e,i,t,n,a,s,o,r){if(!n)return void r.message("doing","miniappCacheDirPath is missing");let l=!1;const p={};if(i["mini-plugin"]&&Array.isArray(i["mini-plugin"].ios)){i["mini-plugin"].ios.forEach(e=>{if(e.open&&e.pluginId&&"object"==typeof e.appexProfiles)for(const i in e.appexProfiles){r.message("doing",`检查插件 ${e.pluginId} ${i} appex 配置中 ...`);const n=e.appexProfiles[i];if(!0===n.enable){const s=`${e.pluginId}_${i}`;p[s]={enable:!0};let o=n.profilePath;if(a&&(o=n.distributeProfilePath),n.bundleID&&o){const a=path_1.default.join(t,o);fs_extra_1.default.existsSync(a)?(p[s].bundleID=n.bundleID,p[s].profilePath=path_1.default.join(t,o)):(l=!0,r.message("error",`${e.pluginId} 中 ${i} 的 profilePath 无法找到对应的文件:${a}(需要在小程序项目路径下,填入相对于项目根目录的路径)`))}else l=!0,r.message("error",`${e.pluginId}中${i} 是 无效的appexProfiles配置。需要配置 bundleID,profilePath,distributeProfilePath。profile 文件需要放置在小程序项目内,然后配置相对于小程序项目根目录的相对路径。分发证书构建的情况下, 一定需要配置distributeProfilePath。查看文档了解详情。`)}}})}if(e.forEach(e=>{fs_extra_1.default.readdirSync(e.dir).forEach(i=>{if(i.endsWith(".appex")){const t=path_1.default.parse(i).name,n=p[t];if(n&&!0===n.enable)if(n.bundleID&&n.profilePath){if(n.bundleID&&n.profilePath){const t=path_1.default.join(e.dir,i,"info.plist"),a=n.bundleID;this.changeInfoplistBundleId(t,a),this.changeInfoplistBundleVersion(t,s,o),r.message("doing",`${e.pluginId} ${i} ${a} ${t} 处理 appex bundle ID 中`)}}else l=!0,r.message("error",`${e.pluginId} 的 多端插件包含了${t.slice(e.pluginId.length+1)} 的 appex。开发者需要在project.miniapp.json 中 mini-plugin 配置下对应合理的 profile 文件。查看文档了解详情。`)}})}),l)return!1;if(!(0,lodash_1.isEmpty)(p)){const e=path_1.default.join(n,APPEX_PROFILES_MAPS_FILE);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.ensureFileSync(e);const i={};for(const e in p)i[e]={bundleID:p[e].bundleID,profilePath:p[e].profilePath};fs_extra_1.default.writeFileSync(e,JSON.stringify(i));const t=path_1.default.join(n,APPEX_PROFILES_MAPS_FOR_SHELL_FILE);fs_extra_1.default.existsSync(t)&&fs_extra_1.default.removeSync(t),fs_extra_1.default.ensureFileSync(t);const a=Object.keys(p).map(e=>{const i=p[e];return`pluginAppexName:${e};_;_;bundleID:${i.bundleID};_;_;profile:${i.profilePath}\n\n`}).join("");fs_extra_1.default.writeFileSync(t,a)}return p}changeExtendSDKInfoplistBundleId(e,i,t){const n=`${i}.${path_1.default.parse(t).name.replace(/_/g,"")}`;return this.changeInfoplistBundleId(e,n)}changeInfoplistBundleId(e,i){const t=plist.readFileSync(e);return t.CFBundleIdentifier=i,plist.writeFileSync(e,t),t.CFBundleIdentifier}changeInfoplistBundleVersion(e,i,t){const n=plist.readFileSync(e);return n.CFBundleVersion=i,n.CFBundleShortVersionString=t,plist.writeFileSync(e,n),n.CFBundleIdentifier}async getEntitlements(e,i,t,n){const{mobileapp_info:a={}}=e;let s=a.ios_universal_link||a.debug_ios_universal_link;if((s.startsWith("https://")||s.startsWith("http://"))&&(s=s.replace(/^http(s)?:\/\//g,"applinks:")),Array.isArray(t.__customAssociatedDomains)){const e=t.__customAssociatedDomains.filter(e=>"string"==typeof e&&e.length>0);if(e.length>0){e.splice(0,0,s);return{"com.apple.developer.associated-domains":e.join("_$_ULinK_$_")}}}return{"com.apple.developer.associated-domains":s}}useTpush(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingTpush)(e)}async buildCloud(e,i){const{projectPath:t,demoIpaPath:n,sdkPath:a,arch:s="arm64",bindingInfo:o,certificateInfo:r,output:l,miniappCacheDirPath:p,pluginDirList:d,inLandun:u,theme:c,i18nInfo:f,debugInfo:_,CILocalBuild:h,cacheAssetCarPath:g}=e,y=this.generateTempDemoIpaPath(n),{selfCertificate:m={}}=r,S=(null==m?void 0:m.isPublish)||!1,I=(0,miniappJson_1.tryGetIOSMiniappJson)(t),x=this.useTpush(I);if((0,lodash_1.isEmpty)(I))throw new Error("获取project.miniapp.json失败");if(errorIOSSdkVersions.includes(I.sdkVersion))throw new Error("当前 mini-ios.sdkVersion 存在缺陷,请参考更新日志进行修改");let v=o;if(r.signType===miniapp_builder_1.miniappSinTypes.appleId.type){const{mobileapp_info:e={}}=v;v=Object.assign(Object.assign({},v),{mobileapp_info:Object.assign(Object.assign({},e),{bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID,debug_ios_bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID})})}const b=await this.updateIOSInfoPlistInfo(t,v,y,I,i,f);await this.updateIOSAppConfigPlistInfo(t,v,y,I,a,!1,i,c,f),await this.updateIOSAppexInfoPlistInfo(v,y,I,b,i),await this.updateIOSIcons(t,y,p,I,S,i,!0===u,g),await this.updateSplashScreen(t,y,I,i,c,f),await this.updateExtendedSdk(v,y,a,s,I,_,i),await this.updatePlugin(y,d,t,I,p,S,b,i),await this.updatePrivacyInfo(y,I,i),await this.updateIOSAppResource(t,y,I,i);const F=await this.getEntitlements(v,y,I,i),{mobileapp_info:P={}}=v;let j;j=r.signType===miniapp_builder_1.miniappSinTypes.appleId.type?miniapp_builder_1.DEFAULT_BUNDLE_ID:P.ios_flag&&P.bundle_id||P.debug_ios_bundle_id;const B={bundleId:j,output:l,entitlements:F};if(I.buildCloud&&(I.buildCloud.certificate&&"string"==typeof I.buildCloud.certificate&&(B.certificate=I.buildCloud.certificate),I.buildCloud.profile&&"string"==typeof I.buildCloud.profile&&(B.profile=path_1.default.join(t,I.buildCloud.profile)),x&&I.buildCloud.tpnsProfile&&"string"==typeof I.buildCloud.tpnsProfile&&(B.tpnsProfile=path_1.default.join(t,I.buildCloud.tpnsProfile))),h&&(B.profile=m.profilePath,B.certificate=m.certificateName),m.isPublish||h){const e=await(0,codesign_1.codesignAndExport)(t,y,p||"",B,i,x,!0===u);if(!0!==e.success)throw new Error("Build ipa failed:"+(e.errMsg||"codesignAndExport failed"))}return{projectPath:t,demoIpaPath:y,opts:B,iosMiniappJson:I,isPublish:S}}async writeI18NInfoFile(e,i,t){Object.keys(i).forEach(n=>{if("base"===n)return;let a="";Object.keys(t).forEach(e=>{var s,o,r,l;"UISplashScreenImageName"!==e?"UILaunchStoryboardName"!==e?(null===(o=null===(s=i[n])||void 0===s?void 0:s.ios)||void 0===o?void 0:o[t[e]])&&(a+=`${e} = "${null===(l=null===(r=i[n])||void 0===r?void 0:r.ios)||void 0===l?void 0:l[t[e]]}";\n`):a+="__UILaunchStoryboardName__\n":a+="__UISplashScreenImageName__\n"}),a&&(fs_extra_1.default.ensureDirSync(path_1.default.join(e,n+".lproj")),fs_extra_1.default.writeFileSync(path_1.default.join(e,n+".lproj/InfoPlist.strings"),a))})}getMaterialFilePath(e,i){if(!i)return"";let t=i;if(path_1.default.isAbsolute(i)||(t=path_1.default.join(e,i)),fs_extra_1.default.existsSync(t))return t;const n=(0,tools_1.generateMD5)(i),a=path_1.default.basename(i),s=path_1.default.join(e,exports.remoteBuildProjectMaterialAbsoluteCacheDir,`${n}_${a}`);return fs_extra_1.default.existsSync(s)?s:""}updateIOSAppResource(e,i,t,n){const a=t.resourcePath;if(!a)return;const s=this.getMaterialFilePath(e,a);if(s){n.progress("正在拷贝资源至主包:"+s);const e=fs_extra_1.default.lstatSync(s);if(e.isDirectory())this.copyDirectory(s,i,!1);else if(e.isFile()){const e=path_1.default.basename(a),t=path_1.default.join(i,e);if(fs_extra_1.default.existsSync(t))throw new Error(`fail to copy ${s}, overwrite is not allowed`);fs_extra_1.default.copyFileSync(s,t)}}}copyDirectory(e,i,t=!0){if(fs_extra_1.default.ensureDirSync(i),t)fs_extra_1.default.copySync(e,i);else{fs_extra_1.default.readdirSync(e).forEach(n=>{const a=path_1.default.join(e,n),s=path_1.default.join(i,n);if(fs_extra_1.default.statSync(a).isDirectory())this.copyDirectory(a,s,t);else{if(fs_extra_1.default.existsSync(s))throw new Error(`fail to copy ${a}, overwrite is not allowed`);fs_extra_1.default.copyFileSync(a,s)}})}}}exports.default=new buildCloudManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.IOSUtils=void 0;const tslib_1=require("tslib"),child_process=tslib_1.__importStar(require("child_process")),path_1=tslib_1.__importDefault(require("path")),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),env_1=require("../../../utils/env"),deviceUtils=tslib_1.__importStar(require("./device")),projectConfigUtils=tslib_1.__importStar(require("./projectconfig")),cp_1=require("../../../utils/cp"),miniapp_builder_1=require("../../../utils/miniapp-builder"),usbProcess_1=require("../../../utils/usbProcess"),miniappJson_1=require("../../../utils/miniappJson"),singletontask_1=require("../../../utils/singletontask"),buildCloud_1=tslib_1.__importStar(require("./buildCloud")),tools_1=require("../../../utils/tools"),codesign_1=require("../../../utils/codesign"),ProjectMiniappJsonSplashScreenThemeKey="__splashscreenTheme",_iconInfoMap={appStore1024:{size:[1024,1024],scale:1,idiom:"ios-marketing",required:!0},mainIcon120:{size:[60,60],scale:2,idiom:"iphone",required:!0},mainIcon180:{size:[60,60],scale:3,idiom:"iphone"},spotlightIcon80:{size:[40,40],scale:2,idiom:"iphone"},spotlightIcon120:{size:[40,40],scale:3,idiom:"iphone"},settingsIcon58:{size:[29,29],scale:2,idiom:"iphone"},settingsIcon87:{size:[29,29],scale:3,idiom:"iphone"},notificationIcon40:{size:[20,20],scale:2,idiom:"iphone"},notificationIcon60:{size:[20,20],scale:3,idiom:"iphone"},ipadMainIcon152:{size:[76,76],scale:2,idiom:"ipad"},ipadMainIcon167:{size:[83.5,83.5],scale:2,idiom:"ipad"},ipadSpotlightIcon40:{size:[40,40],scale:1,idiom:"ipad"},ipadSpotlightIcon80:{size:[40,40],scale:2,idiom:"ipad"},ipadSettingsIcon29:{size:[29,29],scale:1,idiom:"ipad"},ipadSpotlightIcon58:{size:[29,29],scale:2,idiom:"ipad"},ipadNotificationIcon20:{size:[20,20],scale:1,idiom:"ipad"},ipadNotificationIcon40:{size:[20,20],scale:2,idiom:"ipad"}},_allowTheme=["Light","LightSpecial","Dark","DarkSpecial","Default"],_getDepReg=e=>new RegExp(`s.subspec '${e}'.*\n(?:.*\n)*?(?:.*sp.vendored_frameworks = \\[\n)((?:.*'.*?'.*\n)*?)(?:.*\\]\n)`,"m"),buildIOSPluginTask={};class IOSUtils{constructor(e,i={},t,o){this.root=e,this.userConfig=i,this.miniappDirPath=t,this.devtoolsVersion=o}getProjectConfig(){const e=projectConfigUtils.getProjectConfig(this.root,this.userConfig);if(!e)throw new Error("iOS project folder not found. Are you sure this is a miniapp project?");return e}getBundleId(e){return child_process.execFileSync("/usr/libexec/PlistBuddy",["-c","Print:CFBundleIdentifier",path_1.default.join(e,"Info.plist")],{encoding:"utf8",env:(0,env_1.getProcessEnv)()}).trim()}tryInstallPod(e,i){const t=this.getProjectConfig(),{sourceDir:o}=t,n={cwd:o,env:(0,env_1.getProcessEnv)()};i.progress("export LANG=en_US.UTF-8 && pod install"),child_process.execSync("export LANG=en_US.UTF-8 && pod install",n)}async runLocal(e,i){const t=this.getProjectConfig(),{sourceDir:o}=t;process.chdir(o),this.tryInstallPod(e,i);const n=path_1.default.basename(t.name,path_1.default.extname(t.name)),s=e.scheme||n;if(i.progress(`Found Xcode ${t.isWorkspace?"workspace":"project"} "${t.name}"`),e.device||e.udid){if(e.udid||e.device){const o=await deviceUtils.getDevices({recorder:i}),n=o.find(i=>i.udid===e.udid||i.name===e.device);if(!n)throw new Error(`Could not find a device with udid(${e.udid}) or device(${e.device}). ${deviceUtils.printFoundDevices(o)}`);if("simulator"===n.type)return void await this.runOnSimulatorLocal(t,s,e,i);await this.runOnDeviceLocal(t,s,n,i)}}else await this.runOnSimulatorLocal(t,s,e,i)}async runCloud(e,i){try{const{deviceType:t,udid:o,projectPath:n,demoIpaPath:s,sdkPath:r,bindingInfo:a,certificateInfo:c,arch:l="arm64",pluginDirList:d,miniappCacheDirPath:u,theme:p,i18nInfo:h,debugInfo:f}=e,_=buildCloud_1.default.generateTempDemoIpaPath(s),m="simulator"===t,g=(0,miniappJson_1.tryGetIOSMiniappJson)(n);let b=a;if(c.signType===miniapp_builder_1.miniappSinTypes.appleId.type){const{mobileapp_info:e={}}=b;b=Object.assign(Object.assign({},b),{mobileapp_info:Object.assign(Object.assign({},e),{bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID,debug_ios_bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID})})}const v=await buildCloud_1.default.updateIOSInfoPlistInfo(n,b,_,g,i,h);await buildCloud_1.default.updateIOSAppConfigPlistInfo(n,b,_,g,r,m,i,p,h),await buildCloud_1.default.updateIOSAppexInfoPlistInfo(b,_,g,v,i),await buildCloud_1.default.updateIOSIcons(n,_,"",g,!1,i),await buildCloud_1.default.updateSplashScreen(n,_,g,i,p,h),await buildCloud_1.default.updateExtendedSdk(b,_,r,l,g,f,i),await buildCloud_1.default.updatePlugin(_,d,n,g,u,!1,v,i);const y=await buildCloud_1.default.getEntitlements(b,_,g,i);if("device"===t){const{mobileapp_info:e={}}=b,t=e.ios_flag&&e.bundle_id||e.debug_ios_bundle_id;await(0,miniapp_builder_1.signAndInstallOrExport)(n,_,u,c,{bundleId:t,install:!0,deviceId:o,entitlements:y},{recorder:i,miniappDirPath:this.miniappDirPath,devtoolsVersion:this.devtoolsVersion})}else await this.runOnSimulatorCloud(_,{udid:o},i)}catch(e){throw new Error(e.message)}}async buildLocal(e,i){const t=this.getProjectConfig();process.chdir(t.sourceDir);const o=path_1.default.basename(t.name,path_1.default.extname(t.name)),n=e.scheme||o;this.tryInstallPod(e,i),i.progress("start build ipa...");const s=await this.buildProjectArchive(t,{output:e.output,scheme:n},i),r=await this.exportArchive(t,s,e,i);return console.log("Successfully build ipa: "+r),r}async buildCloud(e,i){try{const{projectPath:t,certificateInfo:o,miniappCacheDirPath:n}=e,s=await buildCloud_1.default.buildCloud(e,i),{demoIpaPath:r,opts:a}=s,c={recorder:i,miniappDirPath:this.miniappDirPath,devtoolsVersion:this.devtoolsVersion};s.isPublish||e.CILocalBuild||await(0,miniapp_builder_1.signAndInstallOrExport)(t,r,n,o,a,c)}catch(e){throw new Error(e.message)}}async genProjectMaterialMap(e,i,t,o){var n,s;const r=buildCloud_1.remoteBuildProjectMaterialAbsoluteCacheDir,a=path_1.default.join(i,r),c=(0,miniappJson_1.tryGetIOSMiniappJson)(e);function l(e,i){const t=fs_extra_1.default.lstatSync(e);fs_extra_1.default.ensureDirSync(path_1.default.dirname(i)),t.isDirectory()?fs_extra_1.default.copySync(e,i):fs_extra_1.default.copyFileSync(e,i)}function d(t,o,n=!0){if(!o){if(n)return"";throw new Error(`file cant be empty for cloud build, key: ${t} , fileName: ${o}`)}if(path_1.default.isAbsolute(o)){const e=path_1.default.basename(o);if(!fs_extra_1.default.existsSync(o)){if(n)return"";throw new Error(`file cant be empty for cloud build, key: ${t} , fileName: ${o}`)}const i=(0,tools_1.generateMD5)(o);return l(o,path_1.default.join(a,`${i}_${e}`)),path_1.default.join(r,e)}const s=path_1.default.join(e,o),c=path_1.default.join(i,o);if(!fs_extra_1.default.existsSync(s)){if(n)return"";throw new Error(`file cant be empty for cloud build, key: ${t} , fileName: ${o}`)}return l(s,c),o}fs_extra_1.default.ensureDirSync(a);const{privacy:u={},icons:p={},splashscreen:h={},buildCloud:f={}}=c,_=d("project.miniapp.json","project.miniapp.json",!1),m=d("project.config.json","project.config.json",!1),g=(0,miniappJson_1.getMiniprogramRoot)(e),b=d("app.json",path_1.default.join(g,"app.json"),!1),{template:v,contentViewImage:y,cancelButtonImage:S,confirmButtonImage:P}=u,w=d("privacy template",v),I=d("privacy contentViewImage",y),x=d("privacy cancelButtonImage",S),j=d("privacy confirmButtonImage",P),E=[];for(const e in p)if(p[e]){const i=d("icons."+e,p[e],!1);i&&E.push(i)}const O=d("splashscreen.customImage",h.customImage),{p12:D,profile:C,tpnsProfile:A}=f,$=d("p12 Path",D,!1),T=d("profile Path",C,!1);let k=void 0;!0===(null===(n=null==c?void 0:c.tpush)||void 0===n?void 0:n.useExtendedLib_WeAppTPNS)&&(k=d("tpns profile Path",A,!0!==(null===(s=null==c?void 0:c.tpush)||void 0===s?void 0:s.useExtendedLib_WeAppTPNS)));const B="miniapp/ios/i18nInfo.json",U=path_1.default.join(e,B),F=d("i18n",B,!0);if(fs_extra_1.default.existsSync(U)){const i=function(e,i){function t(i,t,o){if(t[o]&&"object"==typeof t[o][i])for(const n in t[o][i])if("object"==typeof t[o][i]){const s=t[o][i][n];if("string"==typeof s&&s.length>0){fs_extra_1.default.existsSync(path_1.default.isAbsolute(s)?s:path_1.default.join(e,s))&&d(`i18nFiles.${o}.${n}`,s,!0)}}}try{const o=fs_extra_1.default.readJSONSync(path_1.default.join(e,i));for(const e in o)t("ios",o,e),t("android",o,e)}catch(e){return e.message}}(e,B);if(i)throw o.message("error",i),new Error("copyi18NFiles error "+i)}const L=path_1.default.join(i,"project.miniapp.json");try{const e=fs_extra_1.default.readJsonSync(L);let{theme:i}=t;t.theme||(i="Dark"),e.__splashscreenTheme=i,fs_extra_1.default.writeJSONSync(L,e)}catch(e){throw new Error(`ReadWriteJsonFailed projectMiniappJsonCacheFilePath: ${L},error ${e.message}`)}const M=c["mini-plugin"];return M&&Array.isArray(M.ios)&&M.ios.forEach(e=>{!0===e.open&&e.resourcePath&&d(`mini-plugin ios ${e.pluginId}:${e.resourcePath}`,e.resourcePath)}),{projectMiniappJson:_,projectConfigJson:m,appJson:b,privacyJson:w,privacyContentViewImage:I,privacyCancelButtonImage:x,privacyConfirmButtonImage:j,icons:E,splashScreen:O,p12:$,profile:T,tpnsProfile:k,i18nJson:F}}async codesignIOSApp(e,i){const{projectPath:t,demoIpaPath:o,opts:n}=e,s=await(0,codesign_1.codesignAndExport)(t,o,e.miniappCacheDir||"",n,i,e.isUsingTpush,!1,!0);if(!0!==s.success)throw new Error("Build ipa failed:"+(s.errMsg||"codesignAndExport failed"))}async packIOSCloudBuildMaterial(e,i){i.progress("start uploadProjectAllMaterial");const{projectPath:t,matrialDistPath:o,theme:n}=e;await this.genProjectMaterialMap(t,o,e,i);i.progress("packIOSCloudBuildMaterial done")}async initUSBConnectionProcess(e,i){await(0,usbProcess_1.startUSBManagerProcess)(e,i)&&i.progress("Init USB Process Successfully")}launchSimulator(e,i){let t;try{t=JSON.parse(child_process.execFileSync("xcrun",["simctl","list","--json","devices"],{encoding:"utf8",env:(0,env_1.getProcessEnv)()}))}catch(e){throw new Error("Could not get the simulator list from Xcode. Please open Xcode and try running project directly from there to resolve the remaining issues."+e.message)}const o=["iPhone 13","iPhone 12","iPhone 11"].reduce((e,i)=>e||deviceUtils.findMatchingSimulator(t,{device:i}),deviceUtils.findMatchingSimulator(t,e));if(!o)throw new Error("No simulator available with "+(e.device?`name "${e.device}"`:`udid "${e.udid}"`));const n=child_process.execFileSync("xcode-select",["-p"],{encoding:"utf8",env:(0,env_1.getProcessEnv)()}).trim();if(child_process.execFileSync("open",[n+"/Applications/Simulator.app","--args","-CurrentDeviceUDID",o.udid],{env:(0,env_1.getProcessEnv)()}),!o.booted){const e=deviceUtils.formattedDeviceName(o);i.progress("Launching "+e),child_process.spawnSync("xcrun",["simctl","boot",o.udid],{env:(0,env_1.getProcessEnv)()})}return o}async runOnSimulatorCloud(e,i,t){const{udid:o}=i,n=this.launchSimulator({udid:o},t);await this.installAppOnSimulator(n,e,t),await this.launchAppOnSimulator(n,e,t)}async runOnSimulatorLocal(e,i,t,o){const n=this.launchSimulator(t,o),{appPath:s}=await this.buildProjectApp(e,{udid:n.udid,scheme:i},o);await this.installAppOnSimulator(n,s,o),await this.launchAppOnSimulator(n,s,o)}async runOnDeviceLocal(e,i,t,o){const{appPath:n}=await this.buildProjectApp(e,{udid:t.udid,scheme:i},o);if("catalyst"===t.type){child_process.spawn(`${n}/${i}`,[],{detached:!0,stdio:"ignore",env:(0,env_1.getProcessEnv)()}).unref()}else{const e=["--bundle",n,"--id",t.udid,"--justlaunch"];o.progress("Installing and launching your app on "+t.name);const i=path_1.default.join(__dirname,"../../../vendor/ios-deploy/ios-deploy");await(0,cp_1.spawnSync)(i,e,{},o)}return o.progress("Install successfully the app to the device.")}buildProjectApp(e,i,t){return new Promise((o,n)=>{const{scheme:s,udid:r}=i,a=[e.isWorkspace?"-workspace":"-project",e.name,"-scheme",s];let c;r&&a.push("-destination","id="+r),t.progress(`Building (using "xcodebuild ${a.join(" ")}")`),this.xcbeautifyAvailable()?c=child_process.spawn("xcbeautify",[],{stdio:["pipe",process.stdout,process.stderr],env:(0,env_1.getProcessEnv)()}):this.xcprettyAvailable()&&(c=child_process.spawn("xcpretty",[],{stdio:["pipe",process.stdout,process.stderr],env:(0,env_1.getProcessEnv)()}));const l=child_process.spawn("xcodebuild",a,{env:(0,env_1.getProcessEnv)()});let d="",u="";l.stdout.on("data",e=>{const i=e.toString();t.progress(i),d+=i,c&&c.stdin.write(e)}),l.stderr.on("data",e=>{const i=e.toString();u+=i,t.progress(i)}),l.on("close",i=>{if(c&&c.stdin.end(),0!==i)return void n(new Error(` Failed to build iOS project.\n We ran "xcodebuild" command but it exited with error code ${i}. To debug build\n logs further, consider building your app with Xcode.app, by opening\n ${e.name}.\n ${c?void 0:`${d}\n${u}`}\n `));let r;try{r=this.getBuildInfo(e,d,s)}catch(e){n(e)}t.progress("Successfully built the app"),o(r)})})}async installAppOnSimulator(e,i,t){const o=["simctl","install",e.udid,i];await(0,cp_1.spawnSync)("xcrun",o,{},t)}async launchAppOnSimulator(e,i,t){const o=this.getBundleId(i),n=["simctl","launch",e.udid,o];await(0,cp_1.spawnSync)("xcrun",n,{},t),t.progress("Successfully launched the app on the simulator")}async buildProjectArchive(e,i,t){const{output:o,scheme:n,udid:s}=i,r=path_1.default.join(o,"./app"),{sourceDir:a}=e;fs_extra_1.default.ensureDirSync(path_1.default.dirname(r));const c=["archive",e.isWorkspace?"-workspace":"-project",e.name,"-scheme",n,"-archivePath",r];s&&c.push("-destination","id="+s);try{if(await(0,cp_1.spawnSync)("xcodebuild",c,{cwd:a},t),!fs_extra_1.default.existsSync(r+".xcarchive"))throw new Error(`Failed to build iOS project.\n ${r+".xcarchive"} does not found\n `);return t.progress(`Successfully archive the app: ${r}.xcarchive`),r+".xcarchive"}catch(i){throw new Error(`Failed to build iOS project. To debug build\n logs further, consider building your app with Xcode.app, by opening\n ${e.name}.\n `)}}async exportArchive(e,i,t,o){const n=path_1.default.join(t.output,"ipa");fs_extra_1.default.ensureDirSync(n),fs_extra_1.default.emptyDirSync(n);const{exportOptionPlistPath:s}=t;if(!s)throw new Error("build ios ipa require exportOptionPlistPath in project.miniapp.json");let r="";r=path_1.default.isAbsolute(s)?s:path_1.default.join(t.projectPath,s);const a=["-exportArchive","-archivePath",i,"-exportOptionsPlist",r,"-exportPath",n];try{await(0,cp_1.spawnSync)("xcodebuild",a,{cwd:e.sourceDir},o)}catch(i){throw new Error(`To debug build\n logs further, consider building your app with Xcode.app, by opening\n ${e.name}.\n `)}return fs_extra_1.default.removeSync(i),n}getTargetPaths(e){const i=JSON.parse(e);for(const e in i){if("app"===i[e].buildSettings.WRAPPER_EXTENSION)return{targetBuildDir:i[e].buildSettings.TARGET_BUILD_DIR,executableFolderPath:i[e].buildSettings.EXECUTABLE_FOLDER_PATH}}return{}}getBuildInfo(e,i,t){const o=this.getPlatformName(i),n=[e.isWorkspace?"-workspace":"-project",e.name,"-scheme",t,"-sdk",o,"-showBuildSettings","-json"].join(" "),s=child_process.execSync("xcodebuild "+n,{encoding:"utf8",cwd:e.sourceDir,env:(0,env_1.getProcessEnv)()}),r=this.getBuildProductDir(i),{executableFolderPath:a}=this.getTargetPaths(s);if(!a)throw new Error("Failed to get the app name.");return{sdk:o,appPath:`${r}/${a}`}}getPlatformName(e){const i=/export PLATFORM_NAME\\?="?(\w+)"?$/m.exec(e);if(!i)throw new Error("Couldn't find PLATFORM_NAME in xcodebuild output.");return i[1]}getBuildProductDir(e){const i=/export BUILT_PRODUCTS_DIR\\?="?(.+)"?$/m.exec(e);if(!i)throw new Error("Couldn't find BUILT_PRODUCTS_DIR in xcodebuild output.");return i[1]}xcbeautifyAvailable(){try{child_process.execSync("xcbeautify --version",{stdio:[0,"pipe","ignore"],env:(0,env_1.getProcessEnv)()})}catch(e){return!1}return!0}xcprettyAvailable(){try{child_process.execSync("xcpretty --version",{stdio:[0,"pipe","ignore"],env:(0,env_1.getProcessEnv)()})}catch(e){return!1}return!0}async buildPlugin(e,i){const{pluginId:t,projectPath:o,buildShellPath:n}=e;i.progress("start build native plugin...");try{const e=[o,t];fs_extra_1.default.chmodSync(n,"777"),buildIOSPluginTask[t]?(i.message("error","存在未结束的插件构建任务,需等待构建结束..."),await buildIOSPluginTask[t].getResult(!0)):(buildIOSPluginTask[t]=new singletontask_1.SingletonTask(cp_1.spawnSyncExecShell.bind(null,n,e,{},i)),await buildIOSPluginTask[t].getResult(!0),buildIOSPluginTask[t]=void 0)}catch(e){throw buildIOSPluginTask[t]=void 0,new Error("build plugin failed: "+e)}}async writeI18NInfoFile(e,i,t){Object.keys(i).forEach(o=>{if("base"===o)return;let n="";Object.keys(t).forEach(e=>{var s,r,a,c;(null===(r=null===(s=i[o])||void 0===s?void 0:s.ios)||void 0===r?void 0:r[t[e]])&&(n+=`${e} = "${null===(c=null===(a=i[o])||void 0===a?void 0:a.ios)||void 0===c?void 0:c[t[e]]}";\n`)}),n&&(fs_extra_1.default.ensureDirSync(path_1.default.join(e,o+".lproj")),fs_extra_1.default.writeFileSync(path_1.default.join(e,o+".lproj/InfoPlist.strings"),n))})}}exports.IOSUtils=IOSUtils;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.IOSUtils=void 0;const tslib_1=require("tslib"),child_process=tslib_1.__importStar(require("child_process")),path_1=tslib_1.__importDefault(require("path")),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),env_1=require("../../../utils/env"),deviceUtils=tslib_1.__importStar(require("./device")),projectConfigUtils=tslib_1.__importStar(require("./projectconfig")),cp_1=require("../../../utils/cp"),miniapp_builder_1=require("../../../utils/miniapp-builder"),usbProcess_1=require("../../../utils/usbProcess"),miniappJson_1=require("../../../utils/miniappJson"),singletontask_1=require("../../../utils/singletontask"),buildCloud_1=tslib_1.__importStar(require("./buildCloud")),tools_1=require("../../../utils/tools"),codesign_1=require("../../../utils/codesign"),ProjectMiniappJsonSplashScreenThemeKey="__splashscreenTheme",_iconInfoMap={appStore1024:{size:[1024,1024],scale:1,idiom:"ios-marketing",required:!0},mainIcon120:{size:[60,60],scale:2,idiom:"iphone",required:!0},mainIcon180:{size:[60,60],scale:3,idiom:"iphone"},spotlightIcon80:{size:[40,40],scale:2,idiom:"iphone"},spotlightIcon120:{size:[40,40],scale:3,idiom:"iphone"},settingsIcon58:{size:[29,29],scale:2,idiom:"iphone"},settingsIcon87:{size:[29,29],scale:3,idiom:"iphone"},notificationIcon40:{size:[20,20],scale:2,idiom:"iphone"},notificationIcon60:{size:[20,20],scale:3,idiom:"iphone"},ipadMainIcon152:{size:[76,76],scale:2,idiom:"ipad"},ipadMainIcon167:{size:[83.5,83.5],scale:2,idiom:"ipad"},ipadSpotlightIcon40:{size:[40,40],scale:1,idiom:"ipad"},ipadSpotlightIcon80:{size:[40,40],scale:2,idiom:"ipad"},ipadSettingsIcon29:{size:[29,29],scale:1,idiom:"ipad"},ipadSpotlightIcon58:{size:[29,29],scale:2,idiom:"ipad"},ipadNotificationIcon20:{size:[20,20],scale:1,idiom:"ipad"},ipadNotificationIcon40:{size:[20,20],scale:2,idiom:"ipad"}},_allowTheme=["Light","LightSpecial","Dark","DarkSpecial","Default"],_getDepReg=e=>new RegExp(`s.subspec '${e}'.*\n(?:.*\n)*?(?:.*sp.vendored_frameworks = \\[\n)((?:.*'.*?'.*\n)*?)(?:.*\\]\n)`,"m"),buildIOSPluginTask={};class IOSUtils{constructor(e,i={},t,o){this.root=e,this.userConfig=i,this.miniappDirPath=t,this.devtoolsVersion=o}getProjectConfig(){const e=projectConfigUtils.getProjectConfig(this.root,this.userConfig);if(!e)throw new Error("iOS project folder not found. Are you sure this is a miniapp project?");return e}getBundleId(e){return child_process.execFileSync("/usr/libexec/PlistBuddy",["-c","Print:CFBundleIdentifier",path_1.default.join(e,"Info.plist")],{encoding:"utf8",env:(0,env_1.getProcessEnv)()}).trim()}tryInstallPod(e,i){const t=this.getProjectConfig(),{sourceDir:o}=t,n={cwd:o,env:(0,env_1.getProcessEnv)()};i.progress("export LANG=en_US.UTF-8 && pod install"),child_process.execSync("export LANG=en_US.UTF-8 && pod install",n)}async runLocal(e,i){const t=this.getProjectConfig(),{sourceDir:o}=t;process.chdir(o),this.tryInstallPod(e,i);const n=path_1.default.basename(t.name,path_1.default.extname(t.name)),s=e.scheme||n;if(i.progress(`Found Xcode ${t.isWorkspace?"workspace":"project"} "${t.name}"`),e.device||e.udid){if(e.udid||e.device){const o=await deviceUtils.getDevices({recorder:i}),n=o.find(i=>i.udid===e.udid||i.name===e.device);if(!n)throw new Error(`Could not find a device with udid(${e.udid}) or device(${e.device}). ${deviceUtils.printFoundDevices(o)}`);if("simulator"===n.type)return void await this.runOnSimulatorLocal(t,s,e,i);await this.runOnDeviceLocal(t,s,n,i)}}else await this.runOnSimulatorLocal(t,s,e,i)}async runCloud(e,i){try{const{deviceType:t,udid:o,projectPath:n,demoIpaPath:s,sdkPath:r,bindingInfo:a,certificateInfo:c,arch:l="arm64",pluginDirList:d,miniappCacheDirPath:u,theme:p,i18nInfo:h,debugInfo:f,cacheAssetCarPath:_}=e,m=buildCloud_1.default.generateTempDemoIpaPath(s),g="simulator"===t,b=(0,miniappJson_1.tryGetIOSMiniappJson)(n);let v=a;if(c.signType===miniapp_builder_1.miniappSinTypes.appleId.type){const{mobileapp_info:e={}}=v;v=Object.assign(Object.assign({},v),{mobileapp_info:Object.assign(Object.assign({},e),{bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID,debug_ios_bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID})})}const y=await buildCloud_1.default.updateIOSInfoPlistInfo(n,v,m,b,i,h);await buildCloud_1.default.updateIOSAppConfigPlistInfo(n,v,m,b,r,g,i,p,h),await buildCloud_1.default.updateIOSAppexInfoPlistInfo(v,m,b,y,i),await buildCloud_1.default.updateIOSIcons(n,m,"",b,!1,i,!1,_),await buildCloud_1.default.updateSplashScreen(n,m,b,i,p,h),await buildCloud_1.default.updateExtendedSdk(v,m,r,l,b,f,i),await buildCloud_1.default.updatePlugin(m,d,n,b,u,!1,y,i);const S=await buildCloud_1.default.getEntitlements(v,m,b,i);if(await buildCloud_1.default.updateIOSAppResource(n,m,b,i),"device"===t){const{mobileapp_info:e={}}=v,t=e.ios_flag&&e.bundle_id||e.debug_ios_bundle_id;await(0,miniapp_builder_1.signAndInstallOrExport)(n,m,u,c,{bundleId:t,install:!0,deviceId:o,entitlements:S},{recorder:i,miniappDirPath:this.miniappDirPath,devtoolsVersion:this.devtoolsVersion})}else await this.runOnSimulatorCloud(m,{udid:o},i)}catch(e){throw new Error(e.message)}}async buildLocal(e,i){const t=this.getProjectConfig();process.chdir(t.sourceDir);const o=path_1.default.basename(t.name,path_1.default.extname(t.name)),n=e.scheme||o;this.tryInstallPod(e,i),i.progress("start build ipa...");const s=await this.buildProjectArchive(t,{output:e.output,scheme:n},i),r=await this.exportArchive(t,s,e,i);return console.log("Successfully build ipa: "+r),r}async buildCloud(e,i){try{const{projectPath:t,certificateInfo:o,miniappCacheDirPath:n}=e,s=await buildCloud_1.default.buildCloud(e,i),{demoIpaPath:r,opts:a}=s,c={recorder:i,miniappDirPath:this.miniappDirPath,devtoolsVersion:this.devtoolsVersion};s.isPublish||e.CILocalBuild||await(0,miniapp_builder_1.signAndInstallOrExport)(t,r,n,o,a,c)}catch(e){throw new Error(e.message)}}async genProjectMaterialMap(e,i,t,o){var n,s;const r=buildCloud_1.remoteBuildProjectMaterialAbsoluteCacheDir,a=path_1.default.join(i,r),c=(0,miniappJson_1.tryGetIOSMiniappJson)(e);function l(e,i){const t=fs_extra_1.default.lstatSync(e);fs_extra_1.default.ensureDirSync(path_1.default.dirname(i)),t.isDirectory()?fs_extra_1.default.copySync(e,i):fs_extra_1.default.copyFileSync(e,i)}function d(t,o,n=!0){if(!o){if(n)return"";throw new Error(`file cant be empty for cloud build, key: ${t} , fileName: ${o}`)}if(path_1.default.isAbsolute(o)){const e=path_1.default.basename(o);if(!fs_extra_1.default.existsSync(o)){if(n)return"";throw new Error(`file cant be empty for cloud build, key: ${t} , fileName: ${o}`)}const i=(0,tools_1.generateMD5)(o);return l(o,path_1.default.join(a,`${i}_${e}`)),path_1.default.join(r,e)}const s=path_1.default.join(e,o),c=path_1.default.join(i,o);if(!fs_extra_1.default.existsSync(s)){if(n)return"";throw new Error(`file cant be empty for cloud build, key: ${t} , fileName: ${o}`)}return l(s,c),o}fs_extra_1.default.ensureDirSync(a);const{privacy:u={},icons:p={},splashscreen:h={},buildCloud:f={}}=c,_=d("project.miniapp.json","project.miniapp.json",!1),m=d("project.config.json","project.config.json",!1),g=(0,miniappJson_1.getMiniprogramRoot)(e),b=d("app.json",path_1.default.join(g,"app.json"),!1),{template:v,contentViewImage:y,cancelButtonImage:S,confirmButtonImage:P}=u,w=d("privacy template",v),I=d("privacy contentViewImage",y),x=d("privacy cancelButtonImage",S),j=d("privacy confirmButtonImage",P),E=[];for(const e in p)if(p[e]){const i=d("icons."+e,p[e],!1);i&&E.push(i)}const O=d("splashscreen.customImage",h.customImage),{p12:D,profile:C,tpnsProfile:A}=f,$=d("p12 Path",D,!1),T=d("profile Path",C,!1);let k=void 0;!0===(null===(n=null==c?void 0:c.tpush)||void 0===n?void 0:n.useExtendedLib_WeAppTPNS)&&(k=d("tpns profile Path",A,!0!==(null===(s=null==c?void 0:c.tpush)||void 0===s?void 0:s.useExtendedLib_WeAppTPNS)));const B="miniapp/ios/i18nInfo.json",U=path_1.default.join(e,B),F=d("i18n",B,!0);if(fs_extra_1.default.existsSync(U)){const i=function(e,i){function t(i,t,o){if(t[o]&&"object"==typeof t[o][i])for(const n in t[o][i])if("object"==typeof t[o][i]){const s=t[o][i][n];if("string"==typeof s&&s.length>0){fs_extra_1.default.existsSync(path_1.default.isAbsolute(s)?s:path_1.default.join(e,s))&&d(`i18nFiles.${o}.${n}`,s,!0)}}}try{const o=fs_extra_1.default.readJSONSync(path_1.default.join(e,i));for(const e in o)t("ios",o,e),t("android",o,e)}catch(e){return e.message}}(e,B);if(i)throw o.message("error",i),new Error("copyi18NFiles error "+i)}const L=path_1.default.join(i,"project.miniapp.json");try{const e=fs_extra_1.default.readJsonSync(L);let{theme:i}=t;t.theme||(i="Dark"),e.__splashscreenTheme=i,fs_extra_1.default.writeJSONSync(L,e)}catch(e){throw new Error(`ReadWriteJsonFailed projectMiniappJsonCacheFilePath: ${L},error ${e.message}`)}const M=c["mini-plugin"];M&&Array.isArray(M.ios)&&M.ios.forEach(e=>{!0===e.open&&e.resourcePath&&d(`mini-plugin ios ${e.pluginId}:${e.resourcePath}`,e.resourcePath)});return{projectMiniappJson:_,projectConfigJson:m,appJson:b,privacyJson:w,privacyContentViewImage:I,privacyCancelButtonImage:x,privacyConfirmButtonImage:j,icons:E,splashScreen:O,p12:$,profile:T,tpnsProfile:k,i18nJson:F,resourcePath:d("ios resourcePath",c.resourcePath,!0)}}async codesignIOSApp(e,i){const{projectPath:t,demoIpaPath:o,opts:n}=e,s=await(0,codesign_1.codesignAndExport)(t,o,e.miniappCacheDir||"",n,i,e.isUsingTpush,!1,!0);if(!0!==s.success)throw new Error("Build ipa failed:"+(s.errMsg||"codesignAndExport failed"))}async packIOSCloudBuildMaterial(e,i){i.progress("start uploadProjectAllMaterial");const{projectPath:t,matrialDistPath:o,theme:n}=e;await this.genProjectMaterialMap(t,o,e,i);i.progress("packIOSCloudBuildMaterial done")}async initUSBConnectionProcess(e,i){await(0,usbProcess_1.startUSBManagerProcess)(e,i)&&i.progress("Init USB Process Successfully")}launchSimulator(e,i){let t;try{t=JSON.parse(child_process.execFileSync("xcrun",["simctl","list","--json","devices"],{encoding:"utf8",env:(0,env_1.getProcessEnv)()}))}catch(e){throw new Error("Could not get the simulator list from Xcode. Please open Xcode and try running project directly from there to resolve the remaining issues."+e.message)}const o=["iPhone 13","iPhone 12","iPhone 11"].reduce((e,i)=>e||deviceUtils.findMatchingSimulator(t,{device:i}),deviceUtils.findMatchingSimulator(t,e));if(!o)throw new Error("No simulator available with "+(e.device?`name "${e.device}"`:`udid "${e.udid}"`));const n=child_process.execFileSync("xcode-select",["-p"],{encoding:"utf8",env:(0,env_1.getProcessEnv)()}).trim();if(child_process.execFileSync("open",[n+"/Applications/Simulator.app","--args","-CurrentDeviceUDID",o.udid],{env:(0,env_1.getProcessEnv)()}),!o.booted){const e=deviceUtils.formattedDeviceName(o);i.progress("Launching "+e),child_process.spawnSync("xcrun",["simctl","boot",o.udid],{env:(0,env_1.getProcessEnv)()})}return o}async runOnSimulatorCloud(e,i,t){const{udid:o}=i,n=this.launchSimulator({udid:o},t);await this.installAppOnSimulator(n,e,t),await this.launchAppOnSimulator(n,e,t)}async runOnSimulatorLocal(e,i,t,o){const n=this.launchSimulator(t,o),{appPath:s}=await this.buildProjectApp(e,{udid:n.udid,scheme:i},o);await this.installAppOnSimulator(n,s,o),await this.launchAppOnSimulator(n,s,o)}async runOnDeviceLocal(e,i,t,o){const{appPath:n}=await this.buildProjectApp(e,{udid:t.udid,scheme:i},o);if("catalyst"===t.type){child_process.spawn(`${n}/${i}`,[],{detached:!0,stdio:"ignore",env:(0,env_1.getProcessEnv)()}).unref()}else{const e=["--bundle",n,"--id",t.udid,"--justlaunch"];o.progress("Installing and launching your app on "+t.name);const i=path_1.default.join(__dirname,"../../../vendor/ios-deploy/ios-deploy");await(0,cp_1.spawnSync)(i,e,{},o)}return o.progress("Install successfully the app to the device.")}buildProjectApp(e,i,t){return new Promise((o,n)=>{const{scheme:s,udid:r}=i,a=[e.isWorkspace?"-workspace":"-project",e.name,"-scheme",s];let c;r&&a.push("-destination","id="+r),t.progress(`Building (using "xcodebuild ${a.join(" ")}")`),this.xcbeautifyAvailable()?c=child_process.spawn("xcbeautify",[],{stdio:["pipe",process.stdout,process.stderr],env:(0,env_1.getProcessEnv)()}):this.xcprettyAvailable()&&(c=child_process.spawn("xcpretty",[],{stdio:["pipe",process.stdout,process.stderr],env:(0,env_1.getProcessEnv)()}));const l=child_process.spawn("xcodebuild",a,{env:(0,env_1.getProcessEnv)()});let d="",u="";l.stdout.on("data",e=>{const i=e.toString();t.progress(i),d+=i,c&&c.stdin.write(e)}),l.stderr.on("data",e=>{const i=e.toString();u+=i,t.progress(i)}),l.on("close",i=>{if(c&&c.stdin.end(),0!==i)return void n(new Error(` Failed to build iOS project.\n We ran "xcodebuild" command but it exited with error code ${i}. To debug build\n logs further, consider building your app with Xcode.app, by opening\n ${e.name}.\n ${c?void 0:`${d}\n${u}`}\n `));let r;try{r=this.getBuildInfo(e,d,s)}catch(e){n(e)}t.progress("Successfully built the app"),o(r)})})}async installAppOnSimulator(e,i,t){const o=["simctl","install",e.udid,i];await(0,cp_1.spawnSync)("xcrun",o,{},t)}async launchAppOnSimulator(e,i,t){const o=this.getBundleId(i),n=["simctl","launch",e.udid,o];await(0,cp_1.spawnSync)("xcrun",n,{},t),t.progress("Successfully launched the app on the simulator")}async buildProjectArchive(e,i,t){const{output:o,scheme:n,udid:s}=i,r=path_1.default.join(o,"./app"),{sourceDir:a}=e;fs_extra_1.default.ensureDirSync(path_1.default.dirname(r));const c=["archive",e.isWorkspace?"-workspace":"-project",e.name,"-scheme",n,"-archivePath",r];s&&c.push("-destination","id="+s);try{if(await(0,cp_1.spawnSync)("xcodebuild",c,{cwd:a},t),!fs_extra_1.default.existsSync(r+".xcarchive"))throw new Error(`Failed to build iOS project.\n ${r+".xcarchive"} does not found\n `);return t.progress(`Successfully archive the app: ${r}.xcarchive`),r+".xcarchive"}catch(i){throw new Error(`Failed to build iOS project. To debug build\n logs further, consider building your app with Xcode.app, by opening\n ${e.name}.\n `)}}async exportArchive(e,i,t,o){const n=path_1.default.join(t.output,"ipa");fs_extra_1.default.ensureDirSync(n),fs_extra_1.default.emptyDirSync(n);const{exportOptionPlistPath:s}=t;if(!s)throw new Error("build ios ipa require exportOptionPlistPath in project.miniapp.json");let r="";r=path_1.default.isAbsolute(s)?s:path_1.default.join(t.projectPath,s);const a=["-exportArchive","-archivePath",i,"-exportOptionsPlist",r,"-exportPath",n];try{await(0,cp_1.spawnSync)("xcodebuild",a,{cwd:e.sourceDir},o)}catch(i){throw new Error(`To debug build\n logs further, consider building your app with Xcode.app, by opening\n ${e.name}.\n `)}return fs_extra_1.default.removeSync(i),n}getTargetPaths(e){const i=JSON.parse(e);for(const e in i){if("app"===i[e].buildSettings.WRAPPER_EXTENSION)return{targetBuildDir:i[e].buildSettings.TARGET_BUILD_DIR,executableFolderPath:i[e].buildSettings.EXECUTABLE_FOLDER_PATH}}return{}}getBuildInfo(e,i,t){const o=this.getPlatformName(i),n=[e.isWorkspace?"-workspace":"-project",e.name,"-scheme",t,"-sdk",o,"-showBuildSettings","-json"].join(" "),s=child_process.execSync("xcodebuild "+n,{encoding:"utf8",cwd:e.sourceDir,env:(0,env_1.getProcessEnv)()}),r=this.getBuildProductDir(i),{executableFolderPath:a}=this.getTargetPaths(s);if(!a)throw new Error("Failed to get the app name.");return{sdk:o,appPath:`${r}/${a}`}}getPlatformName(e){const i=/export PLATFORM_NAME\\?="?(\w+)"?$/m.exec(e);if(!i)throw new Error("Couldn't find PLATFORM_NAME in xcodebuild output.");return i[1]}getBuildProductDir(e){const i=/export BUILT_PRODUCTS_DIR\\?="?(.+)"?$/m.exec(e);if(!i)throw new Error("Couldn't find BUILT_PRODUCTS_DIR in xcodebuild output.");return i[1]}xcbeautifyAvailable(){try{child_process.execSync("xcbeautify --version",{stdio:[0,"pipe","ignore"],env:(0,env_1.getProcessEnv)()})}catch(e){return!1}return!0}xcprettyAvailable(){try{child_process.execSync("xcpretty --version",{stdio:[0,"pipe","ignore"],env:(0,env_1.getProcessEnv)()})}catch(e){return!1}return!0}async buildPlugin(e,i){const{pluginId:t,projectPath:o,buildShellPath:n}=e;i.progress("start build native plugin...");try{const e=[o,t];fs_extra_1.default.chmodSync(n,"777"),buildIOSPluginTask[t]?(i.message("error","存在未结束的插件构建任务,需等待构建结束..."),await buildIOSPluginTask[t].getResult(!0)):(buildIOSPluginTask[t]=new singletontask_1.SingletonTask(cp_1.spawnSyncExecShell.bind(null,n,e,{},i)),await buildIOSPluginTask[t].getResult(!0),buildIOSPluginTask[t]=void 0)}catch(e){throw buildIOSPluginTask[t]=void 0,new Error("build plugin failed: "+e)}}async writeI18NInfoFile(e,i,t){Object.keys(i).forEach(o=>{if("base"===o)return;let n="";Object.keys(t).forEach(e=>{var s,r,a,c;(null===(r=null===(s=i[o])||void 0===s?void 0:s.ios)||void 0===r?void 0:r[t[e]])&&(n+=`${e} = "${null===(c=null===(a=i[o])||void 0===a?void 0:a.ios)||void 0===c?void 0:c[t[e]]}";\n`)}),n&&(fs_extra_1.default.ensureDirSync(path_1.default.join(e,o+".lproj")),fs_extra_1.default.writeFileSync(path_1.default.join(e,o+".lproj/InfoPlist.strings"),n))})}}exports.IOSUtils=IOSUtils;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseProject=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),stream_1=require("stream"),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),tools_1=require("../utils/tools"),waitable_1=tslib_1.__importDefault(require("../utils/waitable"));class BaseProject extends waitable_1.default{constructor(){super(...arguments),this._projectPath="",this._injectedPages=[],this._projectArchitecture="miniProgram",this._type="miniProgram",this._privateKey="",this.ignores=[],this.setting={},this._dirSet=new Set,this._fileSet=new Set,this.event=new stream_1.EventEmitter}get projectPath(){return this._projectPath}get injectedPages(){return this._injectedPages}get projectArchitecture(){return this._projectArchitecture}get srcPath(){let t="";return"miniProgramPlugin"!==this._type&&"miniGamePlugin"!==this._type||(t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))),t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.miniprogramRoot||"")),(this._projectPath.startsWith("//")||this._projectPath.startsWith("\\\\"))&&(t.startsWith("//")||(t="/"+t)),t}get pluginSrcPath(){return(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))}get type(){return this._type}set type(t){this._type=t}get appid(){return this._appid}set appid(t){this._appid=t}get privateKey(){return this._privateKey}set privateKey(t){this._privateKey=t}get miniprogramRoot(){return this._miniprogramRoot||""}set miniprogramRoot(t){this._miniprogramRoot=t}get pluginRoot(){return this._pluginRoot}set pluginRoot(t){this._pluginRoot=t}get nameMappingFromDevtools(){return this._nameMappingFromDevtools}set nameMappingFromDevtools(t){this._nameMappingFromDevtools=t}async attr(){return this._attr}async ready(){await this.wait()}getProjectType(t,e){let i="";return i=(null==t?void 0:t.gameApp)?"miniGamePlugin"===e?"miniGamePlugin":"miniGame":e,i}getProjectConfig(){let t={};const e=path_1.default.join(this.projectPath,"project.config.json");if(fs_extra_1.default.existsSync(e))try{t=fs_extra_1.default.readJsonSync(e)}catch(t){throw new Error("project.config.json not exist")}return t}async serialize(){const{files:t,dirs:e}=this.getFilesAndDirs();return{projectPath:this.projectPath,appid:this.appid,attr:await this.attr(),type:this.type,projectArchitecture:this.projectArchitecture,miniprogramRoot:this.miniprogramRoot,pluginRoot:this.pluginRoot,files:t,dirs:e,setting:this.setting}}updateFiles(){this.updateFileAndDirs(...arguments)}updateOptions(t){this._appid=t.appid,this._injectedPages=t.injectedPages||[],this._attr=t.attr,this._type=this.getProjectType(t.attr,t.compileType),this._miniprogramRoot=t.miniprogramRoot,this._pluginRoot=t.pluginRoot,this._projectArchitecture=t.projectArchitecture,this.packOptions=t.packOptions||{ignore:[],include:[]},this.event.emit("optionsChange",t)}cacheDirName(t,e){t.has(e)||(t.add(e),this.cacheDirName(t,path_1.default.posix.dirname(e)))}deleteDirOrFileOfSet(t,e,i){if(t.has(i)){t.delete(i);const r=i+"/",s=Array.from(t);for(const e of s)e.startsWith(r)&&t.delete(e);const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseProject=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),stream_1=require("stream"),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),tools_1=require("../utils/tools"),waitable_1=tslib_1.__importDefault(require("../utils/waitable")),rootConfig={qcloudRoot:"腾讯云 wafer 方案目录",miniprogramRoot:"小程序代码的目录",srcMiniprogramRoot:"小程序源码的目录",pluginRoot:"插件目录",cloudfunctionRoot:"云函数目录",cloudfunctionTemplateRoot:"云函数本地调试模板目录",cloudcontainerRoot:"云容器目录",cloudbaseRoot:"cloudbaseRoot",jsserverRoot:"小游戏 jsserver 目录",testRoot:"自动化测试脚本录制的存放目录"};class BaseProject extends waitable_1.default{constructor(){super(...arguments),this._projectPath="",this._injectedPages=[],this._projectArchitecture="miniProgram",this._type="miniProgram",this._privateKey="",this.ignores=[],this.setting={},this._dirSet=new Set,this._fileSet=new Set,this.event=new stream_1.EventEmitter,this.normalizeRootPath=(t="")=>t&&"/"!==t?(t=(0,tools_1.normalizePath)(t+"/")).replace(/\.\.\//g,"").replace(/^\//,"").replace(/^\.\//,""):""}get projectPath(){return this._projectPath}get injectedPages(){return this._injectedPages}get projectArchitecture(){return this._projectArchitecture}get srcPath(){let t="";return"miniProgramPlugin"!==this._type&&"miniGamePlugin"!==this._type||(t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))),t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.miniprogramRoot||"")),(this._projectPath.startsWith("//")||this._projectPath.startsWith("\\\\"))&&(t.startsWith("//")||(t="/"+t)),t}get pluginSrcPath(){return(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))}get type(){return this._type}set type(t){this._type=t}get appid(){return this._appid}set appid(t){this._appid=t}get privateKey(){return this._privateKey}set privateKey(t){this._privateKey=t}get miniprogramRoot(){return this._miniprogramRoot||""}set miniprogramRoot(t){this._miniprogramRoot=t}get pluginRoot(){return this._pluginRoot}set pluginRoot(t){this._pluginRoot=t}get nameMappingFromDevtools(){return this._nameMappingFromDevtools}set nameMappingFromDevtools(t){this._nameMappingFromDevtools=t}async attr(){return this._attr}async ready(){await this.wait()}getProjectType(t,e){let i="";return i=(null==t?void 0:t.gameApp)?"miniGamePlugin"===e?"miniGamePlugin":"miniGame":e,i}getProjectConfig(){let t={};const e=path_1.default.join(this.projectPath,"project.config.json");if(fs_extra_1.default.existsSync(e))try{t=fs_extra_1.default.readJsonSync(e)}catch(t){throw new Error("project.config.json not exist")}for(const e in rootConfig)"string"==typeof t[e]&&(t[e]=this.normalizeRootPath(t[e]));return t}async serialize(){const{files:t,dirs:e}=this.getFilesAndDirs();return{projectPath:this.projectPath,appid:this.appid,attr:await this.attr(),type:this.type,projectArchitecture:this.projectArchitecture,miniprogramRoot:this.miniprogramRoot,pluginRoot:this.pluginRoot,files:t,dirs:e,setting:this.setting}}updateFiles(){this.updateFileAndDirs(...arguments)}updateOptions(t){this._appid=t.appid,this._injectedPages=t.injectedPages||[],this._attr=t.attr,this._type=this.getProjectType(t.attr,t.compileType),this._miniprogramRoot=t.miniprogramRoot,this._pluginRoot=t.pluginRoot,this._projectArchitecture=t.projectArchitecture,this.packOptions=t.packOptions||{ignore:[],include:[]},this.event.emit("optionsChange",t)}cacheDirName(t,e){t.has(e)||(t.add(e),this.cacheDirName(t,path_1.default.posix.dirname(e)))}deleteDirOrFileOfSet(t,e,i){if(t.has(i)){t.delete(i);const r=i+"/",s=Array.from(t);for(const e of s)e.startsWith(r)&&t.delete(e);const o=Array.from(e);for(const t of o)t.startsWith(r)&&e.delete(t)}e.has(i)&&e.delete(i)}getTargetPath(t="",e=""){return(0,tools_1.normalizePath)((0,tools_1.joinPath)(t,e)).replace(/\/$/,"").replace(/^\//,"")}getFilesAndDirs(){return{files:Array.from(this._fileSet),dirs:Array.from(this._dirSet)}}exists(t="",e=""){const i=this.getTargetPath(t,e);if(!i.startsWith(t))return!1;if(this._fileSet.has(i)||this._dirSet.has(i))return!0;const r=(0,tools_1.normalizePath)((0,tools_1.joinPath)(this.projectPath,i));return fs_extra_1.default.existsSync(r)}stat(t="",e=""){if(!this.exists(t,e))return;const i=this.getTargetPath(t,e),r=path_1.default.join(this.projectPath,i);let s={};try{s=fs_extra_1.default.statSync(r)}catch(t){fs_extra_1.default.existsSync(r)||this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,i)}if(this._fileSet.has(i)){return{isFile:!0,isDirectory:!1,size:this.getFileSize(t,e),mtimeMs:s.mtimeMs||""}}return this._dirSet.has(i)?{isFile:!1,isDirectory:!0,size:0,mtimeMs:s.mtimeMs}:void 0}getAllFileInfo(t=""){const e=this.getFileList(t),i={};return e.forEach(t=>{i[t]=this.stat("",t)||{}}),i}getFileList(t="",e=""){return Array.from(this._fileSet).filter(i=>(!e||path_1.default.posix.extname(i)===e)&&!(t&&!i.startsWith(t)))}getSrcFile(t,e){t=t||"";const i=this.getTargetPath(t,e),r=(0,tools_1.normalizePath)((0,tools_1.joinPath)(this.projectPath,i));return fs_extra_1.default.readFileSync(r,null)}getFile(t,e){return this.getSrcFile(t,e)}getJson(t="",e=""){const i=this.getFile(t,e).toString("utf-8");try{return JSON.parse(i)}catch(i){throw new Error("JSON parse failed: "+this.getTargetPath(t,e))}}getFileSize(t="",e=""){const i=this.getFile(t,e);return i?i.byteLength:0}getExtAppid(){throw new Error("Method not implemented.")}async onFileChange(t,e){e=(0,tools_1.normalizePath)(e).replace(/\/$/,"").replace(/^\//,""),"add"===t&&(this.cacheDirName(this._dirSet,path_1.default.posix.dirname(e)),this._fileSet.add(e)),"addDir"===t&&this.cacheDirName(this._dirSet,e),"unlink"===t&&this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,e),"unlinkDir"===t&&this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,e),"change"===t&&this._fileSet.has(e),this.event.emit("fileChange",t,e)}clearCache(){}}exports.BaseProject=BaseProject;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CIProject=exports.getProjectAttr=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),fs_1=tslib_1.__importDefault(require("fs")),glob_1=tslib_1.__importDefault(require("glob")),config_1=require("../config/config"),locales_1=tslib_1.__importDefault(require("../utils/locales/locales")),error_1=require("../utils/error"),request_1=require("../utils/request"),types_1=require("../types"),tools_1=require("../utils/tools"),baseProject_1=require("./baseProject"),projectattr_1=require("../ci/projectattr"),miniappattr_1=require("../ci/miniappattr");var projectattr_2=require("../ci/projectattr");Object.defineProperty(exports,"getProjectAttr",{enumerable:!0,get:function(){return projectattr_2.getProjectAttr}});class CIProject extends baseProject_1.BaseProject{constructor(t){super();const{type:e,projectPath:r,ignores:i,privateKey:o="",privateKeyPath:s=""}=t;let a=t.appid;if(!r)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("projectPath"),config_1.PARAM_ERROR);this._projectPath=path_1.default.isAbsolute(r)?(0,tools_1.normalizePath)(r):(0,tools_1.normalizePath)(path_1.default.join(process.cwd(),r));const p=this.getProjectConfig();if(!a){if(!p.appid)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("appid"),config_1.PARAM_ERROR);a=p.appid}if(o)this._privateKey=o;else{if(!s)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("privateKeyPath"),config_1.PARAM_ERROR);try{this._privateKey=fs_1.default.readFileSync(s).toString("utf8")}catch(t){throw new error_1.CodeError(t.toString(),config_1.PARAM_ERROR)}}this._projectArchitecture=p.projectArchitecture||"miniProgram",this._miniprogramRoot=p.miniprogramRoot||"",this._pluginRoot=p.pluginRoot||"",this._appid=a,this._type=e||types_1.EProjectType.miniProgram,this.ignores=i||[],this.setting=p.setting||{},this._project=t,this._targetPlatform=t.targetPlatform||"mini-weixin",this.init()}get project(){return this._project}async init(){(0,request_1.initGlobalProxy)(),this.updateFileAndDirs()}updateFileAndDirs(){const t=glob_1.default.sync("**",{nodir:!1,ignore:[...(0,config_1.getDefaultIgnores)(this),...this.ignores],nosort:!0,strict:!1,silent:!0,cwd:this.projectPath,absolute:!1,mark:!0,dot:!0});for(const e of t){const t=e.replace(/\\/g,path_1.default.posix.sep),r=fs_1.default.statSync(path_1.default.posix.join(this.projectPath,e));r.isDirectory()&&this.cacheDirName(this._dirSet,t.replace(/\/$/,"")),r.isFile()&&(this._fileSet.add(t),this.cacheDirName(this._dirSet,path_1.default.posix.dirname(t)))}}async attr(){return"function"==typeof this._project.attr?await this._project.attr():(this._attr||(this._attr=await(0,projectattr_1.getProjectAttr)(this._privateKey,this._appid)),this._attr)}async getExtAppid(){if(this._extAppid)return this._extAppid;if(null!==this._extAppid)try{const t=await this.getProjectConfig(),{miniprogramRoot:e=""}=t,r=this.getFile(e,"ext.json"),i=JSON.parse(r.toString("utf-8"));return i.extEnable&&i.extAppid?this._extAppid=i.extAppid:this._extAppid=null,this._extAppid}catch(t){this._extAppid=null}}isMiniappProject(){return"multiPlatform"===this._projectArchitecture}async miniappAttr(){return this.isMiniappProject()?this._miniappAttr?Promise.resolve(this._miniappAttr):(this._miniappAttr=await(0,miniappattr_1.getMiniappAttr)(this._privateKey,this._appid),this._miniappAttr):Promise.resolve({})}async serialize(){return Object.assign(Object.assign({},await super.serialize()),{targetPlatform:this._targetPlatform,targetPlatformDefines:{}})}}exports.CIProject=CIProject;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CIProject=exports.getProjectAttr=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),fs_1=tslib_1.__importDefault(require("fs")),glob_1=tslib_1.__importDefault(require("glob")),config_1=require("../config/config"),locales_1=tslib_1.__importDefault(require("../utils/locales/locales")),error_1=require("../utils/error"),request_1=require("../utils/request"),types_1=require("../types"),tools_1=require("../utils/tools"),baseProject_1=require("./baseProject"),projectattr_1=require("../ci/projectattr"),miniappattr_1=require("../ci/miniappattr");var projectattr_2=require("../ci/projectattr");Object.defineProperty(exports,"getProjectAttr",{enumerable:!0,get:function(){return projectattr_2.getProjectAttr}});class CIProject extends baseProject_1.BaseProject{constructor(t){super();const{type:e,projectPath:r,ignores:i,privateKey:o="",privateKeyPath:s=""}=t;let a=t.appid;if(!r)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("projectPath"),config_1.PARAM_ERROR);this._projectPath=path_1.default.isAbsolute(r)?(0,tools_1.normalizePath)(r):(0,tools_1.normalizePath)(path_1.default.join(process.cwd(),r));const p=this.getProjectConfig();if(!a){if(!p.appid)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("appid"),config_1.PARAM_ERROR);a=p.appid}if(o)this._privateKey=o;else{if(!s)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("privateKeyPath"),config_1.PARAM_ERROR);try{this._privateKey=fs_1.default.readFileSync(s).toString("utf8")}catch(t){throw new error_1.CodeError(t.toString(),config_1.PARAM_ERROR)}}this._projectArchitecture=p.projectArchitecture||"miniProgram",this._miniprogramRoot=p.miniprogramRoot||"",this._pluginRoot=p.pluginRoot||"",this._appid=a,this._type=e||types_1.EProjectType.miniProgram,this.ignores=i||[],this.setting=p.setting||{},this._project=t,this._targetPlatform=t.targetPlatform||"mini-weixin","object"==typeof p.packOptions&&(this.packOptions={ignore:Array.isArray(p.packOptions.ignore)?p.packOptions.ignore:[],include:Array.isArray(p.packOptions.include)?p.packOptions.include:[]}),this.init()}get project(){return this._project}async init(){(0,request_1.initGlobalProxy)(),this.updateFileAndDirs()}updateFileAndDirs(){const t=glob_1.default.sync("**",{nodir:!1,ignore:[...(0,config_1.getDefaultIgnores)(this),...this.ignores],nosort:!0,strict:!1,silent:!0,cwd:this.projectPath,absolute:!1,mark:!0,dot:!0});for(const e of t){const t=e.replace(/\\/g,path_1.default.posix.sep),r=fs_1.default.statSync(path_1.default.posix.join(this.projectPath,e));r.isDirectory()&&this.cacheDirName(this._dirSet,t.replace(/\/$/,"")),r.isFile()&&(this._fileSet.add(t),this.cacheDirName(this._dirSet,path_1.default.posix.dirname(t)))}}async attr(){return"function"==typeof this._project.attr?await this._project.attr():(this._attr||(this._attr=await(0,projectattr_1.getProjectAttr)(this._privateKey,this._appid)),this._attr)}async getExtAppid(){if(this._extAppid)return this._extAppid;if(null!==this._extAppid)try{const t=await this.getProjectConfig(),{miniprogramRoot:e=""}=t,r=this.getFile(e,"ext.json"),i=JSON.parse(r.toString("utf-8"));return i.extEnable&&i.extAppid?this._extAppid=i.extAppid:this._extAppid=null,this._extAppid}catch(t){this._extAppid=null}}isMiniappProject(){return"multiPlatform"===this._projectArchitecture}async miniappAttr(){return this.isMiniappProject()?this._miniappAttr?Promise.resolve(this._miniappAttr):(this._miniappAttr=await(0,miniappattr_1.getMiniappAttr)(this._privateKey,this._appid),this._miniappAttr):Promise.resolve({})}async serialize(){return Object.assign(Object.assign({},await super.serialize()),{targetPlatform:this._targetPlatform,targetPlatformDefines:{}})}}exports.CIProject=CIProject;
|
package/dist/utils/debug.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function shouldInspectCompiler(){var o;return!!(null===(o=global.localStorage)||void 0===o?void 0:o.getItem("inspectCompiler"))}function shouldRunInMainProcess(){var o;return!!(null===(o=global.localStorage)||void 0===o?void 0:o.getItem("compilerInMainProcess"))}function shouldNotRunInWorker(){var o;return!!(null===(o=global.localStorage)||void 0===o?void 0:o.getItem("compilerNotInWorker"))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shouldNotRunInWorker=exports.shouldRunInMainProcess=exports.shouldInspectCompiler=void 0,exports.shouldInspectCompiler=shouldInspectCompiler,exports.shouldRunInMainProcess=shouldRunInMainProcess,exports.shouldNotRunInWorker=shouldNotRunInWorker;
|
|
1
|
+
"use strict";function shouldInspectCompiler(){var o;return!!global.__MINIPROGRAM_CI_TEST__||!!(null===(o=global.localStorage)||void 0===o?void 0:o.getItem("inspectCompiler"))}function shouldRunInMainProcess(){var o;return!!(null===(o=global.localStorage)||void 0===o?void 0:o.getItem("compilerInMainProcess"))}function shouldNotRunInWorker(){var o;return!!(null===(o=global.localStorage)||void 0===o?void 0:o.getItem("compilerNotInWorker"))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shouldNotRunInWorker=exports.shouldRunInMainProcess=exports.shouldInspectCompiler=void 0,exports.shouldInspectCompiler=shouldInspectCompiler,exports.shouldRunInMainProcess=shouldRunInMainProcess,exports.shouldNotRunInWorker=shouldNotRunInWorker;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubProcessProxy=void 0;const tslib_1=require("tslib"),child_process_1=require("child_process"),path_1=tslib_1.__importDefault(require("path")),customError_1=require("../customError"),singletontask_1=require("../singletontask"),debug_1=require("../debug");function performanceMark(s,e){}const PROCESS_READY_TIMEOUT=2e4;class SubProcessProxy{constructor(s,e,t,r,o=8891,i){this.project=s,this.entryPath=e,this.passData=t,this.initOptions=r,this.inspectPort=o,this.progressUpdate=i,this.taskMap=new Map,this.taskId=0,this.init=async()=>{performanceMark("process init"),this.process=await this.forkProcess(),performanceMark("process init",!0)},this.onMessage=s=>{var e,t;if(this._cpPromise&&("ready"===s.type&&(clearTimeout(this._cpPromise.timer),performanceMark("process ready"),null===(e=this._cpPromise)||void 0===e||e.resolve()),"noReady"===s.type&&(performanceMark("process not ready"),this._cpPromise.reject(new Error(s.error.message)))),"progress"===s.type){const e=this.taskMap.get(s.taskId);(null==e?void 0:e.progressUpdate)&&e.progressUpdate(s.id,s.status,s.message)}if("log"===s.type&&(null===(t=this.progressUpdate)||void 0===t||t.call(this,s.id||"",s.status,s.text)),"response"===s.type){const{id:e,data:t,error:r}=s;r?this.onResponse(e,void 0,r):this.onResponse(e,t,void 0)}}}async ready(){var s;return this._checkReadyTask||(this._checkReadyTask=new singletontask_1.SingletonTask(this.init)),await(null===(s=this._checkReadyTask)||void 0===s?void 0:s.getResult(!0))}async sendProcessMessage(s){await this.ready(),this.process.send(s)}destroy(){var s;null===(s=this.process)||void 0===s||s.kill("SIGTERM"),this.process=void 0,this._checkReadyTask=void 0}async forkProcess(){const s=await this.project.serialize(),e={type:"init",data:{passData:this.passData,projectInfo:s,options:this.initOptions}};if((0,debug_1.shouldRunInMainProcess)()){const s=require("../../modules/corecompiler/processHandler");return await s.initHandler(e),s.onMessage(this.onMessage),{send:e=>{(0,debug_1.shouldRunInMainProcess)()&&s.messageHandler(e)},kill:e=>(s.destroy(),!0)}}const t=this.entryPath,r={stdio:["pipe","pipe","pipe","ipc"],cwd:this.project.projectPath,env:Object.assign(Object.assign({},process.env),{cpprocessEnv:"childprocess",nativeProcess:"1",timeout:global.TEST_COMPILER_PROCESS_TIMEOUT})};(0,debug_1.shouldInspectCompiler)()&&(r.execArgv=["--inspect-brk="+this.inspectPort]);const o=process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname;if(r.env.isDevtools=o,o){let s=path_1.default.join(path_1.default.dirname(process.execPath),"node");"darwin"!==process.platform&&(s+=".exe"),r.execPath=s}return performanceMark("fork process"),new Promise((s,i)=>{const a=(0,child_process_1.fork)(t,["--expose-gc"],r),n=setTimeout(()=>{this.destroy(),i(new Error("fork process timeout"))},2e4);return this._cpPromise={timer:n,resolve:()=>{s(a)},reject:i},a.stdout.setEncoding("utf8"),a.stdout.on("data",s=>{console.log("child process stdout: "+s)}),a.stderr.on("data",s=>{console.error("child process stderr: "+s)}),a.on("exit",(s,e)=>{this.process=void 0,this._checkReadyTask=void 0,o&&console.error(`child process exit: code(${s}), signal(${e})`),0!==s&&i(new Error(`native child process exit: code(${s}), signal(${e})`))}),a.on("message",this.onMessage),a.unref(),this.taskId+=1,a.send(e),a})}onResponse(s,e,t){const r=this.taskMap.get(s);this.taskMap.delete(s),r?t?(t=new customError_1.CustomError(t),r.reject(t)):r.resolve(e):console.error(`child process task: ${s} not found`)}async sendEvent(s,e){this.sendProcessMessage({type:"event",name:s,data:e})}async runTask(s,e,t){return new Promise((r,o)=>{const i={name:s,data:e,resolve:r,reject:o,progressUpdate:t};this.taskId+=1,this.taskMap.set(this.taskId,i),this.sendProcessMessage({type:"request",id:this.taskId,name:s,data:e})})}}exports.SubProcessProxy=SubProcessProxy;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubProcessProxy=void 0;const tslib_1=require("tslib"),child_process_1=require("child_process"),path_1=tslib_1.__importDefault(require("path")),customError_1=require("../customError"),singletontask_1=require("../singletontask"),debug_1=require("../debug");function performanceMark(s,e){}const PROCESS_READY_TIMEOUT=2e4;class SubProcessProxy{constructor(s,e,t,r,o=8891,i){this.project=s,this.entryPath=e,this.passData=t,this.initOptions=r,this.inspectPort=o,this.progressUpdate=i,this.taskMap=new Map,this.taskId=0,this.init=async()=>{performanceMark("process init"),this.process=await this.forkProcess(),performanceMark("process init",!0)},this.onMessage=s=>{var e,t;if(this._cpPromise&&("ready"===s.type&&(clearTimeout(this._cpPromise.timer),performanceMark("process ready"),null===(e=this._cpPromise)||void 0===e||e.resolve()),"noReady"===s.type&&(performanceMark("process not ready"),this._cpPromise.reject(new Error(s.error.message)))),"progress"===s.type){const e=this.taskMap.get(s.taskId);(null==e?void 0:e.progressUpdate)&&e.progressUpdate(s.id,s.status,s.message)}if("log"===s.type&&(null===(t=this.progressUpdate)||void 0===t||t.call(this,s.id||"",s.status,s.text)),"response"===s.type){const{id:e,data:t,error:r}=s;r?this.onResponse(e,void 0,r):this.onResponse(e,t,void 0)}}}async ready(){var s;return this._checkReadyTask||(this._checkReadyTask=new singletontask_1.SingletonTask(this.init)),await(null===(s=this._checkReadyTask)||void 0===s?void 0:s.getResult(!0))}async sendProcessMessage(s){await this.ready(),this.process.send(s)}destroy(){var s;null===(s=this.process)||void 0===s||s.kill("SIGTERM"),this.process=void 0,this._checkReadyTask=void 0}async forkProcess(){const s=await this.project.serialize(),e={type:"init",data:{passData:this.passData,projectInfo:s,options:this.initOptions}};if((0,debug_1.shouldRunInMainProcess)()){const s=require("../../modules/corecompiler/processHandler");return await s.initHandler(e),s.onMessage(this.onMessage),{send:e=>{(0,debug_1.shouldRunInMainProcess)()&&s.messageHandler(e)},kill:e=>(s.destroy(),!0)}}const t=this.entryPath,r={stdio:["pipe","pipe","pipe","ipc"],cwd:this.project.projectPath,env:Object.assign(Object.assign({},process.env),{cpprocessEnv:"childprocess",nativeProcess:"1",timeout:global.TEST_COMPILER_PROCESS_TIMEOUT})};(0,debug_1.shouldInspectCompiler)()&&(r.execArgv=["--inspect-brk="+this.inspectPort],r.env.__MINIPROGRAM_CI_TEST__="true");const o=process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname;if(r.env.isDevtools=o,o){let s=path_1.default.join(path_1.default.dirname(process.execPath),"node");"darwin"!==process.platform&&(s+=".exe"),r.execPath=s}return performanceMark("fork process"),new Promise((s,i)=>{const a=(0,child_process_1.fork)(t,["--expose-gc"],r),n=setTimeout(()=>{this.destroy(),i(new Error("fork process timeout"))},2e4);return this._cpPromise={timer:n,resolve:()=>{s(a)},reject:i},a.stdout.setEncoding("utf8"),a.stdout.on("data",s=>{console.log("child process stdout: "+s)}),a.stderr.on("data",s=>{console.error("child process stderr: "+s)}),a.on("exit",(s,e)=>{this.process=void 0,this._checkReadyTask=void 0,o&&console.error(`child process exit: code(${s}), signal(${e})`),0!==s&&i(new Error(`native child process exit: code(${s}), signal(${e})`))}),a.on("message",this.onMessage),a.unref(),this.taskId+=1,a.send(e),a})}onResponse(s,e,t){const r=this.taskMap.get(s);this.taskMap.delete(s),r?t?(t=new customError_1.CustomError(t),r.reject(t)):r.resolve(e):console.error(`child process task: ${s} not found`)}async sendEvent(s,e){this.sendProcessMessage({type:"event",name:s,data:e})}async runTask(s,e,t){return new Promise((r,o)=>{const i={name:s,data:e,resolve:r,reject:o,progressUpdate:t};this.taskId+=1,this.taskMap.set(this.taskId,i),this.sendProcessMessage({type:"request",id:this.taskId,name:s,data:e})})}}exports.SubProcessProxy=SubProcessProxy;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "miniprogram-ci",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.10",
|
|
4
4
|
"description": "Module that build miniprogram project for web or app extracted from WeChatDevtools.",
|
|
5
5
|
"homepage": "https://developers.weixin.qq.com/community/homepage",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"prebuild-ci": "npm run buildandroidtoolkit",
|
|
18
18
|
"build-ci": "rm -rf dist && rm -rf ci-src && npm run build && gulp pre-build-ci && rm -rf dist && gulp removeForCi && npm run ci-tsc && gulp build-ci",
|
|
19
19
|
"ci-tsc": "tsc -p './tsconfig_ci.json'",
|
|
20
|
+
"ci-tsc-dev": "tsc -p './tsconfig_ci_dev.json'",
|
|
20
21
|
"bb": "npm run init && gulp inc-version && tsc && gulp build && node ./task/afterbuild.js ",
|
|
21
22
|
"bbwin": "gulp inc-version && tsc && gulp build && node ./task/afterbuild.js ",
|
|
22
23
|
"test": "nyc --reporter=text npm run mocha && npm run jest",
|