This commit is contained in:
root
2025-11-25 09:56:15 +03:00
commit 68c8f0e80d
23717 changed files with 3200521 additions and 0 deletions

View File

@ -0,0 +1,9 @@
export type Commands = {
OutFile: string;
VIProductVersion?: string;
VIAddVersionKey: Array<string>;
Unicode: boolean;
Icon?: string;
SetCompress?: "off";
SetCompressor?: "zlib";
};

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Commands.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Commands.js","sourceRoot":"","sources":["../../../src/targets/nsis/Commands.ts"],"names":[],"mappings":"","sourcesContent":["export type Commands = {\n OutFile: string\n VIProductVersion?: string\n VIAddVersionKey: Array<string>\n Unicode: boolean\n Icon?: string\n SetCompress?: \"off\"\n SetCompressor?: \"zlib\"\n}\n"]}

View File

@ -0,0 +1,78 @@
/// <reference types="node" />
import { PortableOptions } from "./nsisOptions";
import { PathLike } from "fs";
/**
* Parameters declared as environment variables in NSIS scripts.
* The documentation vaguely explains "All other electron-builder specific flags (e.g. ONE_CLICK) are still defined."
* Parameters with null values in TypeScript can be treated as Boolean values using "!Ifdef" in NSIS Script.
*/
export type Defines = {
APP_ID: string;
APP_GUID: unknown;
UNINSTALL_APP_KEY: unknown;
PRODUCT_NAME: string;
PRODUCT_FILENAME: string;
APP_FILENAME: string;
APP_DESCRIPTION: string;
VERSION: string;
PROJECT_DIR: string;
BUILD_RESOURCES_DIR: string;
APP_PACKAGE_NAME: string;
ENABLE_LOGGING_ELECTRON_BUILDER?: null;
UNINSTALL_REGISTRY_KEY_2?: string;
MUI_ICON?: unknown;
MUI_UNICON?: unknown;
APP_DIR_64?: string;
APP_DIR_ARM64?: string;
APP_DIR_32?: string;
APP_BUILD_DIR?: string;
APP_64?: string;
APP_ARM64?: string;
APP_32?: string;
APP_64_NAME?: string;
APP_ARM64_NAME?: string;
APP_32_NAME?: string;
APP_64_HASH?: string;
APP_ARM64_HASH?: string;
APP_32_HASH?: string;
APP_64_UNPACKED_SIZE?: string;
APP_ARM64_UNPACKED_SIZE?: string;
APP_32_UNPACKED_SIZE?: string;
REQUEST_EXECUTION_LEVEL?: PortableOptions["requestExecutionLevel"];
UNPACK_DIR_NAME?: string | false;
SPLASH_IMAGE?: unknown;
ESTIMATED_SIZE?: number;
COMPRESS?: "auto";
BUILD_UNINSTALLER?: null;
UNINSTALLER_OUT_FILE?: PathLike;
ONE_CLICK?: null;
RUN_AFTER_FINISH?: null;
HEADER_ICO?: string;
HIDE_RUN_AFTER_FINISH?: null;
MUI_HEADERIMAGE?: null;
MUI_HEADERIMAGE_RIGHT?: null;
MUI_HEADERIMAGE_BITMAP?: string;
MUI_WELCOMEFINISHPAGE_BITMAP?: string;
MUI_UNWELCOMEFINISHPAGE_BITMAP?: string;
MULTIUSER_INSTALLMODE_ALLOW_ELEVATION?: null;
INSTALL_MODE_PER_ALL_USERS?: null;
INSTALL_MODE_PER_ALL_USERS_DEFAULT?: null;
INSTALL_MODE_PER_ALL_USERS_REQUIRED?: null;
allowToChangeInstallationDirectory?: null;
removeDefaultUninstallWelcomePage?: null;
MENU_FILENAME?: string;
SHORTCUT_NAME?: string;
DELETE_APP_DATA_ON_UNINSTALL?: null;
UNINSTALLER_ICON?: string;
UNINSTALL_DISPLAY_NAME?: string;
RECREATE_DESKTOP_SHORTCUT?: null;
DO_NOT_CREATE_DESKTOP_SHORTCUT?: null;
DO_NOT_CREATE_START_MENU_SHORTCUT?: null;
DISPLAY_LANG_SELECTOR?: null;
COMPANY_NAME?: string;
APP_PRODUCT_FILENAME?: string;
APP_PACKAGE_STORE_FILE?: string;
APP_INSTALLER_STORE_FILE?: string;
ZIP_COMPRESSION?: null;
COMPRESSION_METHOD?: "zip" | "7z";
};

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Defines.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Defines.js","sourceRoot":"","sources":["../../../src/targets/nsis/Defines.ts"],"names":[],"mappings":"","sourcesContent":["import { PortableOptions } from \"./nsisOptions\"\nimport { PathLike } from \"fs\"\n/**\n * Parameters declared as environment variables in NSIS scripts.\n * The documentation vaguely explains \"All other electron-builder specific flags (e.g. ONE_CLICK) are still defined.\"\n * Parameters with null values in TypeScript can be treated as Boolean values using \"!Ifdef\" in NSIS Script.\n */\nexport type Defines = {\n APP_ID: string\n APP_GUID: unknown\n UNINSTALL_APP_KEY: unknown\n PRODUCT_NAME: string\n PRODUCT_FILENAME: string\n APP_FILENAME: string\n APP_DESCRIPTION: string\n VERSION: string\n\n PROJECT_DIR: string\n BUILD_RESOURCES_DIR: string\n\n APP_PACKAGE_NAME: string\n\n ENABLE_LOGGING_ELECTRON_BUILDER?: null\n UNINSTALL_REGISTRY_KEY_2?: string\n\n MUI_ICON?: unknown\n MUI_UNICON?: unknown\n\n APP_DIR_64?: string\n APP_DIR_ARM64?: string\n APP_DIR_32?: string\n\n APP_BUILD_DIR?: string\n\n APP_64?: string\n APP_ARM64?: string\n APP_32?: string\n\n APP_64_NAME?: string\n APP_ARM64_NAME?: string\n APP_32_NAME?: string\n\n APP_64_HASH?: string\n APP_ARM64_HASH?: string\n APP_32_HASH?: string\n\n APP_64_UNPACKED_SIZE?: string\n APP_ARM64_UNPACKED_SIZE?: string\n APP_32_UNPACKED_SIZE?: string\n\n REQUEST_EXECUTION_LEVEL?: PortableOptions[\"requestExecutionLevel\"]\n\n UNPACK_DIR_NAME?: string | false\n\n SPLASH_IMAGE?: unknown\n\n ESTIMATED_SIZE?: number\n\n COMPRESS?: \"auto\"\n\n BUILD_UNINSTALLER?: null\n UNINSTALLER_OUT_FILE?: PathLike\n\n ONE_CLICK?: null\n RUN_AFTER_FINISH?: null\n HEADER_ICO?: string\n HIDE_RUN_AFTER_FINISH?: null\n\n MUI_HEADERIMAGE?: null\n MUI_HEADERIMAGE_RIGHT?: null\n MUI_HEADERIMAGE_BITMAP?: string\n\n MUI_WELCOMEFINISHPAGE_BITMAP?: string\n MUI_UNWELCOMEFINISHPAGE_BITMAP?: string\n\n MULTIUSER_INSTALLMODE_ALLOW_ELEVATION?: null\n\n INSTALL_MODE_PER_ALL_USERS?: null\n INSTALL_MODE_PER_ALL_USERS_DEFAULT?: null\n INSTALL_MODE_PER_ALL_USERS_REQUIRED?: null\n\n allowToChangeInstallationDirectory?: null\n\n removeDefaultUninstallWelcomePage?: null\n\n MENU_FILENAME?: string\n\n SHORTCUT_NAME?: string\n\n DELETE_APP_DATA_ON_UNINSTALL?: null\n\n UNINSTALLER_ICON?: string\n UNINSTALL_DISPLAY_NAME?: string\n\n RECREATE_DESKTOP_SHORTCUT?: null\n\n DO_NOT_CREATE_DESKTOP_SHORTCUT?: null\n\n DO_NOT_CREATE_START_MENU_SHORTCUT?: null\n\n DISPLAY_LANG_SELECTOR?: null\n\n COMPANY_NAME?: string\n\n APP_PRODUCT_FILENAME?: string\n\n APP_PACKAGE_STORE_FILE?: string\n\n APP_INSTALLER_STORE_FILE?: string\n\n ZIP_COMPRESSION?: null\n\n COMPRESSION_METHOD?: \"zip\" | \"7z\"\n}\n"]}

View File

@ -0,0 +1,36 @@
import { Arch } from "builder-util";
import { PackageFileInfo } from "builder-util-runtime";
import { Target } from "../../core";
import { WinPackager } from "../../winPackager";
import { Defines } from "./Defines";
import { NsisOptions } from "./nsisOptions";
import { AppPackageHelper } from "./nsisUtil";
export declare class NsisTarget extends Target {
readonly packager: WinPackager;
readonly outDir: string;
protected readonly packageHelper: AppPackageHelper;
readonly options: NsisOptions;
/** @private */
readonly archs: Map<Arch, string>;
readonly isAsyncSupported = false;
constructor(packager: WinPackager, outDir: string, targetName: string, packageHelper: AppPackageHelper);
build(appOutDir: string, arch: Arch): Promise<void>;
get isBuildDifferentialAware(): boolean;
private getPreCompressedFileExtensions;
/** @private */
buildAppPackage(appOutDir: string, arch: Arch): Promise<PackageFileInfo>;
protected get installerFilenamePattern(): string;
private get isPortable();
finishBuild(): Promise<any>;
private buildInstaller;
protected generateGitHubInstallerName(): string;
private get isUnicodeEnabled();
get isWebInstaller(): boolean;
private computeScriptAndSignUninstaller;
private computeVersionKey;
protected configureDefines(oneClick: boolean, defines: Defines): Promise<any>;
private configureDefinesForAllTypeOfInstaller;
private executeMakensis;
private computeCommonInstallerScriptHeader;
private computeFinalScript;
}

View File

@ -0,0 +1,682 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NsisTarget = void 0;
const bluebird_lst_1 = require("bluebird-lst");
const builder_util_1 = require("builder-util");
const builder_util_runtime_1 = require("builder-util-runtime");
const fs_1 = require("builder-util/out/fs");
const debug_1 = require("debug");
const fs = require("fs");
const fs_extra_1 = require("fs-extra");
const path = require("path");
const binDownload_1 = require("../../binDownload");
const core_1 = require("../../core");
const CommonWindowsInstallerConfiguration_1 = require("../../options/CommonWindowsInstallerConfiguration");
const platformPackager_1 = require("../../platformPackager");
const hash_1 = require("../../util/hash");
const macosVersion_1 = require("../../util/macosVersion");
const timer_1 = require("../../util/timer");
const wine_1 = require("../../wine");
const archive_1 = require("../archive");
const differentialUpdateInfoBuilder_1 = require("../differentialUpdateInfoBuilder");
const targetUtil_1 = require("../targetUtil");
const nsisLang_1 = require("./nsisLang");
const nsisLicense_1 = require("./nsisLicense");
const nsisScriptGenerator_1 = require("./nsisScriptGenerator");
const nsisUtil_1 = require("./nsisUtil");
const debug = (0, debug_1.default)("electron-builder:nsis");
// noinspection SpellCheckingInspection
const ELECTRON_BUILDER_NS_UUID = builder_util_runtime_1.UUID.parse("50e065bc-3134-11e6-9bab-38c9862bdaf3");
// noinspection SpellCheckingInspection
const nsisResourcePathPromise = () => (0, binDownload_1.getBinFromUrl)("nsis-resources", "3.4.1", "Dqd6g+2buwwvoG1Vyf6BHR1b+25QMmPcwZx40atOT57gH27rkjOei1L0JTldxZu4NFoEmW4kJgZ3DlSWVON3+Q==");
const USE_NSIS_BUILT_IN_COMPRESSOR = false;
class NsisTarget extends core_1.Target {
constructor(packager, outDir, targetName, packageHelper) {
super(targetName);
this.packager = packager;
this.outDir = outDir;
this.packageHelper = packageHelper;
/** @private */
this.archs = new Map();
this.isAsyncSupported = false;
this.packageHelper.refCount++;
this.options =
targetName === "portable"
? Object.create(null)
: {
preCompressedFileExtensions: [".avi", ".mov", ".m4v", ".mp4", ".m4p", ".qt", ".mkv", ".webm", ".vmdk"],
...this.packager.config.nsis,
};
if (targetName !== "nsis") {
Object.assign(this.options, this.packager.config[targetName === "nsis-web" ? "nsisWeb" : targetName]);
}
const deps = packager.info.metadata.dependencies;
if (deps != null && deps["electron-squirrel-startup"] != null) {
builder_util_1.log.warn('"electron-squirrel-startup" dependency is not required for NSIS');
}
nsisUtil_1.NsisTargetOptions.resolve(this.options);
}
build(appOutDir, arch) {
this.archs.set(arch, appOutDir);
return Promise.resolve();
}
get isBuildDifferentialAware() {
return !this.isPortable && this.options.differentialPackage !== false;
}
getPreCompressedFileExtensions() {
const result = this.isWebInstaller ? null : this.options.preCompressedFileExtensions;
return result == null ? null : (0, builder_util_1.asArray)(result).map(it => (it.startsWith(".") ? it : `.${it}`));
}
/** @private */
async buildAppPackage(appOutDir, arch) {
const options = this.options;
const packager = this.packager;
const isBuildDifferentialAware = this.isBuildDifferentialAware;
const format = !isBuildDifferentialAware && options.useZip ? "zip" : "7z";
const archiveFile = path.join(this.outDir, `${packager.appInfo.sanitizedName}-${packager.appInfo.version}-${builder_util_1.Arch[arch]}.nsis.${format}`);
const preCompressedFileExtensions = this.getPreCompressedFileExtensions();
const archiveOptions = {
withoutDir: true,
compression: packager.compression,
excluded: preCompressedFileExtensions == null ? null : preCompressedFileExtensions.map(it => `*${it}`),
};
const timer = (0, timer_1.time)(`nsis package, ${builder_util_1.Arch[arch]}`);
await (0, archive_1.archive)(format, archiveFile, appOutDir, isBuildDifferentialAware ? (0, differentialUpdateInfoBuilder_1.configureDifferentialAwareArchiveOptions)(archiveOptions) : archiveOptions);
timer.end();
if (isBuildDifferentialAware && this.isWebInstaller) {
const data = await (0, differentialUpdateInfoBuilder_1.appendBlockmap)(archiveFile);
return {
...data,
path: archiveFile,
};
}
else {
return await createPackageFileInfo(archiveFile);
}
}
get installerFilenamePattern() {
// tslint:disable:no-invalid-template-strings
return "${productName} " + (this.isPortable ? "" : "Setup ") + "${version}.${ext}";
}
get isPortable() {
return this.name === "portable";
}
async finishBuild() {
try {
const { pattern } = this.packager.artifactPatternConfig(this.options, this.installerFilenamePattern);
const builds = new Set([this.archs]);
if (pattern.includes("${arch}") && this.archs.size > 1) {
;
[...this.archs].forEach(([arch, appOutDir]) => builds.add(new Map().set(arch, appOutDir)));
}
const doBuildArchs = builds.values();
for (const archs of doBuildArchs) {
await this.buildInstaller(archs);
}
}
finally {
await this.packageHelper.finishBuild();
}
}
async buildInstaller(archs) {
var _a;
const primaryArch = archs.size === 1 ? archs.keys().next().value : null;
const packager = this.packager;
const appInfo = packager.appInfo;
const options = this.options;
const installerFilename = packager.expandArtifactNamePattern(options, "exe", primaryArch, this.installerFilenamePattern, false, this.packager.platformSpecificBuildOptions.defaultArch);
const oneClick = options.oneClick !== false;
const installerPath = path.join(this.outDir, installerFilename);
const logFields = {
target: this.name,
file: builder_util_1.log.filePath(installerPath),
archs: Array.from(archs.keys())
.map(it => builder_util_1.Arch[it])
.join(", "),
};
const isPerMachine = options.perMachine === true;
if (!this.isPortable) {
logFields.oneClick = oneClick;
logFields.perMachine = isPerMachine;
}
await packager.info.callArtifactBuildStarted({
targetPresentableName: this.name,
file: installerPath,
arch: primaryArch,
}, logFields);
const guid = options.guid || builder_util_runtime_1.UUID.v5(appInfo.id, ELECTRON_BUILDER_NS_UUID);
const uninstallAppKey = guid.replace(/\\/g, " - ");
const defines = {
APP_ID: appInfo.id,
APP_GUID: guid,
// Windows bug - entry in Software\Microsoft\Windows\CurrentVersion\Uninstall cannot have \ symbols (dir)
UNINSTALL_APP_KEY: uninstallAppKey,
PRODUCT_NAME: appInfo.productName,
PRODUCT_FILENAME: appInfo.productFilename,
APP_FILENAME: (0, targetUtil_1.getWindowsInstallationDirName)(appInfo, !oneClick || isPerMachine),
APP_DESCRIPTION: appInfo.description,
VERSION: appInfo.version,
PROJECT_DIR: packager.projectDir,
BUILD_RESOURCES_DIR: packager.info.buildResourcesDir,
APP_PACKAGE_NAME: (0, targetUtil_1.getWindowsInstallationAppPackageName)(appInfo.name),
};
if ((_a = options.customNsisBinary) === null || _a === void 0 ? void 0 : _a.debugLogging) {
defines.ENABLE_LOGGING_ELECTRON_BUILDER = null;
}
if (uninstallAppKey !== guid) {
defines.UNINSTALL_REGISTRY_KEY_2 = `Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${guid}`;
}
const commands = {
OutFile: `"${installerPath}"`,
VIProductVersion: appInfo.getVersionInWeirdWindowsForm(),
VIAddVersionKey: this.computeVersionKey(),
Unicode: this.isUnicodeEnabled,
};
const isPortable = this.isPortable;
const iconPath = (isPortable ? null : await packager.getResource(options.installerIcon, "installerIcon.ico")) || (await packager.getIconPath());
if (iconPath != null) {
if (isPortable) {
commands.Icon = `"${iconPath}"`;
}
else {
defines.MUI_ICON = iconPath;
defines.MUI_UNICON = iconPath;
}
}
const packageFiles = {};
let estimatedSize = 0;
if (this.isPortable && options.useZip) {
for (const [arch, dir] of archs.entries()) {
defines[arch === builder_util_1.Arch.x64 ? "APP_DIR_64" : arch === builder_util_1.Arch.arm64 ? "APP_DIR_ARM64" : "APP_DIR_32"] = dir;
}
}
else if (USE_NSIS_BUILT_IN_COMPRESSOR && archs.size === 1) {
defines.APP_BUILD_DIR = archs.get(archs.keys().next().value);
}
else {
await bluebird_lst_1.default.map(archs.keys(), async (arch) => {
const { fileInfo, unpackedSize } = await this.packageHelper.packArch(arch, this);
const file = fileInfo.path;
const defineKey = arch === builder_util_1.Arch.x64 ? "APP_64" : arch === builder_util_1.Arch.arm64 ? "APP_ARM64" : "APP_32";
defines[defineKey] = file;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const defineNameKey = `${defineKey}_NAME`;
defines[defineNameKey] = path.basename(file);
// nsis expect a hexadecimal string
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const defineHashKey = `${defineKey}_HASH`;
defines[defineHashKey] = Buffer.from(fileInfo.sha512, "base64").toString("hex").toUpperCase();
// NSIS accepts size in KiloBytes and supports only whole numbers
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const defineUnpackedSizeKey = `${defineKey}_UNPACKED_SIZE`;
defines[defineUnpackedSizeKey] = Math.ceil(unpackedSize / 1024).toString();
if (this.isWebInstaller) {
await packager.dispatchArtifactCreated(file, this, arch);
packageFiles[builder_util_1.Arch[arch]] = fileInfo;
}
const path7za = await (0, builder_util_1.getPath7za)();
const archiveInfo = (await (0, builder_util_1.exec)(path7za, ["l", file])).trim();
// after adding blockmap data will be "Warnings: 1" in the end of output
const match = /(\d+)\s+\d+\s+\d+\s+files/.exec(archiveInfo);
if (match == null) {
builder_util_1.log.warn({ output: archiveInfo }, "cannot compute size of app package");
}
else {
estimatedSize += parseInt(match[1], 10);
}
});
}
this.configureDefinesForAllTypeOfInstaller(defines);
if (isPortable) {
const { unpackDirName, requestExecutionLevel, splashImage } = options;
defines.REQUEST_EXECUTION_LEVEL = requestExecutionLevel || "user";
// https://github.com/electron-userland/electron-builder/issues/5764
if (typeof unpackDirName === "string" || !unpackDirName) {
defines.UNPACK_DIR_NAME = unpackDirName || (await (0, builder_util_1.executeAppBuilder)(["ksuid"]));
}
if (splashImage != null) {
defines.SPLASH_IMAGE = path.resolve(packager.projectDir, splashImage);
}
}
else {
await this.configureDefines(oneClick, defines);
}
if (estimatedSize !== 0) {
// in kb
defines.ESTIMATED_SIZE = Math.round(estimatedSize / 1024);
}
if (packager.compression === "store") {
commands.SetCompress = "off";
}
else {
// difference - 33.540 vs 33.601, only 61 KB (but zip is faster to decompress)
// do not use /SOLID - "With solid compression, files are uncompressed to temporary file before they are copied to their final destination",
// it is not good for portable installer (where built-in NSIS compression is used). http://forums.winamp.com/showpost.php?p=2982902&postcount=6
commands.SetCompressor = "zlib";
if (!this.isWebInstaller) {
defines.COMPRESS = "auto";
}
}
debug(defines);
debug(commands);
if (packager.packagerOptions.effectiveOptionComputed != null && (await packager.packagerOptions.effectiveOptionComputed([defines, commands]))) {
return;
}
// prepare short-version variants of defines and commands, to make an uninstaller that doesn't differ much from the previous one
const definesUninstaller = { ...defines };
const commandsUninstaller = { ...commands };
if (appInfo.shortVersion != null) {
definesUninstaller.VERSION = appInfo.shortVersion;
commandsUninstaller.VIProductVersion = appInfo.shortVersionWindows;
commandsUninstaller.VIAddVersionKey = this.computeVersionKey(true);
}
const sharedHeader = await this.computeCommonInstallerScriptHeader();
const script = isPortable
? await (0, fs_extra_1.readFile)(path.join(nsisUtil_1.nsisTemplatesDir, "portable.nsi"), "utf8")
: await this.computeScriptAndSignUninstaller(definesUninstaller, commandsUninstaller, installerPath, sharedHeader, archs);
// copy outfile name into main options, as the computeScriptAndSignUninstaller function was kind enough to add important data to temporary defines.
defines.UNINSTALLER_OUT_FILE = definesUninstaller.UNINSTALLER_OUT_FILE;
await this.executeMakensis(defines, commands, sharedHeader + (await this.computeFinalScript(script, true, archs)));
await Promise.all([packager.sign(installerPath), defines.UNINSTALLER_OUT_FILE == null ? Promise.resolve() : (0, fs_extra_1.unlink)(defines.UNINSTALLER_OUT_FILE)]);
const safeArtifactName = (0, platformPackager_1.computeSafeArtifactNameIfNeeded)(installerFilename, () => this.generateGitHubInstallerName());
let updateInfo;
if (this.isWebInstaller) {
updateInfo = (0, differentialUpdateInfoBuilder_1.createNsisWebDifferentialUpdateInfo)(installerPath, packageFiles);
}
else if (this.isBuildDifferentialAware) {
updateInfo = await (0, differentialUpdateInfoBuilder_1.createBlockmap)(installerPath, this, packager, safeArtifactName);
}
if (updateInfo != null && isPerMachine && (oneClick || options.packElevateHelper)) {
updateInfo.isAdminRightsRequired = true;
}
await packager.info.callArtifactBuildCompleted({
file: installerPath,
updateInfo,
target: this,
packager,
arch: primaryArch,
safeArtifactName,
isWriteUpdateInfo: !this.isPortable,
});
}
generateGitHubInstallerName() {
const appInfo = this.packager.appInfo;
const classifier = appInfo.name.toLowerCase() === appInfo.name ? "setup-" : "Setup-";
return `${appInfo.name}-${this.isPortable ? "" : classifier}${appInfo.version}.exe`;
}
get isUnicodeEnabled() {
return this.options.unicode !== false;
}
get isWebInstaller() {
return false;
}
async computeScriptAndSignUninstaller(defines, commands, installerPath, sharedHeader, archs) {
const packager = this.packager;
const customScriptPath = await packager.getResource(this.options.script, "installer.nsi");
const script = await (0, fs_extra_1.readFile)(customScriptPath || path.join(nsisUtil_1.nsisTemplatesDir, "installer.nsi"), "utf8");
if (customScriptPath != null) {
builder_util_1.log.info({ reason: "custom NSIS script is used" }, "uninstaller is not signed by electron-builder");
return script;
}
// https://github.com/electron-userland/electron-builder/issues/2103
// it is more safe and reliable to write uninstaller to our out dir
const uninstallerPath = path.join(this.outDir, `__uninstaller-${this.name}-${this.packager.appInfo.sanitizedName}.exe`);
const isWin = process.platform === "win32";
defines.BUILD_UNINSTALLER = null;
defines.UNINSTALLER_OUT_FILE = isWin ? uninstallerPath : path.win32.join("Z:", uninstallerPath);
await this.executeMakensis(defines, commands, sharedHeader + (await this.computeFinalScript(script, false, archs)));
// http://forums.winamp.com/showthread.php?p=3078545
if ((0, macosVersion_1.isMacOsCatalina)()) {
try {
await nsisUtil_1.UninstallerReader.exec(installerPath, uninstallerPath);
}
catch (error) {
builder_util_1.log.warn(`packager.vm is used: ${error.message}`);
const vm = await packager.vm.value;
await vm.exec(installerPath, []);
// Parallels VM can exit after command execution, but NSIS continue to be running
let i = 0;
while (!(await (0, fs_1.exists)(uninstallerPath)) && i++ < 100) {
// noinspection JSUnusedLocalSymbols
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await new Promise((resolve, _reject) => setTimeout(resolve, 300));
}
}
}
else {
await (0, wine_1.execWine)(installerPath, null, [], { env: { __COMPAT_LAYER: "RunAsInvoker" } });
}
await packager.sign(uninstallerPath, "signing NSIS uninstaller");
delete defines.BUILD_UNINSTALLER;
// platform-specific path, not wine
defines.UNINSTALLER_OUT_FILE = uninstallerPath;
return script;
}
computeVersionKey(short = false) {
// Error: invalid VIProductVersion format, should be X.X.X.X
// so, we must strip beta
const localeId = this.options.language || "1033";
const appInfo = this.packager.appInfo;
const versionKey = [
`/LANG=${localeId} ProductName "${appInfo.productName}"`,
`/LANG=${localeId} ProductVersion "${appInfo.version}"`,
`/LANG=${localeId} LegalCopyright "${appInfo.copyright}"`,
`/LANG=${localeId} FileDescription "${appInfo.description}"`,
`/LANG=${localeId} FileVersion "${appInfo.buildVersion}"`,
];
if (short) {
versionKey[1] = `/LANG=${localeId} ProductVersion "${appInfo.shortVersion}"`;
versionKey[4] = `/LANG=${localeId} FileVersion "${appInfo.shortVersion}"`;
}
(0, builder_util_1.use)(this.packager.platformSpecificBuildOptions.legalTrademarks, it => versionKey.push(`/LANG=${localeId} LegalTrademarks "${it}"`));
(0, builder_util_1.use)(appInfo.companyName, it => versionKey.push(`/LANG=${localeId} CompanyName "${it}"`));
return versionKey;
}
configureDefines(oneClick, defines) {
const packager = this.packager;
const options = this.options;
const asyncTaskManager = new builder_util_1.AsyncTaskManager(packager.info.cancellationToken);
if (oneClick) {
defines.ONE_CLICK = null;
if (options.runAfterFinish !== false) {
defines.RUN_AFTER_FINISH = null;
}
asyncTaskManager.add(async () => {
const installerHeaderIcon = await packager.getResource(options.installerHeaderIcon, "installerHeaderIcon.ico");
if (installerHeaderIcon != null) {
defines.HEADER_ICO = installerHeaderIcon;
}
});
}
else {
if (options.runAfterFinish === false) {
defines.HIDE_RUN_AFTER_FINISH = null;
}
asyncTaskManager.add(async () => {
const installerHeader = await packager.getResource(options.installerHeader, "installerHeader.bmp");
if (installerHeader != null) {
defines.MUI_HEADERIMAGE = null;
defines.MUI_HEADERIMAGE_RIGHT = null;
defines.MUI_HEADERIMAGE_BITMAP = installerHeader;
}
});
asyncTaskManager.add(async () => {
const bitmap = (await packager.getResource(options.installerSidebar, "installerSidebar.bmp")) || "${NSISDIR}\\Contrib\\Graphics\\Wizard\\nsis3-metro.bmp";
defines.MUI_WELCOMEFINISHPAGE_BITMAP = bitmap;
defines.MUI_UNWELCOMEFINISHPAGE_BITMAP = (await packager.getResource(options.uninstallerSidebar, "uninstallerSidebar.bmp")) || bitmap;
});
if (options.allowElevation !== false) {
defines.MULTIUSER_INSTALLMODE_ALLOW_ELEVATION = null;
}
}
if (options.perMachine === true) {
defines.INSTALL_MODE_PER_ALL_USERS = null;
}
if (options.selectPerMachineByDefault === true) {
defines.INSTALL_MODE_PER_ALL_USERS_DEFAULT = null;
}
if (!oneClick || options.perMachine === true) {
defines.INSTALL_MODE_PER_ALL_USERS_REQUIRED = null;
}
if (options.allowToChangeInstallationDirectory) {
if (oneClick) {
throw new builder_util_1.InvalidConfigurationError("allowToChangeInstallationDirectory makes sense only for assisted installer (please set oneClick to false)");
}
defines.allowToChangeInstallationDirectory = null;
}
if (options.removeDefaultUninstallWelcomePage) {
defines.removeDefaultUninstallWelcomePage = null;
}
const commonOptions = (0, CommonWindowsInstallerConfiguration_1.getEffectiveOptions)(options, packager);
if (commonOptions.menuCategory != null) {
defines.MENU_FILENAME = commonOptions.menuCategory;
}
defines.SHORTCUT_NAME = commonOptions.shortcutName;
if (options.deleteAppDataOnUninstall) {
defines.DELETE_APP_DATA_ON_UNINSTALL = null;
}
asyncTaskManager.add(async () => {
const uninstallerIcon = await packager.getResource(options.uninstallerIcon, "uninstallerIcon.ico");
if (uninstallerIcon != null) {
// we don't need to copy MUI_UNICON (defaults to app icon), so, we have 2 defines
defines.UNINSTALLER_ICON = uninstallerIcon;
defines.MUI_UNICON = uninstallerIcon;
}
});
defines.UNINSTALL_DISPLAY_NAME = packager.expandMacro(options.uninstallDisplayName || "${productName} ${version}", null, {}, false);
if (commonOptions.isCreateDesktopShortcut === CommonWindowsInstallerConfiguration_1.DesktopShortcutCreationPolicy.NEVER) {
defines.DO_NOT_CREATE_DESKTOP_SHORTCUT = null;
}
if (commonOptions.isCreateDesktopShortcut === CommonWindowsInstallerConfiguration_1.DesktopShortcutCreationPolicy.ALWAYS) {
defines.RECREATE_DESKTOP_SHORTCUT = null;
}
if (!commonOptions.isCreateStartMenuShortcut) {
defines.DO_NOT_CREATE_START_MENU_SHORTCUT = null;
}
if (options.displayLanguageSelector === true) {
defines.DISPLAY_LANG_SELECTOR = null;
}
return asyncTaskManager.awaitTasks();
}
configureDefinesForAllTypeOfInstaller(defines) {
const appInfo = this.packager.appInfo;
const companyName = appInfo.companyName;
if (companyName != null) {
defines.COMPANY_NAME = companyName;
}
// electron uses product file name as app data, define it as well to remove on uninstall
if (defines.APP_FILENAME !== appInfo.productFilename) {
defines.APP_PRODUCT_FILENAME = appInfo.productFilename;
}
if (this.isWebInstaller) {
defines.APP_PACKAGE_STORE_FILE = `${appInfo.updaterCacheDirName}\\${builder_util_runtime_1.CURRENT_APP_PACKAGE_FILE_NAME}`;
}
else {
defines.APP_INSTALLER_STORE_FILE = `${appInfo.updaterCacheDirName}\\${builder_util_runtime_1.CURRENT_APP_INSTALLER_FILE_NAME}`;
}
if (!this.isWebInstaller && defines.APP_BUILD_DIR == null) {
const options = this.options;
if (options.useZip) {
defines.ZIP_COMPRESSION = null;
}
defines.COMPRESSION_METHOD = options.useZip ? "zip" : "7z";
}
}
async executeMakensis(defines, commands, script) {
const args = this.options.warningsAsErrors === false ? [] : ["-WX"];
args.push("-INPUTCHARSET", "UTF8");
for (const name of Object.keys(defines)) {
const value = defines[name];
if (value == null) {
args.push(`-D${name}`);
}
else {
args.push(`-D${name}=${value}`);
}
}
for (const name of Object.keys(commands)) {
const value = commands[name];
if (Array.isArray(value)) {
for (const c of value) {
args.push(`-X${name} ${c}`);
}
}
else {
args.push(`-X${name} ${value}`);
}
}
args.push("-");
if (this.packager.debugLogger.isEnabled) {
this.packager.debugLogger.add("nsis.script", script);
}
const nsisPath = await (0, nsisUtil_1.NSIS_PATH)();
const command = path.join(nsisPath, process.platform === "darwin" ? "mac" : process.platform === "win32" ? "Bin" : "linux", process.platform === "win32" ? "makensis.exe" : "makensis");
// if (process.platform === "win32") {
// fix for an issue caused by virus scanners, locking the file during write
// https://github.com/electron-userland/electron-builder/issues/5005
await ensureNotBusy(commands["OutFile"].replace(/"/g, ""));
// }
await (0, builder_util_1.spawnAndWrite)(command, args, script, {
// we use NSIS_CONFIG_CONST_DATA_PATH=no to build makensis on Linux, but in any case it doesn't use stubs as MacOS/Windows version, so, we explicitly set NSISDIR
env: { ...process.env, NSISDIR: nsisPath },
cwd: nsisUtil_1.nsisTemplatesDir,
});
}
async computeCommonInstallerScriptHeader() {
const packager = this.packager;
const options = this.options;
const scriptGenerator = new nsisScriptGenerator_1.NsisScriptGenerator();
const langConfigurator = new nsisLang_1.LangConfigurator(options);
scriptGenerator.include(path.join(nsisUtil_1.nsisTemplatesDir, "include", "StdUtils.nsh"));
const includeDir = path.join(nsisUtil_1.nsisTemplatesDir, "include");
scriptGenerator.addIncludeDir(includeDir);
scriptGenerator.flags(["updated", "force-run", "keep-shortcuts", "no-desktop-shortcut", "delete-app-data", "allusers", "currentuser"]);
(0, nsisLang_1.createAddLangsMacro)(scriptGenerator, langConfigurator);
const taskManager = new builder_util_1.AsyncTaskManager(packager.info.cancellationToken);
const pluginArch = this.isUnicodeEnabled ? "x86-unicode" : "x86-ansi";
taskManager.add(async () => {
scriptGenerator.addPluginDir(pluginArch, path.join(await nsisResourcePathPromise(), "plugins", pluginArch));
});
taskManager.add(async () => {
const userPluginDir = path.join(packager.info.buildResourcesDir, pluginArch);
const stat = await (0, fs_1.statOrNull)(userPluginDir);
if (stat != null && stat.isDirectory()) {
scriptGenerator.addPluginDir(pluginArch, userPluginDir);
}
});
taskManager.addTask((0, nsisLang_1.addCustomMessageFileInclude)("messages.yml", packager, scriptGenerator, langConfigurator));
if (!this.isPortable) {
if (options.oneClick === false) {
taskManager.addTask((0, nsisLang_1.addCustomMessageFileInclude)("assistedMessages.yml", packager, scriptGenerator, langConfigurator));
}
taskManager.add(async () => {
const customInclude = await packager.getResource(this.options.include, "installer.nsh");
if (customInclude != null) {
scriptGenerator.addIncludeDir(packager.info.buildResourcesDir);
scriptGenerator.include(customInclude);
}
});
}
await taskManager.awaitTasks();
return scriptGenerator.build();
}
async computeFinalScript(originalScript, isInstaller, archs) {
const packager = this.packager;
const options = this.options;
const langConfigurator = new nsisLang_1.LangConfigurator(options);
const scriptGenerator = new nsisScriptGenerator_1.NsisScriptGenerator();
const taskManager = new builder_util_1.AsyncTaskManager(packager.info.cancellationToken);
if (isInstaller) {
// http://stackoverflow.com/questions/997456/nsis-license-file-based-on-language-selection
taskManager.add(() => (0, nsisLicense_1.computeLicensePage)(packager, options, scriptGenerator, langConfigurator.langs));
}
await taskManager.awaitTasks();
if (this.isPortable) {
return scriptGenerator.build() + originalScript;
}
const preCompressedFileExtensions = this.getPreCompressedFileExtensions();
if (preCompressedFileExtensions != null && preCompressedFileExtensions.length !== 0) {
for (const [arch, dir] of archs.entries()) {
await generateForPreCompressed(preCompressedFileExtensions, dir, arch, scriptGenerator);
}
}
const fileAssociations = packager.fileAssociations;
if (fileAssociations.length !== 0) {
scriptGenerator.include(path.join(path.join(nsisUtil_1.nsisTemplatesDir, "include"), "FileAssociation.nsh"));
if (isInstaller) {
const registerFileAssociationsScript = new nsisScriptGenerator_1.NsisScriptGenerator();
for (const item of fileAssociations) {
const extensions = (0, builder_util_1.asArray)(item.ext).map(platformPackager_1.normalizeExt);
for (const ext of extensions) {
const customIcon = await packager.getResource((0, builder_util_1.getPlatformIconFileName)(item.icon, false), `${extensions[0]}.ico`);
let installedIconPath = "$appExe,0";
if (customIcon != null) {
installedIconPath = `$INSTDIR\\resources\\${path.basename(customIcon)}`;
registerFileAssociationsScript.file(installedIconPath, customIcon);
}
const icon = `"${installedIconPath}"`;
const commandText = `"Open with ${packager.appInfo.productName}"`;
const command = '"$appExe $\\"%1$\\""';
registerFileAssociationsScript.insertMacro("APP_ASSOCIATE", `"${ext}" "${item.name || ext}" "${item.description || ""}" ${icon} ${commandText} ${command}`);
}
}
scriptGenerator.macro("registerFileAssociations", registerFileAssociationsScript);
}
else {
const unregisterFileAssociationsScript = new nsisScriptGenerator_1.NsisScriptGenerator();
for (const item of fileAssociations) {
for (const ext of (0, builder_util_1.asArray)(item.ext)) {
unregisterFileAssociationsScript.insertMacro("APP_UNASSOCIATE", `"${(0, platformPackager_1.normalizeExt)(ext)}" "${item.name || ext}"`);
}
}
scriptGenerator.macro("unregisterFileAssociations", unregisterFileAssociationsScript);
}
}
return scriptGenerator.build() + originalScript;
}
}
exports.NsisTarget = NsisTarget;
async function generateForPreCompressed(preCompressedFileExtensions, dir, arch, scriptGenerator) {
const resourcesDir = path.join(dir, "resources");
const dirInfo = await (0, fs_1.statOrNull)(resourcesDir);
if (dirInfo == null || !dirInfo.isDirectory()) {
return;
}
const nodeModules = `${path.sep}node_modules`;
const preCompressedAssets = await (0, fs_1.walk)(resourcesDir, (file, stat) => {
if (stat.isDirectory()) {
return !file.endsWith(nodeModules);
}
else {
return preCompressedFileExtensions.some(it => file.endsWith(it));
}
});
if (preCompressedAssets.length !== 0) {
const macro = new nsisScriptGenerator_1.NsisScriptGenerator();
for (const file of preCompressedAssets) {
macro.file(`$INSTDIR\\${path.relative(dir, file).replace(/\//g, "\\")}`, file);
}
scriptGenerator.macro(`customFiles_${builder_util_1.Arch[arch]}`, macro);
}
}
async function ensureNotBusy(outFile) {
function isBusy(wasBusyBefore) {
return new Promise((resolve, reject) => {
fs.open(outFile, "r+", (error, fd) => {
try {
if (error != null && error.code === "EBUSY") {
if (!wasBusyBefore) {
builder_util_1.log.info({}, "output file is locked for writing (maybe by virus scanner) => waiting for unlock...");
}
resolve(false);
}
else if (fd == null) {
resolve(true);
}
else {
fs.close(fd, () => resolve(true));
}
}
catch (error) {
reject(error);
}
});
}).then(result => {
if (result) {
return true;
}
else {
return new Promise(resolve => setTimeout(resolve, 2000)).then(() => isBusy(true));
}
});
}
await isBusy(false);
}
async function createPackageFileInfo(file) {
return {
path: file,
size: (await (0, fs_extra_1.stat)(file)).size,
sha512: await (0, hash_1.hashFile)(file),
};
}
//# sourceMappingURL=NsisTarget.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,11 @@
import { WinPackager } from "../../winPackager";
import { NsisTarget } from "./NsisTarget";
import { AppPackageHelper } from "./nsisUtil";
/** @private */
export declare class WebInstallerTarget extends NsisTarget {
constructor(packager: WinPackager, outDir: string, targetName: string, packageHelper: AppPackageHelper);
get isWebInstaller(): boolean;
protected configureDefines(oneClick: boolean, defines: any): Promise<any>;
protected get installerFilenamePattern(): string;
protected generateGitHubInstallerName(): string;
}

View File

@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebInstallerTarget = void 0;
const PublishManager_1 = require("../../publish/PublishManager");
const NsisTarget_1 = require("./NsisTarget");
/** @private */
class WebInstallerTarget extends NsisTarget_1.NsisTarget {
constructor(packager, outDir, targetName, packageHelper) {
super(packager, outDir, targetName, packageHelper);
}
get isWebInstaller() {
return true;
}
async configureDefines(oneClick, defines) {
//noinspection ES6MissingAwait
await NsisTarget_1.NsisTarget.prototype.configureDefines.call(this, oneClick, defines);
const packager = this.packager;
const options = this.options;
let appPackageUrl = options.appPackageUrl;
if (appPackageUrl == null) {
const publishConfigs = await (0, PublishManager_1.getPublishConfigsForUpdateInfo)(packager, await (0, PublishManager_1.getPublishConfigs)(packager, packager.info.config, null, false), null);
if (publishConfigs == null || publishConfigs.length === 0) {
throw new Error("Cannot compute app package download URL");
}
appPackageUrl = (0, PublishManager_1.computeDownloadUrl)(publishConfigs[0], null, packager);
}
defines.APP_PACKAGE_URL_IS_INCOMPLETE = null;
defines.APP_PACKAGE_URL = appPackageUrl;
}
get installerFilenamePattern() {
// tslint:disable:no-invalid-template-strings
return "${productName} Web Setup ${version}.${ext}";
}
generateGitHubInstallerName() {
const appInfo = this.packager.appInfo;
const classifier = appInfo.name.toLowerCase() === appInfo.name ? "web-setup" : "WebSetup";
return `${appInfo.name}-${classifier}-${appInfo.version}.exe`;
}
}
exports.WebInstallerTarget = WebInstallerTarget;
//# sourceMappingURL=WebInstallerTarget.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"WebInstallerTarget.js","sourceRoot":"","sources":["../../../src/targets/nsis/WebInstallerTarget.ts"],"names":[],"mappings":";;;AAAA,iEAAoH;AAGpH,6CAAyC;AAGzC,eAAe;AACf,MAAa,kBAAmB,SAAQ,uBAAU;IAChD,YAAY,QAAqB,EAAE,MAAc,EAAE,UAAkB,EAAE,aAA+B;QACpG,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,CAAC,CAAA;IACpD,CAAC;IAED,IAAI,cAAc;QAChB,OAAO,IAAI,CAAA;IACb,CAAC;IAES,KAAK,CAAC,gBAAgB,CAAC,QAAiB,EAAE,OAAY;QAC9D,8BAA8B;QAC9B,MAAO,uBAAU,CAAC,SAAgC,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAA;QAEjG,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAA;QAC9B,MAAM,OAAO,GAAG,IAAI,CAAC,OAAyB,CAAA;QAE9C,IAAI,aAAa,GAAG,OAAO,CAAC,aAAa,CAAA;QACzC,IAAI,aAAa,IAAI,IAAI,EAAE,CAAC;YAC1B,MAAM,cAAc,GAAG,MAAM,IAAA,+CAA8B,EAAC,QAAQ,EAAE,MAAM,IAAA,kCAAiB,EAAC,QAAQ,EAAE,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,IAAI,CAAC,CAAA;YACjJ,IAAI,cAAc,IAAI,IAAI,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC1D,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAA;YAC5D,CAAC;YAED,aAAa,GAAG,IAAA,mCAAkB,EAAC,cAAc,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;QACvE,CAAC;QAED,OAAO,CAAC,6BAA6B,GAAG,IAAI,CAAA;QAC5C,OAAO,CAAC,eAAe,GAAG,aAAa,CAAA;IACzC,CAAC;IAED,IAAc,wBAAwB;QACpC,6CAA6C;QAC7C,OAAO,4CAA4C,CAAA;IACrD,CAAC;IAES,2BAA2B;QACnC,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAA;QACrC,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,UAAU,CAAA;QACzF,OAAO,GAAG,OAAO,CAAC,IAAI,IAAI,UAAU,IAAI,OAAO,CAAC,OAAO,MAAM,CAAA;IAC/D,CAAC;CACF;AAxCD,gDAwCC","sourcesContent":["import { computeDownloadUrl, getPublishConfigs, getPublishConfigsForUpdateInfo } from \"../../publish/PublishManager\"\nimport { WinPackager } from \"../../winPackager\"\nimport { NsisWebOptions } from \"./nsisOptions\"\nimport { NsisTarget } from \"./NsisTarget\"\nimport { AppPackageHelper } from \"./nsisUtil\"\n\n/** @private */\nexport class WebInstallerTarget extends NsisTarget {\n constructor(packager: WinPackager, outDir: string, targetName: string, packageHelper: AppPackageHelper) {\n super(packager, outDir, targetName, packageHelper)\n }\n\n get isWebInstaller(): boolean {\n return true\n }\n\n protected async configureDefines(oneClick: boolean, defines: any): Promise<any> {\n //noinspection ES6MissingAwait\n await (NsisTarget.prototype as WebInstallerTarget).configureDefines.call(this, oneClick, defines)\n\n const packager = this.packager\n const options = this.options as NsisWebOptions\n\n let appPackageUrl = options.appPackageUrl\n if (appPackageUrl == null) {\n const publishConfigs = await getPublishConfigsForUpdateInfo(packager, await getPublishConfigs(packager, packager.info.config, null, false), null)\n if (publishConfigs == null || publishConfigs.length === 0) {\n throw new Error(\"Cannot compute app package download URL\")\n }\n\n appPackageUrl = computeDownloadUrl(publishConfigs[0], null, packager)\n }\n\n defines.APP_PACKAGE_URL_IS_INCOMPLETE = null\n defines.APP_PACKAGE_URL = appPackageUrl\n }\n\n protected get installerFilenamePattern(): string {\n // tslint:disable:no-invalid-template-strings\n return \"${productName} Web Setup ${version}.${ext}\"\n }\n\n protected generateGitHubInstallerName(): string {\n const appInfo = this.packager.appInfo\n const classifier = appInfo.name.toLowerCase() === appInfo.name ? \"web-setup\" : \"WebSetup\"\n return `${appInfo.name}-${classifier}-${appInfo.version}.exe`\n }\n}\n"]}

View File

@ -0,0 +1,10 @@
import { PlatformPackager } from "../../platformPackager";
import { NsisOptions } from "./nsisOptions";
import { NsisScriptGenerator } from "./nsisScriptGenerator";
export declare class LangConfigurator {
readonly isMultiLang: boolean;
readonly langs: Array<string>;
constructor(options: NsisOptions);
}
export declare function createAddLangsMacro(scriptGenerator: NsisScriptGenerator, langConfigurator: LangConfigurator): void;
export declare function addCustomMessageFileInclude(input: string, packager: PlatformPackager<any>, scriptGenerator: NsisScriptGenerator, langConfigurator: LangConfigurator): Promise<void>;

View File

@ -0,0 +1,100 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCustomMessageFileInclude = exports.createAddLangsMacro = exports.LangConfigurator = void 0;
const builder_util_1 = require("builder-util");
const langs_1 = require("../../util/langs");
const debug_1 = require("debug");
const fs_extra_1 = require("fs-extra");
const js_yaml_1 = require("js-yaml");
const path = require("path");
const nsisUtil_1 = require("./nsisUtil");
const debug = (0, debug_1.default)("electron-builder:nsis");
class LangConfigurator {
constructor(options) {
const rawList = options.installerLanguages;
if (options.unicode === false || rawList === null || (Array.isArray(rawList) && rawList.length === 0)) {
this.isMultiLang = false;
}
else {
this.isMultiLang = options.multiLanguageInstaller !== false;
}
if (this.isMultiLang) {
this.langs = rawList == null ? langs_1.bundledLanguages.slice() : (0, builder_util_1.asArray)(rawList).map(it => (0, langs_1.toLangWithRegion)(it.replace("-", "_")));
}
else {
this.langs = ["en_US"];
}
}
}
exports.LangConfigurator = LangConfigurator;
function createAddLangsMacro(scriptGenerator, langConfigurator) {
const result = [];
for (const langWithRegion of langConfigurator.langs) {
let name;
if (langWithRegion === "zh_CN") {
name = "SimpChinese";
}
else if (langWithRegion === "zh_TW") {
name = "TradChinese";
}
else if (langWithRegion === "nb_NO") {
name = "Norwegian";
}
else if (langWithRegion === "pt_BR") {
name = "PortugueseBR";
}
else {
const lang = langWithRegion.substring(0, langWithRegion.indexOf("_"));
name = langs_1.langIdToName[lang];
if (name == null) {
throw new Error(`Language name is unknown for ${lang}`);
}
if (name === "Spanish") {
name = "SpanishInternational";
}
}
result.push(`!insertmacro MUI_LANGUAGE "${name}"`);
}
scriptGenerator.macro("addLangs", result);
}
exports.createAddLangsMacro = createAddLangsMacro;
async function writeCustomLangFile(data, packager) {
const file = await packager.getTempFile("messages.nsh");
await (0, fs_extra_1.outputFile)(file, data);
return file;
}
async function addCustomMessageFileInclude(input, packager, scriptGenerator, langConfigurator) {
const data = (0, js_yaml_1.load)(await (0, fs_extra_1.readFile)(path.join(nsisUtil_1.nsisTemplatesDir, input), "utf-8"));
const instructions = computeCustomMessageTranslations(data, langConfigurator).join("\n");
debug(instructions);
scriptGenerator.include(await writeCustomLangFile(instructions, packager));
}
exports.addCustomMessageFileInclude = addCustomMessageFileInclude;
function computeCustomMessageTranslations(messages, langConfigurator) {
const result = [];
const includedLangs = new Set(langConfigurator.langs);
for (const messageId of Object.keys(messages)) {
const langToTranslations = messages[messageId];
const unspecifiedLangs = new Set(langConfigurator.langs);
for (const lang of Object.keys(langToTranslations)) {
const langWithRegion = (0, langs_1.toLangWithRegion)(lang);
if (!includedLangs.has(langWithRegion)) {
continue;
}
const value = langToTranslations[lang];
if (value == null) {
throw new Error(`${messageId} not specified for ${lang}`);
}
result.push(`LangString ${messageId} ${langs_1.lcid[langWithRegion]} "${value.replace(/\n/g, "$\\r$\\n")}"`);
unspecifiedLangs.delete(langWithRegion);
}
if (langConfigurator.isMultiLang) {
const defaultTranslation = langToTranslations.en.replace(/\n/g, "$\\r$\\n");
for (const langWithRegion of unspecifiedLangs) {
result.push(`LangString ${messageId} ${langs_1.lcid[langWithRegion]} "${defaultTranslation}"`);
}
}
}
return result;
}
//# sourceMappingURL=nsisLang.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
import { WinPackager } from "../../winPackager";
import { NsisOptions } from "./nsisOptions";
import { NsisScriptGenerator } from "./nsisScriptGenerator";
export declare function computeLicensePage(packager: WinPackager, options: NsisOptions, scriptGenerator: NsisScriptGenerator, languages: Array<string>): Promise<void>;

View File

@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeLicensePage = void 0;
const langs_1 = require("../../util/langs");
const license_1 = require("../../util/license");
const path = require("path");
const nsisUtil_1 = require("./nsisUtil");
async function computeLicensePage(packager, options, scriptGenerator, languages) {
const license = await (0, license_1.getNotLocalizedLicenseFile)(options.license, packager);
if (license != null) {
let licensePage;
if (license.endsWith(".html")) {
licensePage = [
"!define MUI_PAGE_CUSTOMFUNCTION_SHOW LicenseShow",
"Function LicenseShow",
" FindWindow $R0 `#32770` `` $HWNDPARENT",
" GetDlgItem $R0 $R0 1000",
"EmbedHTML::Load /replace $R0 file://$PLUGINSDIR\\license.html",
"FunctionEnd",
`!insertmacro MUI_PAGE_LICENSE "${path.join(nsisUtil_1.nsisTemplatesDir, "empty-license.txt")}"`,
];
}
else {
licensePage = [`!insertmacro MUI_PAGE_LICENSE "${license}"`];
}
scriptGenerator.macro("licensePage", licensePage);
if (license.endsWith(".html")) {
scriptGenerator.macro("addLicenseFiles", [`File /oname=$PLUGINSDIR\\license.html "${license}"`]);
}
return;
}
const licenseFiles = await (0, license_1.getLicenseFiles)(packager);
if (licenseFiles.length === 0) {
return;
}
const licensePage = [];
const unspecifiedLangs = new Set(languages);
let defaultFile = null;
for (const item of licenseFiles) {
unspecifiedLangs.delete(item.langWithRegion);
if (defaultFile == null) {
defaultFile = item.file;
}
licensePage.push(`LicenseLangString MUILicense ${langs_1.lcid[item.langWithRegion] || item.lang} "${item.file}"`);
}
for (const l of unspecifiedLangs) {
licensePage.push(`LicenseLangString MUILicense ${langs_1.lcid[l]} "${defaultFile}"`);
}
licensePage.push('!insertmacro MUI_PAGE_LICENSE "$(MUILicense)"');
scriptGenerator.macro("licensePage", licensePage);
}
exports.computeLicensePage = computeLicensePage;
//# sourceMappingURL=nsisLicense.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"nsisLicense.js","sourceRoot":"","sources":["../../../src/targets/nsis/nsisLicense.ts"],"names":[],"mappings":";;;AAAA,4CAAuC;AACvC,gDAAgF;AAChF,6BAA4B;AAI5B,yCAA6C;AAEtC,KAAK,UAAU,kBAAkB,CAAC,QAAqB,EAAE,OAAoB,EAAE,eAAoC,EAAE,SAAwB;IAClJ,MAAM,OAAO,GAAG,MAAM,IAAA,oCAA0B,EAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;IAC3E,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;QACpB,IAAI,WAA0B,CAAA;QAC9B,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9B,WAAW,GAAG;gBACZ,kDAAkD;gBAClD,sBAAsB;gBACtB,0CAA0C;gBAC1C,2BAA2B;gBAC3B,+DAA+D;gBAC/D,aAAa;gBAEb,kCAAkC,IAAI,CAAC,IAAI,CAAC,2BAAgB,EAAE,mBAAmB,CAAC,GAAG;aACtF,CAAA;QACH,CAAC;aAAM,CAAC;YACN,WAAW,GAAG,CAAC,kCAAkC,OAAO,GAAG,CAAC,CAAA;QAC9D,CAAC;QAED,eAAe,CAAC,KAAK,CAAC,aAAa,EAAE,WAAW,CAAC,CAAA;QACjD,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9B,eAAe,CAAC,KAAK,CAAC,iBAAiB,EAAE,CAAC,0CAA0C,OAAO,GAAG,CAAC,CAAC,CAAA;QAClG,CAAC;QACD,OAAM;IACR,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,IAAA,yBAAe,EAAC,QAAQ,CAAC,CAAA;IACpD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAM;IACR,CAAC;IAED,MAAM,WAAW,GAAkB,EAAE,CAAA;IACrC,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAA;IAE3C,IAAI,WAAW,GAAkB,IAAI,CAAA;IACrC,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QAChC,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;QAC5C,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;YACxB,WAAW,GAAG,IAAI,CAAC,IAAI,CAAA;QACzB,CAAC;QACD,WAAW,CAAC,IAAI,CAAC,gCAAgC,YAAI,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,CAAC,CAAA;IAC3G,CAAC;IAED,KAAK,MAAM,CAAC,IAAI,gBAAgB,EAAE,CAAC;QACjC,WAAW,CAAC,IAAI,CAAC,gCAAgC,YAAI,CAAC,CAAC,CAAC,KAAK,WAAW,GAAG,CAAC,CAAA;IAC9E,CAAC;IAED,WAAW,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAA;IACjE,eAAe,CAAC,KAAK,CAAC,aAAa,EAAE,WAAW,CAAC,CAAA;AACnD,CAAC;AAjDD,gDAiDC","sourcesContent":["import { lcid } from \"../../util/langs\"\nimport { getLicenseFiles, getNotLocalizedLicenseFile } from \"../../util/license\"\nimport * as path from \"path\"\nimport { WinPackager } from \"../../winPackager\"\nimport { NsisOptions } from \"./nsisOptions\"\nimport { NsisScriptGenerator } from \"./nsisScriptGenerator\"\nimport { nsisTemplatesDir } from \"./nsisUtil\"\n\nexport async function computeLicensePage(packager: WinPackager, options: NsisOptions, scriptGenerator: NsisScriptGenerator, languages: Array<string>): Promise<void> {\n const license = await getNotLocalizedLicenseFile(options.license, packager)\n if (license != null) {\n let licensePage: Array<string>\n if (license.endsWith(\".html\")) {\n licensePage = [\n \"!define MUI_PAGE_CUSTOMFUNCTION_SHOW LicenseShow\",\n \"Function LicenseShow\",\n \" FindWindow $R0 `#32770` `` $HWNDPARENT\",\n \" GetDlgItem $R0 $R0 1000\",\n \"EmbedHTML::Load /replace $R0 file://$PLUGINSDIR\\\\license.html\",\n \"FunctionEnd\",\n\n `!insertmacro MUI_PAGE_LICENSE \"${path.join(nsisTemplatesDir, \"empty-license.txt\")}\"`,\n ]\n } else {\n licensePage = [`!insertmacro MUI_PAGE_LICENSE \"${license}\"`]\n }\n\n scriptGenerator.macro(\"licensePage\", licensePage)\n if (license.endsWith(\".html\")) {\n scriptGenerator.macro(\"addLicenseFiles\", [`File /oname=$PLUGINSDIR\\\\license.html \"${license}\"`])\n }\n return\n }\n\n const licenseFiles = await getLicenseFiles(packager)\n if (licenseFiles.length === 0) {\n return\n }\n\n const licensePage: Array<string> = []\n const unspecifiedLangs = new Set(languages)\n\n let defaultFile: string | null = null\n for (const item of licenseFiles) {\n unspecifiedLangs.delete(item.langWithRegion)\n if (defaultFile == null) {\n defaultFile = item.file\n }\n licensePage.push(`LicenseLangString MUILicense ${lcid[item.langWithRegion] || item.lang} \"${item.file}\"`)\n }\n\n for (const l of unspecifiedLangs) {\n licensePage.push(`LicenseLangString MUILicense ${lcid[l]} \"${defaultFile}\"`)\n }\n\n licensePage.push('!insertmacro MUI_PAGE_LICENSE \"$(MUILicense)\"')\n scriptGenerator.macro(\"licensePage\", licensePage)\n}\n"]}

View File

@ -0,0 +1,221 @@
import { TargetSpecificOptions } from "../../core";
import { CommonWindowsInstallerConfiguration } from "../..";
interface CustomNsisBinary {
/**
* @default https://github.com/electron-userland/electron-builder-binaries/releases/download
*/
readonly url: string | null;
/**
* @default VKMiizYdmNdJOWpRGz4trl4lD++BvYP2irAXpMilheUP0pc93iKlWAoP843Vlraj8YG19CVn0j+dCo/hURz9+Q==
*/
readonly checksum?: string | null;
/**
* @default 3.0.4.1
*/
readonly version?: string | null;
/**
* Whether or not to enable NSIS logging for debugging.
* Note: Requires a debug-enabled NSIS build.
* electron-builder's included `makensis` does not natively support debug-enabled NSIS installers currently, you must supply your own via `customNsisBinary?: CustomNsisBinary`
* In your custom nsis scripts, you can leverage this functionality via `LogSet` and `LogText`
*/
readonly debugLogging?: boolean | null;
}
export interface CommonNsisOptions {
/**
* Whether to create [Unicode installer](http://nsis.sourceforge.net/Docs/Chapter1.html#intro-unicode).
* @default true
*/
readonly unicode?: boolean;
/**
* See [GUID vs Application Name](../configuration/nsis#guid-vs-application-name).
*/
readonly guid?: string | null;
/**
* If `warningsAsErrors` is `true` (default): NSIS will treat warnings as errors. If `warningsAsErrors` is `false`: NSIS will allow warnings.
* @default true
*/
readonly warningsAsErrors?: boolean;
/**
* @private
* @default false
*/
readonly useZip?: boolean;
/**
* Allows you to provide your own `makensis`, such as one with support for debug logging via LogSet and LogText. (Logging also requires option `debugLogging = true`)
*/
readonly customNsisBinary?: CustomNsisBinary | null;
}
export interface NsisOptions extends CommonNsisOptions, CommonWindowsInstallerConfiguration, TargetSpecificOptions {
/**
* Whether to create one-click installer or assisted.
* @default true
*/
readonly oneClick?: boolean;
/**
* Whether to show install mode installer page (choice per-machine or per-user) for assisted installer. Or whether installation always per all users (per-machine).
*
* If `oneClick` is `true` (default): Whether to install per all users (per-machine).
*
* If `oneClick` is `false` and `perMachine` is `true`: no install mode installer page, always install per-machine.
*
* If `oneClick` is `false` and `perMachine` is `false` (default): install mode installer page.
* @default false
*/
readonly perMachine?: boolean;
/**
* Whether to set per-machine or per-user installation as default selection on the install mode installer page.
*
* @default false
*/
readonly selectPerMachineByDefault?: boolean;
/**
* *assisted installer only.* Allow requesting for elevation. If false, user will have to restart installer with elevated permissions.
* @default true
*/
readonly allowElevation?: boolean;
/**
* *assisted installer only.* Whether to allow user to change installation directory.
* @default false
*/
readonly allowToChangeInstallationDirectory?: boolean;
/**
* *assisted installer only.* remove the default uninstall welcome page.
* @default false
*/
readonly removeDefaultUninstallWelcomePage?: boolean;
/**
* The path to installer icon, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/installerIcon.ico` or application icon.
*/
readonly installerIcon?: string | null;
/**
* The path to uninstaller icon, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/uninstallerIcon.ico` or application icon.
*/
readonly uninstallerIcon?: string | null;
/**
* *assisted installer only.* `MUI_HEADERIMAGE`, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* @default build/installerHeader.bmp
*/
readonly installerHeader?: string | null;
/**
* *one-click installer only.* The path to header icon (above the progress bar), relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/installerHeaderIcon.ico` or application icon.
*/
readonly installerHeaderIcon?: string | null;
/**
* *assisted installer only.* `MUI_WELCOMEFINISHPAGE_BITMAP`, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/installerSidebar.bmp` or `${NSISDIR}\\Contrib\\Graphics\\Wizard\\nsis3-metro.bmp`. Image size 164 × 314 pixels.
*/
readonly installerSidebar?: string | null;
/**
* *assisted installer only.* `MUI_UNWELCOMEFINISHPAGE_BITMAP`, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `installerSidebar` option or `build/uninstallerSidebar.bmp` or `build/installerSidebar.bmp` or `${NSISDIR}\\Contrib\\Graphics\\Wizard\\nsis3-metro.bmp`
*/
readonly uninstallerSidebar?: string | null;
/**
* The uninstaller display name in the control panel.
* @default ${productName} ${version}
*/
readonly uninstallDisplayName?: string;
/**
* The path to NSIS include script to customize installer. Defaults to `build/installer.nsh`. See [Custom NSIS script](#custom-nsis-script).
*/
readonly include?: string | null;
/**
* The path to NSIS script to customize installer. Defaults to `build/installer.nsi`. See [Custom NSIS script](#custom-nsis-script).
*/
readonly script?: string | null;
/**
* The path to EULA license file. Defaults to `license.txt` or `eula.txt` (or uppercase variants). In addition to `txt`, `rtf` and `html` supported (don't forget to use `target="_blank"` for links).
*
* Multiple license files in different languages are supported — use lang postfix (e.g. `_de`, `_ru`). For example, create files `license_de.txt` and `license_en.txt` in the build resources.
* If OS language is german, `license_de.txt` will be displayed. See map of [language code to name](https://github.com/meikidd/iso-639-1/blob/master/src/data.js).
*
* Appropriate license file will be selected by user OS language.
*/
readonly license?: string | null;
/**
* The [artifact file name template](/configuration/configuration#artifact-file-name-template). Defaults to `${productName} Setup ${version}.${ext}`.
*/
readonly artifactName?: string | null;
/**
* *one-click installer only.* Whether to delete app data on uninstall.
* @default false
*/
readonly deleteAppDataOnUninstall?: boolean;
/**
* @private
*/
differentialPackage?: boolean;
/**
* Whether to display a language selection dialog. Not recommended (by default will be detected using OS language).
* @default false
*/
readonly displayLanguageSelector?: boolean;
/**
* The installer languages (e.g. `en_US`, `de_DE`). Change only if you understand what do you do and for what.
*/
readonly installerLanguages?: Array<string> | string | null;
/**
* [LCID Dec](https://msdn.microsoft.com/en-au/goglobal/bb964664.aspx), defaults to `1033`(`English - United States`).
*/
readonly language?: string | null;
/**
* Whether to create multi-language installer. Defaults to `unicode` option value.
*/
readonly multiLanguageInstaller?: boolean;
/**
* Whether to pack the elevate executable (required for electron-updater if per-machine installer used or can be used in the future). Ignored if `perMachine` is set to `true`.
* @default true
*/
readonly packElevateHelper?: boolean;
/**
* The file extension of files that will be not compressed. Applicable only for `extraResources` and `extraFiles` files.
* @default [".avi", ".mov", ".m4v", ".mp4", ".m4p", ".qt", ".mkv", ".webm", ".vmdk"]
*/
readonly preCompressedFileExtensions?: Array<string> | string | null;
}
/**
* Portable options.
*/
export interface PortableOptions extends TargetSpecificOptions, CommonNsisOptions {
/**
* The [requested execution level](http://nsis.sourceforge.net/Reference/RequestExecutionLevel) for Windows.
* @default user
*/
readonly requestExecutionLevel?: "user" | "highest" | "admin";
/**
* The unpack directory for the portable app resources.
*
* If set to a string, it will be the name in [TEMP](https://www.askvg.com/where-does-windows-store-temporary-files-and-how-to-change-temp-folder-location/) directory
* If set explicitly to `false`, it will use the Windows temp directory ($PLUGINSDIR) that is unique to each launch of the portable application.
*
* Defaults to [uuid](https://github.com/segmentio/ksuid) of build (changed on each build of portable executable).
*/
readonly unpackDirName?: string | boolean;
/**
* The image to show while the portable executable is extracting. This image must be a bitmap (`.bmp`) image.
*/
readonly splashImage?: string | null;
}
/**
* Web Installer options.
*/
export interface NsisWebOptions extends NsisOptions {
/**
* The application package download URL. Optional — by default computed using publish configuration.
*
* URL like `https://example.com/download/latest` allows web installer to be version independent (installer will download latest application package).
* Please note — it is [full URL](https://github.com/electron-userland/electron-builder/issues/1810#issuecomment-317650878).
*
* Custom `X-Arch` http header is set to `32` or `64`.
*/
readonly appPackageUrl?: string | null;
/**
* The [artifact file name template](/configuration/configuration#artifact-file-name-template). Defaults to `${productName} Web Setup ${version}.${ext}`.
*/
readonly artifactName?: string | null;
}
export {};

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=nsisOptions.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,11 @@
export declare class NsisScriptGenerator {
private readonly lines;
addIncludeDir(file: string): void;
addPluginDir(pluginArch: string, dir: string): void;
include(file: string): void;
macro(name: string, lines: Array<string> | NsisScriptGenerator): void;
file(outputName: string | null, file: string): void;
insertMacro(name: string, parameters: string): void;
flags(flags: Array<string>): void;
build(): string;
}

View File

@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NsisScriptGenerator = void 0;
class NsisScriptGenerator {
constructor() {
this.lines = [];
}
addIncludeDir(file) {
this.lines.push(`!addincludedir "${file}"`);
}
addPluginDir(pluginArch, dir) {
this.lines.push(`!addplugindir /${pluginArch} "${dir}"`);
}
include(file) {
this.lines.push(`!include "${file}"`);
}
macro(name, lines) {
this.lines.push(`!macro ${name}`, ` ${(Array.isArray(lines) ? lines : lines.lines).join("\n ")}`, `!macroend\n`);
}
file(outputName, file) {
this.lines.push(`File${outputName == null ? "" : ` "/oname=${outputName}"`} "${file}"`);
}
insertMacro(name, parameters) {
this.lines.push(`!insertmacro ${name} ${parameters}`);
}
// without -- !!!
flags(flags) {
for (const flagName of flags) {
const variableName = getVarNameForFlag(flagName).replace(/[-]+(\w|$)/g, (m, p1) => p1.toUpperCase());
this.lines.push(`!macro _${variableName} _a _b _t _f
$\{StdUtils.TestParameter} $R9 "${flagName}"
StrCmp "$R9" "true" \`$\{_t}\` \`$\{_f}\`
!macroend
!define ${variableName} \`"" ${variableName} ""\`
`);
}
}
build() {
return this.lines.join("\n") + "\n";
}
}
exports.NsisScriptGenerator = NsisScriptGenerator;
function getVarNameForFlag(flagName) {
if (flagName === "allusers") {
return "isForAllUsers";
}
if (flagName === "currentuser") {
return "isForCurrentUser";
}
return "is" + flagName[0].toUpperCase() + flagName.substring(1);
}
//# sourceMappingURL=nsisScriptGenerator.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"nsisScriptGenerator.js","sourceRoot":"","sources":["../../../src/targets/nsis/nsisScriptGenerator.ts"],"names":[],"mappings":";;;AAAA,MAAa,mBAAmB;IAAhC;QACmB,UAAK,GAAkB,EAAE,CAAA;IA0C5C,CAAC;IAxCC,aAAa,CAAC,IAAY;QACxB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,IAAI,GAAG,CAAC,CAAA;IAC7C,CAAC;IAED,YAAY,CAAC,UAAkB,EAAE,GAAW;QAC1C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAkB,UAAU,KAAK,GAAG,GAAG,CAAC,CAAA;IAC1D,CAAC;IAED,OAAO,CAAC,IAAY;QAClB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,aAAa,IAAI,GAAG,CAAC,CAAA;IACvC,CAAC;IAED,KAAK,CAAC,IAAY,EAAE,KAA0C;QAC5D,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,IAAI,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,aAAa,CAAC,CAAA;IACpH,CAAC;IAED,IAAI,CAAC,UAAyB,EAAE,IAAY;QAC1C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,UAAU,GAAG,KAAK,IAAI,GAAG,CAAC,CAAA;IACzF,CAAC;IAED,WAAW,CAAC,IAAY,EAAE,UAAkB;QAC1C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,gBAAgB,IAAI,IAAI,UAAU,EAAE,CAAC,CAAA;IACvD,CAAC;IAED,iBAAiB;IACjB,KAAK,CAAC,KAAoB;QACxB,KAAK,MAAM,QAAQ,IAAI,KAAK,EAAE,CAAC;YAC7B,MAAM,YAAY,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,WAAW,EAAE,CAAC,CAAA;YACpG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,YAAY;oCACT,QAAQ;;;UAGlC,YAAY,SAAS,YAAY;CAC1C,CAAC,CAAA;QACE,CAAC;IACH,CAAC;IAED,KAAK;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACrC,CAAC;CACF;AA3CD,kDA2CC;AAED,SAAS,iBAAiB,CAAC,QAAgB;IACzC,IAAI,QAAQ,KAAK,UAAU,EAAE,CAAC;QAC5B,OAAO,eAAe,CAAA;IACxB,CAAC;IACD,IAAI,QAAQ,KAAK,aAAa,EAAE,CAAC;QAC/B,OAAO,kBAAkB,CAAA;IAC3B,CAAC;IACD,OAAO,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;AACjE,CAAC","sourcesContent":["export class NsisScriptGenerator {\n private readonly lines: Array<string> = []\n\n addIncludeDir(file: string) {\n this.lines.push(`!addincludedir \"${file}\"`)\n }\n\n addPluginDir(pluginArch: string, dir: string) {\n this.lines.push(`!addplugindir /${pluginArch} \"${dir}\"`)\n }\n\n include(file: string) {\n this.lines.push(`!include \"${file}\"`)\n }\n\n macro(name: string, lines: Array<string> | NsisScriptGenerator) {\n this.lines.push(`!macro ${name}`, ` ${(Array.isArray(lines) ? lines : lines.lines).join(\"\\n \")}`, `!macroend\\n`)\n }\n\n file(outputName: string | null, file: string) {\n this.lines.push(`File${outputName == null ? \"\" : ` \"/oname=${outputName}\"`} \"${file}\"`)\n }\n\n insertMacro(name: string, parameters: string) {\n this.lines.push(`!insertmacro ${name} ${parameters}`)\n }\n\n // without -- !!!\n flags(flags: Array<string>) {\n for (const flagName of flags) {\n const variableName = getVarNameForFlag(flagName).replace(/[-]+(\\w|$)/g, (m, p1) => p1.toUpperCase())\n this.lines.push(`!macro _${variableName} _a _b _t _f\n $\\{StdUtils.TestParameter} $R9 \"${flagName}\"\n StrCmp \"$R9\" \"true\" \\`$\\{_t}\\` \\`$\\{_f}\\`\n!macroend\n!define ${variableName} \\`\"\" ${variableName} \"\"\\`\n`)\n }\n }\n\n build() {\n return this.lines.join(\"\\n\") + \"\\n\"\n }\n}\n\nfunction getVarNameForFlag(flagName: string): string {\n if (flagName === \"allusers\") {\n return \"isForAllUsers\"\n }\n if (flagName === \"currentuser\") {\n return \"isForCurrentUser\"\n }\n return \"is\" + flagName[0].toUpperCase() + flagName.substring(1)\n}\n"]}

View File

@ -0,0 +1,31 @@
import { Arch } from "builder-util";
import { PackageFileInfo } from "builder-util-runtime";
import { NsisTarget } from "./NsisTarget";
import { NsisOptions } from "./nsisOptions";
export declare const nsisTemplatesDir: string;
export declare const NsisTargetOptions: {
then: (callback: (options: NsisOptions) => any) => Promise<string>;
resolve: (options: NsisOptions) => any;
};
export declare const NSIS_PATH: () => Promise<string>;
export interface PackArchResult {
fileInfo: PackageFileInfo;
unpackedSize: number;
}
export declare class AppPackageHelper {
private readonly elevateHelper;
private readonly archToResult;
private readonly infoToIsDelete;
/** @private */
refCount: number;
constructor(elevateHelper: CopyElevateHelper);
packArch(arch: Arch, target: NsisTarget): Promise<PackArchResult>;
finishBuild(): Promise<any>;
}
export declare class CopyElevateHelper {
private readonly copied;
copy(appOutDir: string, target: NsisTarget): Promise<any>;
}
export declare class UninstallerReader {
static exec(installerPath: string, uninstallerPath: string): Promise<void>;
}

View File

@ -0,0 +1,251 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UninstallerReader = exports.CopyElevateHelper = exports.AppPackageHelper = exports.NSIS_PATH = exports.NsisTargetOptions = exports.nsisTemplatesDir = void 0;
const builder_util_1 = require("builder-util");
const binDownload_1 = require("../../binDownload");
const fs_1 = require("builder-util/out/fs");
const path = require("path");
const pathManager_1 = require("../../util/pathManager");
const fs = require("fs/promises");
const zlib = require("zlib");
exports.nsisTemplatesDir = (0, pathManager_1.getTemplatePath)("nsis");
exports.NsisTargetOptions = (() => {
let _resolve;
const promise = new Promise(resolve => (_resolve = resolve));
return {
then: (callback) => promise.then(callback),
resolve: (options) => _resolve(options),
};
})();
const NSIS_PATH = () => {
const custom = process.env.ELECTRON_BUILDER_NSIS_DIR;
if (custom != null && custom.length > 0) {
return Promise.resolve(custom.trim());
}
return exports.NsisTargetOptions.then((options) => {
if (options.customNsisBinary) {
const { checksum, url, version } = options.customNsisBinary;
if (checksum && url) {
const binaryVersion = version || checksum.substr(0, 8);
return (0, binDownload_1.getBinFromCustomLoc)("nsis", binaryVersion, url, checksum);
}
}
// Warning: Don't use v3.0.4.2 - https://github.com/electron-userland/electron-builder/issues/6334
// noinspection SpellCheckingInspection
return (0, binDownload_1.getBinFromUrl)("nsis", "3.0.4.1", "VKMiizYdmNdJOWpRGz4trl4lD++BvYP2irAXpMilheUP0pc93iKlWAoP843Vlraj8YG19CVn0j+dCo/hURz9+Q==");
});
};
exports.NSIS_PATH = NSIS_PATH;
class AppPackageHelper {
constructor(elevateHelper) {
this.elevateHelper = elevateHelper;
this.archToResult = new Map();
this.infoToIsDelete = new Map();
/** @private */
this.refCount = 0;
}
async packArch(arch, target) {
let resultPromise = this.archToResult.get(arch);
if (resultPromise == null) {
const appOutDir = target.archs.get(arch);
resultPromise = this.elevateHelper
.copy(appOutDir, target)
.then(() => target.buildAppPackage(appOutDir, arch))
.then(async (fileInfo) => ({
fileInfo,
unpackedSize: await (0, fs_1.dirSize)(appOutDir),
}));
this.archToResult.set(arch, resultPromise);
}
const result = await resultPromise;
const { fileInfo: info } = result;
if (target.isWebInstaller) {
this.infoToIsDelete.set(info, false);
}
else if (!this.infoToIsDelete.has(info)) {
this.infoToIsDelete.set(info, true);
}
return result;
}
async finishBuild() {
if (--this.refCount > 0) {
return;
}
const filesToDelete = [];
for (const [info, isDelete] of this.infoToIsDelete.entries()) {
if (isDelete) {
filesToDelete.push(info.path);
}
}
await Promise.all(filesToDelete.map(it => fs.unlink(it)));
}
}
exports.AppPackageHelper = AppPackageHelper;
class CopyElevateHelper {
constructor() {
this.copied = new Map();
}
copy(appOutDir, target) {
if (!target.packager.info.framework.isCopyElevateHelper) {
return Promise.resolve();
}
let isPackElevateHelper = target.options.packElevateHelper;
if (isPackElevateHelper === false && target.options.perMachine === true) {
isPackElevateHelper = true;
builder_util_1.log.warn("`packElevateHelper = false` is ignored, because `perMachine` is set to `true`");
}
if (isPackElevateHelper === false) {
return Promise.resolve();
}
let promise = this.copied.get(appOutDir);
if (promise != null) {
return promise;
}
promise = (0, exports.NSIS_PATH)().then(it => {
const outFile = path.join(appOutDir, "resources", "elevate.exe");
const promise = (0, fs_1.copyFile)(path.join(it, "elevate.exe"), outFile, false);
if (target.packager.platformSpecificBuildOptions.signAndEditExecutable !== false) {
return promise.then(() => target.packager.sign(outFile));
}
return promise;
});
this.copied.set(appOutDir, promise);
return promise;
}
}
exports.CopyElevateHelper = CopyElevateHelper;
class BinaryReader {
constructor(buffer) {
this._buffer = buffer;
this._position = 0;
}
get length() {
return this._buffer.length;
}
get position() {
return this._position;
}
match(signature) {
if (signature.every((v, i) => this._buffer[this._position + i] === v)) {
this._position += signature.length;
return true;
}
return false;
}
skip(offset) {
this._position += offset;
}
bytes(size) {
const value = this._buffer.subarray(this._position, this._position + size);
this._position += size;
return value;
}
uint16() {
const value = this._buffer[this._position] | (this._buffer[this._position + 1] << 8);
this._position += 2;
return value;
}
uint32() {
return this.uint16() | (this.uint16() << 16);
}
string(length) {
let value = "";
for (let i = 0; i < length; i++) {
const c = this._buffer[this._position + i];
if (c === 0x00) {
break;
}
value += String.fromCharCode(c);
}
this._position += length;
return value;
}
}
class UninstallerReader {
// noinspection SpellCheckingInspection
static async exec(installerPath, uninstallerPath) {
const buffer = await fs.readFile(installerPath);
const reader = new BinaryReader(buffer);
// IMAGE_DOS_HEADER
if (!reader.match([0x4d, 0x5a])) {
throw new Error("Invalid 'MZ' signature.");
}
reader.skip(58);
// e_lfanew
reader.skip(reader.uint32() - reader.position);
// IMAGE_FILE_HEADER
if (!reader.match([0x50, 0x45, 0x00, 0x00])) {
throw new Error("Invalid 'PE' signature.");
}
reader.skip(2);
const numberOfSections = reader.uint16();
reader.skip(12);
const sizeOfOptionalHeader = reader.uint16();
reader.skip(2);
reader.skip(sizeOfOptionalHeader);
// IMAGE_SECTION_HEADER
let nsisOffset = 0;
for (let i = 0; i < numberOfSections; i++) {
const name = reader.string(8);
reader.skip(8);
const rawSize = reader.uint32();
const rawPointer = reader.uint32();
reader.skip(16);
switch (name) {
case ".text":
case ".rdata":
case ".data":
case ".rsrc": {
nsisOffset = Math.max(rawPointer + rawSize, nsisOffset);
break;
}
default: {
if (rawPointer !== 0 && rawSize !== 0) {
throw new Error("Unsupported section '" + name + "'.");
}
break;
}
}
}
const executable = buffer.subarray(0, nsisOffset);
const nsisSize = buffer.length - nsisOffset;
const nsisReader = new BinaryReader(buffer.subarray(nsisOffset, nsisOffset + nsisSize));
const nsisSignature = [0xef, 0xbe, 0xad, 0xde, 0x4e, 0x75, 0x6c, 0x6c, 0x73, 0x6f, 0x66, 0x74, 0x49, 0x6e, 0x73, 0x74];
nsisReader.uint32(); // ?
if (!nsisReader.match(nsisSignature)) {
throw new Error("Invalid signature.");
}
nsisReader.uint32(); // ?
if (nsisSize !== nsisReader.uint32()) {
throw new Error("Size mismatch.");
}
let innerBuffer = null;
while (true) {
let size = nsisReader.uint32();
const compressed = (size & 0x80000000) !== 0;
size = size & 0x7fffffff;
if (size === 0 || nsisReader.position + size > nsisReader.length || nsisReader.position >= nsisReader.length) {
break;
}
let buffer = nsisReader.bytes(size);
if (compressed) {
buffer = zlib.inflateRawSync(buffer);
}
const innerReader = new BinaryReader(buffer);
innerReader.uint32(); // ?
if (innerReader.match(nsisSignature)) {
if (innerBuffer) {
throw new Error("Multiple inner blocks.");
}
innerBuffer = buffer;
}
}
if (!innerBuffer) {
throw new Error("Inner block not found.");
}
await fs.writeFile(uninstallerPath, executable);
await fs.appendFile(uninstallerPath, innerBuffer);
}
}
exports.UninstallerReader = UninstallerReader;
//# sourceMappingURL=nsisUtil.js.map

File diff suppressed because one or more lines are too long