AppxTarget.js 16.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _bluebirdLst() {
  const data = _interopRequireDefault(require("bluebird-lst"));

  _bluebirdLst = function () {
    return data;
  };

  return data;
}

function _builderUtil() {
  const data = require("builder-util");

  _builderUtil = function () {
    return data;
  };

  return data;
}

function _fs() {
  const data = require("builder-util/out/fs");

  _fs = function () {
    return data;
  };

  return data;
}

function _fsExtra() {
  const data = require("fs-extra");

  _fsExtra = function () {
    return data;
  };

  return data;
}

var path = _interopRequireWildcard(require("path"));

function _windowsCodeSign() {
  const data = require("../codeSign/windowsCodeSign");

  _windowsCodeSign = function () {
    return data;
  };

  return data;
}

function _core() {
  const data = require("../core");

  _core = function () {
    return data;
  };

  return data;
}

function _pathManager() {
  const data = require("../util/pathManager");

  _pathManager = function () {
    return data;
  };

  return data;
}

function _targetUtil() {
  const data = require("./targetUtil");

  _targetUtil = function () {
    return data;
  };

  return data;
}

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _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; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const APPX_ASSETS_DIR_NAME = "appx";
const vendorAssetsForDefaultAssets = {
  "StoreLogo.png": "SampleAppx.50x50.png",
  "Square150x150Logo.png": "SampleAppx.150x150.png",
  "Square44x44Logo.png": "SampleAppx.44x44.png",
  "Wide310x150Logo.png": "SampleAppx.310x150.png"
};
const DEFAULT_RESOURCE_LANG = "en-US";

class AppXTarget extends _core().Target {
  constructor(packager, outDir) {
    super("appx");
    this.packager = packager;
    this.outDir = outDir;
    this.options = (0, _builderUtil().deepAssign)({}, this.packager.platformSpecificBuildOptions, this.packager.config.appx);

    if (process.platform !== "darwin" && (process.platform !== "win32" || (0, _windowsCodeSign().isOldWin6)())) {
      throw new Error("AppX is supported only on Windows 10 or Windows Server 2012 R2 (version number 6.3+)");
    }
  } // https://docs.microsoft.com/en-us/windows/uwp/packaging/create-app-package-with-makeappx-tool#mapping-files


  async build(appOutDir, arch) {
    const packager = this.packager;
    const artifactName = packager.expandArtifactBeautyNamePattern(this.options, "appx", arch);
    const artifactPath = path.join(this.outDir, artifactName);
    await packager.info.callArtifactBuildStarted({
      targetPresentableName: "AppX",
      file: artifactPath,
      arch
    });
    const vendorPath = await (0, _windowsCodeSign().getSignVendorPath)();
    const vm = await packager.vm.value;
    const stageDir = await (0, _targetUtil().createStageDir)(this, packager, arch);
    const mappingFile = stageDir.getTempFile("mapping.txt");
    const makeAppXArgs = ["pack", "/o"
    /* overwrite the output file if it exists */
    , "/f", vm.toVmFile(mappingFile), "/p", vm.toVmFile(artifactPath)];

    if (packager.compression === "store") {
      makeAppXArgs.push("/nc");
    }

    const mappingList = [];
    mappingList.push(await _bluebirdLst().default.map((0, _fs().walk)(appOutDir), file => {
      let appxPath = file.substring(appOutDir.length + 1);

      if (path.sep !== "\\") {
        appxPath = appxPath.replace(/\//g, "\\");
      }

      return `"${vm.toVmFile(file)}" "app\\${appxPath}"`;
    }));
    const userAssetDir = await this.packager.getResource(undefined, APPX_ASSETS_DIR_NAME);
    const assetInfo = await AppXTarget.computeUserAssets(vm, vendorPath, userAssetDir);
    const userAssets = assetInfo.userAssets;
    const manifestFile = stageDir.getTempFile("AppxManifest.xml");
    await this.writeManifest(manifestFile, arch, await this.computePublisherName(), userAssets);
    await packager.info.callAppxManifestCreated(manifestFile);
    mappingList.push(assetInfo.mappings);
    mappingList.push([`"${vm.toVmFile(manifestFile)}" "AppxManifest.xml"`]);
    const signToolArch = arch === _builderUtil().Arch.arm64 ? "x64" : _builderUtil().Arch[arch];

    if (isScaledAssetsProvided(userAssets)) {
      const outFile = vm.toVmFile(stageDir.getTempFile("resources.pri"));
      const makePriPath = vm.toVmFile(path.join(vendorPath, "windows-10", signToolArch, "makepri.exe"));
      const assetRoot = stageDir.getTempFile("appx/assets");
      await (0, _fsExtra().emptyDir)(assetRoot);
      await _bluebirdLst().default.map(assetInfo.allAssets, it => (0, _fs().copyOrLinkFile)(it, path.join(assetRoot, path.basename(it))));
      await vm.exec(makePriPath, ["new", "/Overwrite", "/Manifest", vm.toVmFile(manifestFile), "/ProjectRoot", vm.toVmFile(path.dirname(assetRoot)), "/ConfigXml", vm.toVmFile(path.join((0, _pathManager().getTemplatePath)("appx"), "priconfig.xml")), "/OutputFile", outFile]); // in addition to resources.pri, resources.scale-140.pri and other such files will be generated

      for (const resourceFile of (await (0, _fsExtra().readdir)(stageDir.dir)).filter(it => it.startsWith("resources.")).sort()) {
        mappingList.push([`"${vm.toVmFile(stageDir.getTempFile(resourceFile))}" "${resourceFile}"`]);
      }

      makeAppXArgs.push("/l");
    }

    let mapping = "[Files]";

    for (const list of mappingList) {
      mapping += "\r\n" + list.join("\r\n");
    }

    await (0, _fsExtra().writeFile)(mappingFile, mapping);
    packager.debugLogger.add("appx.mapping", mapping);

    if (this.options.makeappxArgs != null) {
      makeAppXArgs.push(...this.options.makeappxArgs);
    }

    await vm.exec(vm.toVmFile(path.join(vendorPath, "windows-10", signToolArch, "makeappx.exe")), makeAppXArgs);
    await packager.sign(artifactPath);
    await stageDir.cleanup();
    await packager.info.callArtifactBuildCompleted({
      file: artifactPath,
      packager,
      arch,
      safeArtifactName: packager.computeSafeArtifactName(artifactName, "appx"),
      target: this,
      isWriteUpdateInfo: this.options.electronUpdaterAware
    });
  }

  static async computeUserAssets(vm, vendorPath, userAssetDir) {
    const mappings = [];
    let userAssets;
    const allAssets = [];

    if (userAssetDir == null) {
      userAssets = [];
    } else {
      userAssets = (await (0, _fsExtra().readdir)(userAssetDir)).filter(it => !it.startsWith(".") && !it.endsWith(".db") && it.includes("."));

      for (const name of userAssets) {
        mappings.push(`"${vm.toVmFile(userAssetDir)}${vm.pathSep}${name}" "assets\\${name}"`);
        allAssets.push(path.join(userAssetDir, name));
      }
    }

    for (const defaultAsset of Object.keys(vendorAssetsForDefaultAssets)) {
      if (userAssets.length === 0 || !isDefaultAssetIncluded(userAssets, defaultAsset)) {
        const file = path.join(vendorPath, "appxAssets", vendorAssetsForDefaultAssets[defaultAsset]);
        mappings.push(`"${vm.toVmFile(file)}" "assets\\${defaultAsset}"`);
        allAssets.push(file);
      }
    } // we do not use process.arch to build path to tools, because even if you are on x64, ia32 appx tool must be used if you build appx for ia32


    return {
      userAssets,
      mappings,
      allAssets
    };
  } // https://github.com/electron-userland/electron-builder/issues/2108#issuecomment-333200711


  async computePublisherName() {
    if ((await this.packager.cscInfo.value) == null) {
      _builderUtil().log.info({
        reason: "Windows Store only build"
      }, "AppX is not signed");

      return this.options.publisher || "CN=ms";
    }

    const certInfo = await this.packager.lazyCertInfo.value;
    const publisher = this.options.publisher || (certInfo == null ? null : certInfo.bloodyMicrosoftSubjectDn);

    if (publisher == null) {
      throw new Error("Internal error: cannot compute subject using certificate info");
    }

    return publisher;
  }

  async writeManifest(outFile, arch, publisher, userAssets) {
    const appInfo = this.packager.appInfo;
    const options = this.options;
    const executable = `app\\${appInfo.productFilename}.exe`;
    const displayName = options.displayName || appInfo.productName;
    const extensions = await this.getExtensions(executable, displayName);
    const manifest = (await (0, _fsExtra().readFile)(path.join((0, _pathManager().getTemplatePath)("appx"), "appxmanifest.xml"), "utf8")).replace(/\${([a-zA-Z0-9]+)}/g, (match, p1) => {
      switch (p1) {
        case "publisher":
          return publisher;

        case "publisherDisplayName":
          {
            const name = options.publisherDisplayName || appInfo.companyName;

            if (name == null) {
              throw new (_builderUtil().InvalidConfigurationError)(`Please specify "author" in the application package.json — it is required because "appx.publisherDisplayName" is not set.`);
            }

            return name;
          }

        case "version":
          return appInfo.getVersionInWeirdWindowsForm(options.setBuildNumber === true);

        case "applicationId":
          {
            const result = options.applicationId || options.identityName || appInfo.name;

            if (!isNaN(parseInt(result[0], 10))) {
              let message = `AppX Application.Id can’t start with numbers: "${result}"`;

              if (options.applicationId == null) {
                message += `\nPlease set appx.applicationId (or correct appx.identityName or name)`;
              }

              throw new (_builderUtil().InvalidConfigurationError)(message);
            }

            return result;
          }

        case "identityName":
          return options.identityName || appInfo.name;

        case "executable":
          return executable;

        case "displayName":
          return displayName;

        case "description":
          return appInfo.description || appInfo.productName;

        case "backgroundColor":
          return options.backgroundColor || "#464646";

        case "logo":
          return "assets\\StoreLogo.png";

        case "square150x150Logo":
          return "assets\\Square150x150Logo.png";

        case "square44x44Logo":
          return "assets\\Square44x44Logo.png";

        case "lockScreen":
          return lockScreenTag(userAssets);

        case "defaultTile":
          return defaultTileTag(userAssets, options.showNameOnTiles || false);

        case "splashScreen":
          return splashScreenTag(userAssets);

        case "arch":
          return arch === _builderUtil().Arch.ia32 ? "x86" : arch === _builderUtil().Arch.arm64 ? "arm64" : "x64";

        case "resourceLanguages":
          return resourceLanguageTag((0, _builderUtil().asArray)(options.languages));

        case "extensions":
          return extensions;

        case "minVersion":
          return arch === _builderUtil().Arch.arm64 ? "10.0.16299.0" : "10.0.14316.0";

        case "maxVersionTested":
          return arch === _builderUtil().Arch.arm64 ? "10.0.16299.0" : "10.0.14316.0";

        default:
          throw new Error(`Macro ${p1} is not defined`);
      }
    });
    await (0, _fsExtra().writeFile)(outFile, manifest);
  }

  async getExtensions(executable, displayName) {
    const uriSchemes = (0, _builderUtil().asArray)(this.packager.config.protocols).concat((0, _builderUtil().asArray)(this.packager.platformSpecificBuildOptions.protocols));
    const fileAssociations = (0, _builderUtil().asArray)(this.packager.config.fileAssociations).concat((0, _builderUtil().asArray)(this.packager.platformSpecificBuildOptions.fileAssociations));
    let isAddAutoLaunchExtension = this.options.addAutoLaunchExtension;

    if (isAddAutoLaunchExtension === undefined) {
      const deps = this.packager.info.metadata.dependencies;
      isAddAutoLaunchExtension = deps != null && deps["electron-winstore-auto-launch"] != null;
    }

    if (!isAddAutoLaunchExtension && uriSchemes.length === 0 && fileAssociations.length === 0 && this.options.customExtensionsPath === undefined) {
      return "";
    }

    let extensions = "<Extensions>";

    if (isAddAutoLaunchExtension) {
      extensions += `
        <desktop:Extension Category="windows.startupTask" Executable="${executable}" EntryPoint="Windows.FullTrustApplication">
          <desktop:StartupTask TaskId="SlackStartup" Enabled="true" DisplayName="${displayName}" />
        </desktop:Extension>`;
    }

    for (const protocol of uriSchemes) {
      for (const scheme of (0, _builderUtil().asArray)(protocol.schemes)) {
        extensions += `
          <uap:Extension Category="windows.protocol">
            <uap:Protocol Name="${scheme}">
               <uap:DisplayName>${protocol.name}</uap:DisplayName>
             </uap:Protocol>
          </uap:Extension>`;
      }
    }

    for (const fileAssociation of fileAssociations) {
      for (const ext of (0, _builderUtil().asArray)(fileAssociation.ext)) {
        extensions += `
          <uap:Extension Category="windows.fileTypeAssociation">
            <uap:FileTypeAssociation Name="${ext}">
              <uap:SupportedFileTypes>
                <uap:FileType>.${ext}</uap:FileType>
              </uap:SupportedFileTypes>
            </uap:FileTypeAssociation>
          </uap:Extension>`;
      }
    }

    if (this.options.customExtensionsPath !== undefined) {
      const extensionsPath = path.resolve(this.packager.info.appDir, this.options.customExtensionsPath);
      extensions += await (0, _fsExtra().readFile)(extensionsPath, "utf8");
    }

    extensions += "</Extensions>";
    return extensions;
  }

} // get the resource - language tag, see https://docs.microsoft.com/en-us/windows/uwp/globalizing/manage-language-and-region#specify-the-supported-languages-in-the-apps-manifest


exports.default = AppXTarget;

function resourceLanguageTag(userLanguages) {
  if (userLanguages == null || userLanguages.length === 0) {
    userLanguages = [DEFAULT_RESOURCE_LANG];
  }

  return userLanguages.map(it => `<Resource Language="${it.replace(/_/g, "-")}" />`).join("\n");
}

function lockScreenTag(userAssets) {
  if (isDefaultAssetIncluded(userAssets, "BadgeLogo.png")) {
    return '<uap:LockScreen Notification="badgeAndTileText" BadgeLogo="assets\\BadgeLogo.png" />';
  } else {
    return "";
  }
}

function defaultTileTag(userAssets, showNameOnTiles) {
  const defaultTiles = ["<uap:DefaultTile", 'Wide310x150Logo="assets\\Wide310x150Logo.png"'];

  if (isDefaultAssetIncluded(userAssets, "LargeTile.png")) {
    defaultTiles.push('Square310x310Logo="assets\\LargeTile.png"');
  }

  if (isDefaultAssetIncluded(userAssets, "SmallTile.png")) {
    defaultTiles.push('Square71x71Logo="assets\\SmallTile.png"');
  }

  if (showNameOnTiles) {
    defaultTiles.push(">");
    defaultTiles.push("<uap:ShowNameOnTiles>");
    defaultTiles.push("<uap:ShowOn", 'Tile="wide310x150Logo"', "/>");
    defaultTiles.push("<uap:ShowOn", 'Tile="square150x150Logo"', "/>");
    defaultTiles.push("</uap:ShowNameOnTiles>");
    defaultTiles.push("</uap:DefaultTile>");
  } else {
    defaultTiles.push("/>");
  }

  return defaultTiles.join(" ");
}

function splashScreenTag(userAssets) {
  if (isDefaultAssetIncluded(userAssets, "SplashScreen.png")) {
    return '<uap:SplashScreen Image="assets\\SplashScreen.png" />';
  } else {
    return "";
  }
}

function isDefaultAssetIncluded(userAssets, defaultAsset) {
  const defaultAssetName = defaultAsset.substring(0, defaultAsset.indexOf("."));
  return userAssets.some(it => it.includes(defaultAssetName));
}

function isScaledAssetsProvided(userAssets) {
  return userAssets.some(it => it.includes(".scale-") || it.includes(".targetsize-"));
} 
// __ts-babel@6.0.4
//# sourceMappingURL=AppxTarget.js.map