UNPKG

22.6 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.Packager = void 0;
7
8function _builderUtil() {
9 const data = require("builder-util");
10
11 _builderUtil = function () {
12 return data;
13 };
14
15 return data;
16}
17
18function _builderUtilRuntime() {
19 const data = require("builder-util-runtime");
20
21 _builderUtilRuntime = function () {
22 return data;
23 };
24
25 return data;
26}
27
28function _promise() {
29 const data = require("builder-util/out/promise");
30
31 _promise = function () {
32 return data;
33 };
34
35 return data;
36}
37
38function _events() {
39 const data = require("events");
40
41 _events = function () {
42 return data;
43 };
44
45 return data;
46}
47
48function _fsExtra() {
49 const data = require("fs-extra");
50
51 _fsExtra = function () {
52 return data;
53 };
54
55 return data;
56}
57
58function _isCi() {
59 const data = _interopRequireDefault(require("is-ci"));
60
61 _isCi = function () {
62 return data;
63 };
64
65 return data;
66}
67
68function _lazyVal() {
69 const data = require("lazy-val");
70
71 _lazyVal = function () {
72 return data;
73 };
74
75 return data;
76}
77
78var path = _interopRequireWildcard(require("path"));
79
80function _arch() {
81 const data = require("builder-util/out/arch");
82
83 _arch = function () {
84 return data;
85 };
86
87 return data;
88}
89
90function _appInfo() {
91 const data = require("./appInfo");
92
93 _appInfo = function () {
94 return data;
95 };
96
97 return data;
98}
99
100function _asar() {
101 const data = require("./asar/asar");
102
103 _asar = function () {
104 return data;
105 };
106
107 return data;
108}
109
110function _ElectronFramework() {
111 const data = require("./electron/ElectronFramework");
112
113 _ElectronFramework = function () {
114 return data;
115 };
116
117 return data;
118}
119
120function _LibUiFramework() {
121 const data = require("./frameworks/LibUiFramework");
122
123 _LibUiFramework = function () {
124 return data;
125 };
126
127 return data;
128}
129
130function _index() {
131 const data = require("./index");
132
133 _index = function () {
134 return data;
135 };
136
137 return data;
138}
139
140function _platformPackager() {
141 const data = require("./platformPackager");
142
143 _platformPackager = function () {
144 return data;
145 };
146
147 return data;
148}
149
150function _ProtonFramework() {
151 const data = require("./ProtonFramework");
152
153 _ProtonFramework = function () {
154 return data;
155 };
156
157 return data;
158}
159
160function _targetFactory() {
161 const data = require("./targets/targetFactory");
162
163 _targetFactory = function () {
164 return data;
165 };
166
167 return data;
168}
169
170function _config() {
171 const data = require("./util/config");
172
173 _config = function () {
174 return data;
175 };
176
177 return data;
178}
179
180function _macroExpander() {
181 const data = require("./util/macroExpander");
182
183 _macroExpander = function () {
184 return data;
185 };
186
187 return data;
188}
189
190function _packageDependencies() {
191 const data = require("./util/packageDependencies");
192
193 _packageDependencies = function () {
194 return data;
195 };
196
197 return data;
198}
199
200function _packageMetadata() {
201 const data = require("./util/packageMetadata");
202
203 _packageMetadata = function () {
204 return data;
205 };
206
207 return data;
208}
209
210function _repositoryInfo() {
211 const data = require("./util/repositoryInfo");
212
213 _repositoryInfo = function () {
214 return data;
215 };
216
217 return data;
218}
219
220function _yarn() {
221 const data = require("./util/yarn");
222
223 _yarn = function () {
224 return data;
225 };
226
227 return data;
228}
229
230function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
231
232function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
233
234function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
235
236function addHandler(emitter, event, handler) {
237 emitter.on(event, handler);
238}
239
240async function createFrameworkInfo(configuration, packager) {
241 let framework = configuration.framework;
242
243 if (framework != null) {
244 framework = framework.toLowerCase();
245 }
246
247 let nodeVersion = configuration.nodeVersion;
248
249 if (framework === "electron" || framework == null) {
250 return await (0, _ElectronFramework().createElectronFrameworkSupport)(configuration, packager);
251 }
252
253 if (nodeVersion == null || nodeVersion === "current") {
254 nodeVersion = process.versions.node;
255 }
256
257 const distMacOsName = `${packager.appInfo.productFilename}.app`;
258 const isUseLaunchUi = configuration.launchUiVersion !== false;
259
260 if (framework === "proton" || framework === "proton-native") {
261 return new (_ProtonFramework().ProtonFramework)(nodeVersion, distMacOsName, isUseLaunchUi);
262 } else if (framework === "libui") {
263 return new (_LibUiFramework().LibUiFramework)(nodeVersion, distMacOsName, isUseLaunchUi);
264 } else {
265 throw new (_builderUtil().InvalidConfigurationError)(`Unknown framework: ${framework}`);
266 }
267}
268
269class Packager {
270 //noinspection JSUnusedGlobalSymbols
271 constructor(options, cancellationToken = new (_builderUtilRuntime().CancellationToken)()) {
272 this.cancellationToken = cancellationToken;
273 this._metadata = null;
274 this._nodeModulesHandledExternally = false;
275 this._isPrepackedAppAsar = false;
276 this._devMetadata = null;
277 this._configuration = null;
278 this.isTwoPackageJsonProjectLayoutUsed = false;
279 this.eventEmitter = new (_events().EventEmitter)();
280 this._appInfo = null;
281 this.tempDirManager = new (_builderUtil().TmpDir)("packager");
282 this._repositoryInfo = new (_lazyVal().Lazy)(() => (0, _repositoryInfo().getRepositoryInfo)(this.projectDir, this.metadata, this.devMetadata));
283 this.afterPackHandlers = [];
284 this.debugLogger = new (_builderUtil().DebugLogger)(_builderUtil().log.isDebugEnabled);
285 this.nodeDependencyInfo = new Map();
286
287 this.stageDirPathCustomizer = (target, packager, arch) => {
288 return path.join(target.outDir, `__${target.name}-${(0, _arch().getArtifactArchName)(arch, target.name)}`);
289 };
290
291 this._buildResourcesDir = null;
292 this._framework = null;
293 this.toDispose = [];
294
295 if ("devMetadata" in options) {
296 throw new (_builderUtil().InvalidConfigurationError)("devMetadata in the options is deprecated, please use config instead");
297 }
298
299 if ("extraMetadata" in options) {
300 throw new (_builderUtil().InvalidConfigurationError)("extraMetadata in the options is deprecated, please use config.extraMetadata instead");
301 }
302
303 const targets = options.targets || new Map();
304
305 if (options.targets == null) {
306 options.targets = targets;
307 }
308
309 function processTargets(platform, types) {
310 function commonArch(currentIfNotSpecified) {
311 const result = Array();
312 return result.length === 0 && currentIfNotSpecified ? [(0, _builderUtil().archFromString)(process.arch)] : result;
313 }
314
315 let archToType = targets.get(platform);
316
317 if (archToType == null) {
318 archToType = new Map();
319 targets.set(platform, archToType);
320 }
321
322 if (types.length === 0) {
323 for (const arch of commonArch(false)) {
324 archToType.set(arch, []);
325 }
326
327 return;
328 }
329
330 for (const type of types) {
331 const suffixPos = type.lastIndexOf(":");
332
333 if (suffixPos > 0) {
334 (0, _builderUtil().addValue)(archToType, (0, _builderUtil().archFromString)(type.substring(suffixPos + 1)), type.substring(0, suffixPos));
335 } else {
336 for (const arch of commonArch(true)) {
337 (0, _builderUtil().addValue)(archToType, arch, type);
338 }
339 }
340 }
341 }
342
343 if (options.mac != null) {
344 processTargets(_index().Platform.MAC, options.mac);
345 }
346
347 if (options.linux != null) {
348 processTargets(_index().Platform.LINUX, options.linux);
349 }
350
351 if (options.win != null) {
352 processTargets(_index().Platform.WINDOWS, options.win);
353 }
354
355 this.projectDir = options.projectDir == null ? process.cwd() : path.resolve(options.projectDir);
356 this._appDir = this.projectDir;
357 this.options = { ...options,
358 prepackaged: options.prepackaged == null ? null : path.resolve(this.projectDir, options.prepackaged)
359 };
360
361 try {
362 _builderUtil().log.info({
363 version: "22.10.3",
364 os: require("os").release()
365 }, "electron-builder");
366 } catch (e) {
367 // error in dev mode without babel
368 if (!(e instanceof ReferenceError)) {
369 throw e;
370 }
371 }
372 }
373
374 get appDir() {
375 return this._appDir;
376 }
377
378 get metadata() {
379 return this._metadata;
380 }
381
382 get areNodeModulesHandledExternally() {
383 return this._nodeModulesHandledExternally;
384 }
385
386 get isPrepackedAppAsar() {
387 return this._isPrepackedAppAsar;
388 }
389
390 get devMetadata() {
391 return this._devMetadata;
392 }
393
394 get config() {
395 return this._configuration;
396 }
397
398 get appInfo() {
399 return this._appInfo;
400 }
401
402 get repositoryInfo() {
403 return this._repositoryInfo.value;
404 }
405
406 getNodeDependencyInfo(platform) {
407 let key = "";
408 let excludedDependencies = null;
409
410 if (platform != null && this.framework.getExcludedDependencies != null) {
411 excludedDependencies = this.framework.getExcludedDependencies(platform);
412
413 if (excludedDependencies != null) {
414 key += `-${platform.name}`;
415 }
416 }
417
418 let result = this.nodeDependencyInfo.get(key);
419
420 if (result == null) {
421 result = (0, _packageDependencies().createLazyProductionDeps)(this.appDir, excludedDependencies);
422 this.nodeDependencyInfo.set(key, result);
423 }
424
425 return result;
426 }
427
428 get buildResourcesDir() {
429 let result = this._buildResourcesDir;
430
431 if (result == null) {
432 result = path.resolve(this.projectDir, this.relativeBuildResourcesDirname);
433 this._buildResourcesDir = result;
434 }
435
436 return result;
437 }
438
439 get relativeBuildResourcesDirname() {
440 return this.config.directories.buildResources;
441 }
442
443 get framework() {
444 return this._framework;
445 }
446
447 disposeOnBuildFinish(disposer) {
448 this.toDispose.push(disposer);
449 }
450
451 addAfterPackHandler(handler) {
452 this.afterPackHandlers.push(handler);
453 }
454
455 artifactCreated(handler) {
456 addHandler(this.eventEmitter, "artifactCreated", handler);
457 return this;
458 }
459
460 async callArtifactBuildStarted(event, logFields) {
461 _builderUtil().log.info(logFields || {
462 target: event.targetPresentableName,
463 arch: event.arch == null ? null : _builderUtil().Arch[event.arch],
464 file: _builderUtil().log.filePath(event.file)
465 }, "building");
466
467 const handler = (0, _platformPackager().resolveFunction)(this.config.artifactBuildStarted, "artifactBuildStarted");
468
469 if (handler != null) {
470 await Promise.resolve(handler(event));
471 }
472 }
473 /**
474 * Only for sub artifacts (update info), for main artifacts use `callArtifactBuildCompleted`.
475 */
476
477
478 dispatchArtifactCreated(event) {
479 this.eventEmitter.emit("artifactCreated", event);
480 }
481
482 async callArtifactBuildCompleted(event) {
483 this.dispatchArtifactCreated(event);
484 const handler = (0, _platformPackager().resolveFunction)(this.config.artifactBuildCompleted, "artifactBuildCompleted");
485
486 if (handler != null) {
487 await Promise.resolve(handler(event));
488 }
489 }
490
491 async callAppxManifestCreated(path) {
492 const handler = (0, _platformPackager().resolveFunction)(this.config.appxManifestCreated, "appxManifestCreated");
493
494 if (handler != null) {
495 await Promise.resolve(handler(path));
496 }
497 }
498
499 async build() {
500 let configPath = null;
501 let configFromOptions = this.options.config;
502
503 if (typeof configFromOptions === "string") {
504 // it is a path to config file
505 configPath = configFromOptions;
506 configFromOptions = null;
507 } else if (configFromOptions != null && configFromOptions.extends != null && configFromOptions.extends.includes(".")) {
508 configPath = configFromOptions.extends;
509 delete configFromOptions.extends;
510 }
511
512 const projectDir = this.projectDir;
513 const devPackageFile = path.join(projectDir, "package.json");
514 this._devMetadata = await (0, _promise().orNullIfFileNotExist)((0, _packageMetadata().readPackageJson)(devPackageFile));
515 const devMetadata = this.devMetadata;
516 const configuration = await (0, _config().getConfig)(projectDir, configPath, configFromOptions, new (_lazyVal().Lazy)(() => Promise.resolve(devMetadata)));
517
518 if (_builderUtil().log.isDebugEnabled) {
519 _builderUtil().log.debug({
520 config: getSafeEffectiveConfig(configuration)
521 }, "effective config");
522 }
523
524 this._appDir = await (0, _config().computeDefaultAppDirectory)(projectDir, configuration.directories.app);
525 this.isTwoPackageJsonProjectLayoutUsed = this._appDir !== projectDir;
526 const appPackageFile = this.isTwoPackageJsonProjectLayoutUsed ? path.join(this.appDir, "package.json") : devPackageFile; // tslint:disable:prefer-conditional-expression
527
528 if (this.devMetadata != null && !this.isTwoPackageJsonProjectLayoutUsed) {
529 this._metadata = this.devMetadata;
530 } else {
531 this._metadata = await this.readProjectMetadataIfTwoPackageStructureOrPrepacked(appPackageFile);
532 }
533
534 (0, _builderUtil().deepAssign)(this.metadata, configuration.extraMetadata);
535
536 if (this.isTwoPackageJsonProjectLayoutUsed) {
537 _builderUtil().log.debug({
538 devPackageFile,
539 appPackageFile
540 }, "two package.json structure is used");
541 }
542
543 (0, _packageMetadata().checkMetadata)(this.metadata, this.devMetadata, appPackageFile, devPackageFile);
544 return await this._build(configuration, this._metadata, this._devMetadata);
545 } // external caller of this method always uses isTwoPackageJsonProjectLayoutUsed=false and appDir=projectDir, no way (and need) to use another values
546
547
548 async _build(configuration, metadata, devMetadata, repositoryInfo) {
549 await (0, _config().validateConfig)(configuration, this.debugLogger);
550 this._configuration = configuration;
551 this._metadata = metadata;
552 this._devMetadata = devMetadata;
553
554 if (repositoryInfo != null) {
555 this._repositoryInfo.value = Promise.resolve(repositoryInfo);
556 }
557
558 this._appInfo = new (_appInfo().AppInfo)(this, null);
559 this._framework = await createFrameworkInfo(this.config, this);
560 const commonOutDirWithoutPossibleOsMacro = path.resolve(this.projectDir, (0, _macroExpander().expandMacro)(configuration.directories.output, null, this._appInfo, {
561 os: ""
562 }));
563
564 if (!_isCi().default && process.stdout.isTTY) {
565 const effectiveConfigFile = path.join(commonOutDirWithoutPossibleOsMacro, "builder-effective-config.yaml");
566
567 _builderUtil().log.info({
568 file: _builderUtil().log.filePath(effectiveConfigFile)
569 }, "writing effective config");
570
571 await (0, _fsExtra().outputFile)(effectiveConfigFile, getSafeEffectiveConfig(configuration));
572 } // because artifact event maybe dispatched several times for different publish providers
573
574
575 const artifactPaths = new Set();
576 this.artifactCreated(event => {
577 if (event.file != null) {
578 artifactPaths.add(event.file);
579 }
580 });
581 this.disposeOnBuildFinish(() => this.tempDirManager.cleanup());
582 const platformToTargets = await (0, _promise().executeFinally)(this.doBuild(), async () => {
583 if (this.debugLogger.isEnabled) {
584 await this.debugLogger.save(path.join(commonOutDirWithoutPossibleOsMacro, "builder-debug.yml"));
585 }
586
587 const toDispose = this.toDispose.slice();
588 this.toDispose.length = 0;
589
590 for (const disposer of toDispose) {
591 await disposer().catch(e => {
592 _builderUtil().log.warn({
593 error: e
594 }, "cannot dispose");
595 });
596 }
597 });
598 return {
599 outDir: commonOutDirWithoutPossibleOsMacro,
600 artifactPaths: Array.from(artifactPaths),
601 platformToTargets,
602 configuration
603 };
604 }
605
606 async readProjectMetadataIfTwoPackageStructureOrPrepacked(appPackageFile) {
607 let data = await (0, _promise().orNullIfFileNotExist)((0, _packageMetadata().readPackageJson)(appPackageFile));
608
609 if (data != null) {
610 return data;
611 }
612
613 data = await (0, _promise().orNullIfFileNotExist)((0, _asar().readAsarJson)(path.join(this.projectDir, "app.asar"), "package.json"));
614
615 if (data != null) {
616 this._isPrepackedAppAsar = true;
617 return data;
618 }
619
620 throw new Error(`Cannot find package.json in the ${path.dirname(appPackageFile)}`);
621 }
622
623 async doBuild() {
624 const taskManager = new (_builderUtil().AsyncTaskManager)(this.cancellationToken);
625 const platformToTarget = new Map();
626 const createdOutDirs = new Set();
627
628 for (const [platform, archToType] of this.options.targets) {
629 if (this.cancellationToken.cancelled) {
630 break;
631 }
632
633 if (platform === _index().Platform.MAC && process.platform === _index().Platform.WINDOWS.nodeName) {
634 throw new (_builderUtil().InvalidConfigurationError)("Build for macOS is supported only on macOS, please see https://electron.build/multi-platform-build");
635 }
636
637 const packager = this.createHelper(platform);
638 const nameToTarget = new Map();
639 platformToTarget.set(platform, nameToTarget);
640
641 for (const [arch, targetNames] of (0, _targetFactory().computeArchToTargetNamesMap)(archToType, packager, platform)) {
642 if (this.cancellationToken.cancelled) {
643 break;
644 }
645
646 await this.installAppDependencies(platform, arch);
647
648 if (this.cancellationToken.cancelled) {
649 break;
650 } // support os and arch macro in output value
651
652
653 const outDir = path.resolve(this.projectDir, packager.expandMacro(this._configuration.directories.output, _builderUtil().Arch[arch]));
654 const targetList = (0, _targetFactory().createTargets)(nameToTarget, targetNames.length === 0 ? packager.defaultTarget : targetNames, outDir, packager);
655 await createOutDirIfNeed(targetList, createdOutDirs);
656 await packager.pack(outDir, arch, targetList, taskManager);
657 }
658
659 if (this.cancellationToken.cancelled) {
660 break;
661 }
662
663 for (const target of nameToTarget.values()) {
664 taskManager.addTask(target.finishBuild());
665 }
666 }
667
668 await taskManager.awaitTasks();
669 return platformToTarget;
670 }
671
672 createHelper(platform) {
673 if (this.options.platformPackagerFactory != null) {
674 return this.options.platformPackagerFactory(this, platform);
675 }
676
677 switch (platform) {
678 case _index().Platform.MAC:
679 {
680 const helperClass = require("./macPackager").default;
681
682 return new helperClass(this);
683 }
684
685 case _index().Platform.WINDOWS:
686 {
687 const helperClass = require("./winPackager").WinPackager;
688
689 return new helperClass(this);
690 }
691
692 case _index().Platform.LINUX:
693 return new (require("./linuxPackager").LinuxPackager)(this);
694
695 default:
696 throw new Error(`Unknown platform: ${platform}`);
697 }
698 }
699
700 async installAppDependencies(platform, arch) {
701 if (this.options.prepackaged != null || this.framework.isNpmRebuildRequired !== true) {
702 return;
703 }
704
705 const frameworkInfo = {
706 version: this.framework.version,
707 useCustomDist: true
708 };
709 const config = this.config;
710
711 if (config.nodeGypRebuild === true) {
712 await (0, _yarn().nodeGypRebuild)(platform.nodeName, _builderUtil().Arch[arch], frameworkInfo);
713 }
714
715 if (config.npmRebuild === false) {
716 _builderUtil().log.info({
717 reason: "npmRebuild is set to false"
718 }, "skipped dependencies rebuild");
719
720 return;
721 }
722
723 const beforeBuild = (0, _platformPackager().resolveFunction)(config.beforeBuild, "beforeBuild");
724
725 if (beforeBuild != null) {
726 const performDependenciesInstallOrRebuild = await beforeBuild({
727 appDir: this.appDir,
728 electronVersion: this.config.electronVersion,
729 platform,
730 arch: _builderUtil().Arch[arch]
731 }); // If beforeBuild resolves to false, it means that handling node_modules is done outside of electron-builder.
732
733 this._nodeModulesHandledExternally = !performDependenciesInstallOrRebuild;
734
735 if (!performDependenciesInstallOrRebuild) {
736 return;
737 }
738 }
739
740 if (config.buildDependenciesFromSource === true && platform.nodeName !== process.platform) {
741 _builderUtil().log.info({
742 reason: "platform is different and buildDependenciesFromSource is set to true"
743 }, "skipped dependencies rebuild");
744 } else {
745 await (0, _yarn().installOrRebuild)(config, this.appDir, {
746 frameworkInfo,
747 platform: platform.nodeName,
748 arch: _builderUtil().Arch[arch],
749 productionDeps: this.getNodeDependencyInfo(null)
750 });
751 }
752 }
753
754 async afterPack(context) {
755 const afterPack = (0, _platformPackager().resolveFunction)(this.config.afterPack, "afterPack");
756 const handlers = this.afterPackHandlers.slice();
757
758 if (afterPack != null) {
759 // user handler should be last
760 handlers.push(afterPack);
761 }
762
763 for (const handler of handlers) {
764 await Promise.resolve(handler(context));
765 }
766 }
767
768}
769
770exports.Packager = Packager;
771
772function createOutDirIfNeed(targetList, createdOutDirs) {
773 const ourDirs = new Set();
774
775 for (const target of targetList) {
776 // noinspection SuspiciousInstanceOfGuard
777 if (target instanceof _targetFactory().NoOpTarget) {
778 continue;
779 }
780
781 const outDir = target.outDir;
782
783 if (!createdOutDirs.has(outDir)) {
784 ourDirs.add(outDir);
785 }
786 }
787
788 if (ourDirs.size === 0) {
789 return Promise.resolve();
790 }
791
792 return Promise.all(Array.from(ourDirs).sort().map(dir => {
793 return (0, _fsExtra().mkdirs)(dir).then(() => (0, _fsExtra().chmod)(dir, 0o755)
794 /* set explicitly */
795 ).then(() => createdOutDirs.add(dir));
796 }));
797}
798
799function getSafeEffectiveConfig(configuration) {
800 const o = JSON.parse((0, _builderUtil().safeStringifyJson)(configuration));
801
802 if (o.cscLink != null) {
803 o.cscLink = "<hidden by builder>";
804 }
805
806 return (0, _builderUtil().serializeToYaml)(o, true);
807}
808// __ts-babel@6.0.4
809//# sourceMappingURL=packager.js.map
\No newline at end of file