Add prettier and re-format .js files

This commit is contained in:
hensm
2021-08-31 07:59:58 +01:00
parent 9339b1a306
commit d6ca1325dc
38 changed files with 908 additions and 13254 deletions

5
.prettierrc.json Normal file
View File

@@ -0,0 +1,5 @@
{
"arrowParens": "avoid",
"tabWidth": 4,
"trailingComma": "none"
}

View File

@@ -13,40 +13,36 @@ const { spawnSync } = require("child_process");
const meta = require("../package.json"); const meta = require("../package.json");
const paths = require("./lib/paths"); const paths = require("./lib/paths");
const { author const { author, homepage } = require("../../package.json");
, homepage } = require("../../package.json");
const EXTENSION_ID = "fx_cast@matt.tf"; const EXTENSION_ID = "fx_cast@matt.tf";
// Command line args // Command line args
const argv = minimist(process.argv.slice(2), { const argv = minimist(process.argv.slice(2), {
boolean: [ "usePkg", "package", "skipNativeBuilds" ] boolean: ["usePkg", "package", "skipNativeBuilds"],
, string: [ "arch", "packageType" ] string: ["arch", "packageType"],
, default: { default: {
arch: os.arch() arch: os.arch(),
, package: false package: false,
// Linux package type (deb/rpm) // Linux package type (deb/rpm)
, packageType: "deb" packageType: "deb",
, skipNativeBuilds: false skipNativeBuilds: false
} }
}); });
const supportedTargets = [ const supportedTargets = [
"win-x64" "win-x64",
, "win-x86" "win-x86",
, "macos-x64" "macos-x64",
, "macos-arm64" "macos-arm64",
, "linux-x64" "linux-x64"
]; ];
const supportedPlatforms = []; const supportedPlatforms = [];
const supportedArchs = []; const supportedArchs = [];
for (const target of supportedTargets) { for (const target of supportedTargets) {
const [ platform, arch ] = target.split("-"); const [platform, arch] = target.split("-");
supportedPlatforms.push(platform); supportedPlatforms.push(platform);
supportedArchs.push(arch); supportedArchs.push(arch);
@@ -61,14 +57,13 @@ if (!supportedArchs.includes(argv.arch)) {
process.exit(1); process.exit(1);
} }
const ROOT_PATH = path.join(__dirname, ".."); const ROOT_PATH = path.join(__dirname, "..");
const SRC_PATH = path.join(ROOT_PATH, "src"); const SRC_PATH = path.join(ROOT_PATH, "src");
const BUILD_PATH = path.join(ROOT_PATH, "build"); const BUILD_PATH = path.join(ROOT_PATH, "build");
const spawnOptions = { const spawnOptions = {
shell: true shell: true,
, stdio: [ process.stdin, process.stdout, process.stderr ] stdio: [process.stdin, process.stdout, process.stderr]
}; };
/** /**
@@ -80,26 +75,29 @@ fs.removeSync(paths.DIST_PATH, { recursive: true });
fs.ensureDirSync(BUILD_PATH); fs.ensureDirSync(BUILD_PATH);
fs.ensureDirSync(paths.DIST_PATH, { recursive: true }); fs.ensureDirSync(paths.DIST_PATH, { recursive: true });
const MDNS_BINDING_PATH = path.join( const MDNS_BINDING_PATH = path.join(
__dirname, "../node_modules/mdns/build/Release/"); __dirname,
"../node_modules/mdns/build/Release/"
);
const MDNS_BINDING_NAME = "dns_sd_bindings.node"; const MDNS_BINDING_NAME = "dns_sd_bindings.node";
async function build () { async function build() {
// Run tsc // Run tsc
spawnSync(`tsc --project ${ROOT_PATH} \ spawnSync(
--outDir ${BUILD_PATH}` `tsc --project ${ROOT_PATH}
, spawnOptions); --outDir ${BUILD_PATH}`,
spawnOptions
);
/** /**
* Native app manifest * Native app manifest
* https://mdn.io/Native_manifests#Native_messaging_manifests * https://mdn.io/Native_manifests#Native_messaging_manifests
*/ */
const manifest = { const manifest = {
"name": meta.__applicationName name: meta.__applicationName,
, "description": "" description: "",
, "type": "stdio" type: "stdio",
, "allowed_extensions": [ EXTENSION_ID ] allowed_extensions: [EXTENSION_ID]
}; };
/** /**
@@ -109,63 +107,80 @@ async function build () {
if (argv.package || argv.usePkg) { if (argv.package || argv.usePkg) {
// Need a minimal package.json for pkg. // Need a minimal package.json for pkg.
const pkgManifest = { const pkgManifest = {
bin: "main.js" bin: "main.js",
, pkg: { pkg: {
/** /**
* Workaround for pkg asset detection * Workaround for pkg asset detection
* https://github.com/thibauts/node-castv2/issues/46 * https://github.com/thibauts/node-castv2/issues/46
*/ */
"assets": "../../node_modules/castv2/lib/cast_channel.proto" assets: "../../node_modules/castv2/lib/cast_channel.proto"
} }
}; };
const executableName = paths.getExecutableName(process.platform); const executableName = paths.getExecutableName(process.platform);
const executablePath = paths.getExecutablePath(process.platform, argv.arch); const executablePath = paths.getExecutablePath(
process.platform,
argv.arch
);
// Write pkg manifest // Write pkg manifest
fs.writeFileSync(path.join(BUILD_PATH, "src/package.json") fs.writeFileSync(
, JSON.stringify(pkgManifest)) path.join(BUILD_PATH, "src/package.json"),
JSON.stringify(pkgManifest)
);
// Run pkg to create a single executable // Run pkg to create a single executable
await pkg.exec([ await pkg.exec([
path.join(BUILD_PATH, "src") path.join(BUILD_PATH, "src"),
, "--target", `node12-${paths.pkgPlatformMap[process.platform]}-${argv.arch}` "--target",
, "--output", path.join(BUILD_PATH, executableName) `node12-${paths.pkgPlatformMap[process.platform]}-${argv.arch}`,
"--output",
path.join(BUILD_PATH, executableName)
]); ]);
fs.copySync(path.join(MDNS_BINDING_PATH, MDNS_BINDING_NAME) fs.copySync(
, path.join(BUILD_PATH, MDNS_BINDING_NAME)); path.join(MDNS_BINDING_PATH, MDNS_BINDING_NAME),
path.join(BUILD_PATH, MDNS_BINDING_NAME)
);
fs.removeSync(path.join(BUILD_PATH, "src")); fs.removeSync(path.join(BUILD_PATH, "src"));
manifest.path = !argv.package && argv.usePkg manifest.path =
? path.join(paths.DIST_PATH, executableName) !argv.package && argv.usePkg
: path.join(executablePath, executableName); ? path.join(paths.DIST_PATH, executableName)
: path.join(executablePath, executableName);
} else { } else {
let launcherPath = path.join(BUILD_PATH let launcherPath = path.join(
, meta.__applicationExecutableName); BUILD_PATH,
meta.__applicationExecutableName
);
const modulesDir = path.join(ROOT_PATH, "node_modules"); const modulesDir = path.join(ROOT_PATH, "node_modules");
// Write launcher script
switch (process.platform) { switch (process.platform) {
case "win32": { case "win32": {
launcherPath += ".bat"; launcherPath += ".bat";
fs.writeFileSync(launcherPath, fs.writeFileSync(
`@echo off launcherPath,
`@echo off
setlocal setlocal
set NODE_PATH=${modulesDir} set NODE_PATH=${modulesDir}
node %~dp0src\\main.js --__name %~n0%~x0 %* node %~dp0src\\main.js --__name %~n0%~x0 %*
endlocal endlocal
`); `
);
break; break;
} }
case "linux": case "linux":
case "darwin": { case "darwin": {
launcherPath += ".sh"; launcherPath += ".sh";
fs.writeFileSync(launcherPath, fs.writeFileSync(
`#!/usr/bin/env sh launcherPath,
`#!/usr/bin/env sh
NODE_PATH="${modulesDir}" node $(dirname $0)/src/main.js --__name $(basename $0) "$@" NODE_PATH="${modulesDir}" node $(dirname $0)/src/main.js --__name $(basename $0) "$@"
`); `
);
break; break;
} }
} }
@@ -173,11 +188,11 @@ NODE_PATH="${modulesDir}" node $(dirname $0)/src/main.js --__name $(basename $0)
manifest.path = path.join(paths.DIST_PATH, path.basename(launcherPath)); manifest.path = path.join(paths.DIST_PATH, path.basename(launcherPath));
} }
// Write app manifest // Write app manifest
fs.writeFileSync(path.join(BUILD_PATH, paths.MANIFEST_NAME) fs.writeFileSync(
, JSON.stringify(manifest, null, 4)); path.join(BUILD_PATH, paths.MANIFEST_NAME),
JSON.stringify(manifest, null, 4)
);
// Ensure file permissions are correct // Ensure file permissions are correct
for (const file of fs.readdirSync(BUILD_PATH)) { for (const file of fs.readdirSync(BUILD_PATH)) {
@@ -194,19 +209,20 @@ NODE_PATH="${modulesDir}" node $(dirname $0)/src/main.js --__name $(basename $0)
if (installerName) { if (installerName) {
// Move installer to dist // Move installer to dist
fs.moveSync( fs.moveSync(
path.join(BUILD_PATH, installerName) path.join(BUILD_PATH, installerName),
, path.join(paths.DIST_PATH, path.basename(installerName)) path.join(paths.DIST_PATH, path.basename(installerName)),
, { overwrite: true }); { overwrite: true }
);
} }
} else { } else {
// Move tsc output and launcher to dist // Move tsc output and launcher to dist
fs.moveSync(BUILD_PATH, paths.DIST_PATH, { overwrite: true }); fs.moveSync(BUILD_PATH, paths.DIST_PATH, { overwrite: true });
/* /*
spawnSync("npm install --production", { spawnSync("npm install --production", {
...spawnOptions ...spawnOptions
, cwd: paths.DIST_PATH , cwd: paths.DIST_PATH
}); });
*/ */
} }
// Remove build directory // Remove build directory
@@ -217,31 +233,34 @@ NODE_PATH="${modulesDir}" node $(dirname $0)/src/main.js --__name $(basename $0)
* Takes a platform and returns the path of the created * Takes a platform and returns the path of the created
* installer package. * installer package.
*/ */
async function packageApp (platform, arch) { async function packageApp(platform, arch) {
const packageFunctionArgs = [ const packageFunctionArgs = [
arch arch,
// platformExecutableName // platformExecutableName
, paths.getExecutableName(platform, arch) paths.getExecutableName(platform, arch),
// platformExecutablePath // platformExecutablePath
, paths.getExecutablePath(platform, arch) paths.getExecutablePath(platform, arch),
// platformManifestPath // platformManifestPath
, paths.getManifestPath(platform, arch, argv.packageType) paths.getManifestPath(platform, arch, argv.packageType)
]; ];
switch (platform) { switch (platform) {
case "win32": return packageWin32(...packageFunctionArgs); case "win32":
case "darwin": return packageDarwin(...packageFunctionArgs); return packageWin32(...packageFunctionArgs);
case "darwin":
return packageDarwin(...packageFunctionArgs);
case "linux": { case "linux": {
switch (argv.packageType) { switch (argv.packageType) {
case "deb": return packageLinuxDeb(...packageFunctionArgs); case "deb":
case "rpm": return packageLinuxRpm(...packageFunctionArgs); return packageLinuxDeb(...packageFunctionArgs);
case "rpm":
return packageLinuxRpm(...packageFunctionArgs);
} }
break; break;
} }
default: { default: {
console.error("Unsupported target platform"); console.error("Unsupported target platform");
process.exit(1); process.exit(1);
@@ -262,14 +281,13 @@ async function packageApp (platform, arch) {
* Requires the pkgbuild and productbuild command line * Requires the pkgbuild and productbuild command line
* utilities. Only possible on macOS. * utilities. Only possible on macOS.
*/ */
function packageDarwin ( function packageDarwin(
arch arch,
, platformExecutableName platformExecutableName,
, platformExecutablePath platformExecutablePath,
, platformManifestPath) { platformManifestPath
) {
const outputName = `${meta.__applicationName}-${ const outputName = `${meta.__applicationName}-${meta.__applicationVersion}-${arch}.pkg`;
meta.__applicationVersion}-${arch}.pkg`;
const componentName = `${meta.__applicationName}_component.pkg`; const componentName = `${meta.__applicationName}_component.pkg`;
const packagingDir = path.join(__dirname, "../packaging/mac/"); const packagingDir = path.join(__dirname, "../packaging/mac/");
@@ -285,30 +303,35 @@ function packageDarwin (
fs.ensureDirSync(rootManifestPath, { recursive: true }); fs.ensureDirSync(rootManifestPath, { recursive: true });
// Move files to root // Move files to root
fs.moveSync(path.join(BUILD_PATH, platformExecutableName) fs.moveSync(
, path.join(rootExecutablePath, platformExecutableName)); path.join(BUILD_PATH, platformExecutableName),
fs.moveSync(path.join(BUILD_PATH, MDNS_BINDING_NAME) path.join(rootExecutablePath, platformExecutableName)
, path.join(rootExecutablePath, MDNS_BINDING_NAME)); );
fs.moveSync(path.join(BUILD_PATH, paths.MANIFEST_NAME) fs.moveSync(
, path.join(rootManifestPath, paths.MANIFEST_NAME)); path.join(BUILD_PATH, MDNS_BINDING_NAME),
path.join(rootExecutablePath, MDNS_BINDING_NAME)
);
fs.moveSync(
path.join(BUILD_PATH, paths.MANIFEST_NAME),
path.join(rootManifestPath, paths.MANIFEST_NAME)
);
// Copy static files to be processed // Copy static files to be processed
fs.copySync(packagingDir, packagingOutputDir); fs.copySync(packagingDir, packagingOutputDir);
const view = { const view = {
applicationName: meta.__applicationName applicationName: meta.__applicationName,
, manifestName: paths.MANIFEST_NAME manifestName: paths.MANIFEST_NAME,
, componentName componentName,
, packageId: `tf.matt.${meta.__applicationName}` packageId: `tf.matt.${meta.__applicationName}`,
, executablePath: platformExecutablePath executablePath: platformExecutablePath,
, manifestPath: platformManifestPath manifestPath: platformManifestPath
}; };
// Template paths // Template paths
const templatePaths = [ const templatePaths = [
path.join(packagingOutputDir, "scripts/postinstall") path.join(packagingOutputDir, "scripts/postinstall"),
, path.join(packagingOutputDir, "distribution.xml") path.join(packagingOutputDir, "distribution.xml")
]; ];
// Do templating on static files // Do templating on static files
@@ -317,25 +340,26 @@ function packageDarwin (
fs.writeFileSync(templatePath, mustache.render(templateContent, view)); fs.writeFileSync(templatePath, mustache.render(templateContent, view));
} }
// Build component package // Build component package
spawnSync(` spawnSync(
pkgbuild --root ${rootPath} \ `pkgbuild --root ${rootPath} \
--identifier "tf.matt.${meta.__applicationName}" \ --identifier "tf.matt.${meta.__applicationName}" \
--version "${meta.__applicationVersion}" \ --version "${meta.__applicationVersion}" \
--scripts ${path.join(packagingOutputDir, "scripts")} \ --scripts ${path.join(packagingOutputDir, "scripts")} \
${path.join(BUILD_PATH, componentName)}` ${path.join(BUILD_PATH, componentName)}`,
, spawnOptions); spawnOptions
);
// Distribution XML file // Distribution XML file
const distFilePath = path.join(packagingOutputDir, "distribution.xml"); const distFilePath = path.join(packagingOutputDir, "distribution.xml");
// Build installer package // Build installer package
spawnSync(` spawnSync(
productbuild --distribution ${distFilePath} \ `productbuild --distribution ${distFilePath} \
--package-path ${BUILD_PATH} \ --package-path ${BUILD_PATH} \
${path.join(BUILD_PATH, outputName)}` ${path.join(BUILD_PATH, outputName)}`,
, spawnOptions); spawnOptions
);
return outputName; return outputName;
} }
@@ -349,14 +373,13 @@ function packageDarwin (
* package from root. * package from root.
* Requires the dpkg-deb command line utility. * Requires the dpkg-deb command line utility.
*/ */
function packageLinuxDeb ( function packageLinuxDeb(
arch arch,
, platformExecutableName platformExecutableName,
, platformExecutablePath platformExecutablePath,
, platformManifestPath) { platformManifestPath
) {
const outputName = `${meta.__applicationName}-${ const outputName = `${meta.__applicationName}-${meta.__applicationVersion}-${arch}.deb`;
meta.__applicationVersion}-${arch}.deb`;
// Create root // Create root
const rootPath = path.join(BUILD_PATH, "root"); const rootPath = path.join(BUILD_PATH, "root");
@@ -367,12 +390,18 @@ function packageLinuxDeb (
fs.ensureDirSync(rootManifestPath, { recursive: true }); fs.ensureDirSync(rootManifestPath, { recursive: true });
// Move files to root // Move files to root
fs.moveSync(path.join(BUILD_PATH, platformExecutableName) fs.moveSync(
, path.join(rootExecutablePath, platformExecutableName)); path.join(BUILD_PATH, platformExecutableName),
fs.moveSync(path.join(BUILD_PATH, MDNS_BINDING_NAME) path.join(rootExecutablePath, platformExecutableName)
, path.join(rootExecutablePath, MDNS_BINDING_NAME)); );
fs.moveSync(path.join(BUILD_PATH, paths.MANIFEST_NAME) fs.moveSync(
, path.join(rootManifestPath, paths.MANIFEST_NAME)); path.join(BUILD_PATH, MDNS_BINDING_NAME),
path.join(rootExecutablePath, MDNS_BINDING_NAME)
);
fs.moveSync(
path.join(BUILD_PATH, paths.MANIFEST_NAME),
path.join(rootManifestPath, paths.MANIFEST_NAME)
);
const controlDir = path.join(__dirname, "../packaging/linux/deb/DEBIAN/"); const controlDir = path.join(__dirname, "../packaging/linux/deb/DEBIAN/");
const controlOutputDir = path.join(rootPath, path.basename(controlDir)); const controlOutputDir = path.join(rootPath, path.basename(controlDir));
@@ -383,23 +412,24 @@ function packageLinuxDeb (
const view = { const view = {
// Debian package names can't contain underscores // Debian package names can't contain underscores
packageName: meta.__applicationName.replace(/_/g, "-") packageName: meta.__applicationName.replace(/_/g, "-"),
, applicationName: meta.__applicationName applicationName: meta.__applicationName,
, applicationVersion: meta.__applicationVersion applicationVersion: meta.__applicationVersion,
, author author
}; };
// Do templating on control file // Do templating on control file
fs.writeFileSync(controlFilePath fs.writeFileSync(
, mustache.render( controlFilePath,
fs.readFileSync(controlFilePath).toString() mustache.render(fs.readFileSync(controlFilePath).toString(), view)
, view)); );
// Build .deb package // Build .deb package
spawnSync(` spawnSync(
dpkg-deb --build ${rootPath} \ `dpkg-deb --build ${rootPath} \
${path.join(BUILD_PATH, outputName)}` ${path.join(BUILD_PATH, outputName)}`,
, spawnOptions); spawnOptions
);
return outputName; return outputName;
} }
@@ -411,48 +441,47 @@ function packageLinuxDeb (
* (packaging/linux/rpm/package.spec) to build the package. * (packaging/linux/rpm/package.spec) to build the package.
* Requires the rpmbuild command line utility. * Requires the rpmbuild command line utility.
*/ */
function packageLinuxRpm ( function packageLinuxRpm(
arch arch,
, platformExecutableName platformExecutableName,
, platformExecutablePath platformExecutablePath,
, platformManifestPath) { platformManifestPath
) {
const outputName = `${meta.__applicationName}-${meta.__applicationVersion}-${arch}.rpm`;
const outputName = `${meta.__applicationName}-${ const specPath = path.join(
meta.__applicationVersion}-${arch}.rpm`; __dirname,
"../packaging/linux/rpm/package.spec"
const specPath = path.join(__dirname );
, "../packaging/linux/rpm/package.spec");
const specOutputPath = path.join(BUILD_PATH, path.basename(specPath)); const specOutputPath = path.join(BUILD_PATH, path.basename(specPath));
const view = { const view = {
packageName: meta.__applicationName packageName: meta.__applicationName,
, applicationName: meta.__applicationName applicationName: meta.__applicationName,
, applicationVersion: meta.__applicationVersion applicationVersion: meta.__applicationVersion,
, executablePath: platformExecutablePath executablePath: platformExecutablePath,
, manifestPath: platformManifestPath manifestPath: platformManifestPath,
, executableName: platformExecutableName executableName: platformExecutableName,
, manifestName: paths.MANIFEST_NAME manifestName: paths.MANIFEST_NAME,
, bindingName: MDNS_BINDING_NAME bindingName: MDNS_BINDING_NAME
}; };
fs.writeFileSync(specOutputPath fs.writeFileSync(
, mustache.render( specOutputPath,
fs.readFileSync(specPath).toString() mustache.render(fs.readFileSync(specPath).toString(), view)
, view)); );
const rpmArchMap = { const rpmArchMap = { x86: "i386", x64: "x86_64" };
"x86": "i386"
, "x64": "x86_64"
};
spawnSync(` spawnSync(
rpmbuild -bb ${specOutputPath} \ `rpmbuild -bb ${specOutputPath} \
--define "_distdir ${BUILD_PATH}" \ --define "_distdir ${BUILD_PATH}" \
--define "_rpmdir ${BUILD_PATH}" \ --define "_rpmdir ${BUILD_PATH}" \
--define "_rpmfilename ${outputName}" \ --define "_rpmfilename ${outputName}" \
--target=${rpmArchMap[arch]}-linux` --target=${rpmArchMap[arch]}-linux`,
, spawnOptions); spawnOptions
);
return outputName; return outputName;
} }
@@ -464,47 +493,44 @@ function packageLinuxRpm (
* script (packaging/win/installer.nsi). Requires the * script (packaging/win/installer.nsi). Requires the
* makensis command line utility. * makensis command line utility.
*/ */
function packageWin32 ( function packageWin32(
arch arch,
, platformExecutableName platformExecutableName,
, platformExecutablePath platformExecutablePath,
, platformManifestPath) { platformManifestPath
) {
const outputName = `${meta.__applicationName}-${ const outputName = `${meta.__applicationName}-${meta.__applicationVersion}-${arch}.exe`;
meta.__applicationVersion}-${arch}.exe`;
const scriptPath = path.join(__dirname, "../packaging/win/installer.nsi"); const scriptPath = path.join(__dirname, "../packaging/win/installer.nsi");
const scriptOutputPath = path.join(BUILD_PATH, path.basename(scriptPath)); const scriptOutputPath = path.join(BUILD_PATH, path.basename(scriptPath));
const view = { const view = {
applicationName: meta.__applicationName applicationName: meta.__applicationName,
, applicationVersion: meta.__applicationVersion applicationVersion: meta.__applicationVersion,
, executableName: platformExecutableName executableName: platformExecutableName,
, executablePath: platformExecutablePath executablePath: platformExecutablePath,
, manifestName: paths.MANIFEST_NAME manifestName: paths.MANIFEST_NAME,
, bindingName: MDNS_BINDING_NAME bindingName: MDNS_BINDING_NAME,
, winRegistryKey: paths.REGISTRY_KEY winRegistryKey: paths.REGISTRY_KEY,
, outputName outputName,
, licensePath: paths.LICENSE_PATH licensePath: paths.LICENSE_PATH,
// Uninstaller keys // Uninstaller keys
, registryPublisher: author registryPublisher: author,
, registryUrlInfoAbout: homepage registryUrlInfoAbout: homepage
}; };
// Write templated script to build dir // Write templated script to build dir
fs.writeFileSync(scriptOutputPath fs.writeFileSync(
, mustache.render( scriptOutputPath,
fs.readFileSync(scriptPath).toString() mustache.render(fs.readFileSync(scriptPath).toString(), view)
, view)); );
spawnSync(`makensis /DARCH=${arch} ${scriptOutputPath}` spawnSync(`makensis /DARCH=${arch} ${scriptOutputPath}`, spawnOptions);
, spawnOptions);
return outputName; return outputName;
} }
build().catch(e => { build().catch(e => {
console.log("Build failed", e); console.log("Build failed", e);
process.exit(1); process.exit(1);

View File

@@ -5,24 +5,20 @@ const minimist = require("minimist");
const paths = require("./lib/paths"); const paths = require("./lib/paths");
const argv = minimist(process.argv.slice(2), { const argv = minimist(process.argv.slice(2), {
boolean: [ "remove" ] boolean: ["remove"],
, default: { default: {
remove: false remove: false
} }
}); });
const CURRENT_MANIFEST_PATH = path.join(paths.DIST_PATH, paths.MANIFEST_NAME); const CURRENT_MANIFEST_PATH = path.join(paths.DIST_PATH, paths.MANIFEST_NAME);
if (!fs.existsSync(CURRENT_MANIFEST_PATH) && !argv.remove) { if (!fs.existsSync(CURRENT_MANIFEST_PATH) && !argv.remove) {
console.error("No manifest in dist/app/ to install."); console.error("No manifest in dist/app/ to install.");
process.exit(1); process.exit(1);
} }
const platform = os.platform(); const platform = os.platform();
const arch = os.arch(); const arch = os.arch();
@@ -30,9 +26,12 @@ switch (platform) {
case "darwin": case "darwin":
case "linux": { case "linux": {
// Manifest location within home directory // Manifest location within home directory
const destination = path.join(os.homedir(), platform === "linux" const destination = path.join(
? ".mozilla/native-messaging-hosts/" os.homedir(),
: paths.getManifestPath(platform, arch)); platform === "linux"
? ".mozilla/native-messaging-hosts/"
: paths.getManifestPath(platform, arch)
);
if (argv.remove) { if (argv.remove) {
fs.remove(path.join(destination, paths.MANIFEST_NAME)); fs.remove(path.join(destination, paths.MANIFEST_NAME));
@@ -41,11 +40,13 @@ switch (platform) {
// Install manifest // Install manifest
fs.ensureDirSync(destination); fs.ensureDirSync(destination);
fs.copyFileSync(CURRENT_MANIFEST_PATH fs.copyFileSync(
, path.join(destination, paths.MANIFEST_NAME)); CURRENT_MANIFEST_PATH,
path.join(destination, paths.MANIFEST_NAME)
);
break; break;
}; }
case "win32": { case "win32": {
const { Registry } = require("rage-edit"); const { Registry } = require("rage-edit");
@@ -56,14 +57,10 @@ switch (platform) {
break; break;
} }
Registry.set( Registry.set(REGISTRY_PATH, "", CURRENT_MANIFEST_PATH, "REG_SZ");
REGISTRY_PATH
, ""
, CURRENT_MANIFEST_PATH
, "REG_SZ");
break; break;
}; }
default: { default: {
console.error("Sorry, this installer does not yet support your OS"); console.error("Sorry, this installer does not yet support your OS");

View File

@@ -2,10 +2,11 @@
const path = require("path"); const path = require("path");
const { __applicationName const {
, __applicationDirectoryName __applicationName,
, __applicationExecutableName } = require("../../package.json"); __applicationDirectoryName,
__applicationExecutableName
} = require("../../package.json");
const rootPath = path.join(__dirname, "../../../"); const rootPath = path.join(__dirname, "../../../");
@@ -15,9 +16,9 @@ exports.LICENSE_PATH = path.join(rootPath, "LICENSE");
exports.REGISTRY_KEY = __applicationName; exports.REGISTRY_KEY = __applicationName;
exports.pkgPlatformMap = { exports.pkgPlatformMap = {
win32: "win" win32: "win",
, darwin: "macos" darwin: "macos",
, linux: "linux" linux: "linux"
}; };
exports.MANIFEST_NAME = `${__applicationName}.json`; exports.MANIFEST_NAME = `${__applicationName}.json`;
@@ -30,7 +31,7 @@ exports.getExecutableName = platform => {
case "linux": case "linux":
return __applicationExecutableName; return __applicationExecutableName;
} }
} };
exports.getExecutablePath = (platform, arch) => { exports.getExecutablePath = (platform, arch) => {
const EXECUTABLE_PATH_WIN32_X64 = `C:\\Program Files\\${__applicationDirectoryName}\\`; const EXECUTABLE_PATH_WIN32_X64 = `C:\\Program Files\\${__applicationDirectoryName}\\`;
@@ -41,32 +42,42 @@ exports.getExecutablePath = (platform, arch) => {
switch (platform) { switch (platform) {
case "win32": case "win32":
switch (arch) { switch (arch) {
case "x86": return EXECUTABLE_PATH_WIN32_X86; case "x86":
case "x64": return EXECUTABLE_PATH_WIN32_X64; return EXECUTABLE_PATH_WIN32_X86;
case "x64":
return EXECUTABLE_PATH_WIN32_X64;
} }
break; break;
case "darwin": return EXECUTABLE_PATH_DARWIN; case "darwin":
case "linux": return EXECUTABLE_PATH_LINUX; return EXECUTABLE_PATH_DARWIN;
case "linux":
return EXECUTABLE_PATH_LINUX;
} }
}; };
exports.getManifestPath = (platform, arch, linuxPackageType) => { exports.getManifestPath = (platform, arch, linuxPackageType) => {
const MANIFEST_PATH_DARWIN = "/Library/Application Support/Mozilla/NativeMessagingHosts/"; const MANIFEST_PATH_DARWIN =
"/Library/Application Support/Mozilla/NativeMessagingHosts/";
const MANIFEST_PATH_LINUX_DEB = "/usr/lib/mozilla/native-messaging-hosts/"; const MANIFEST_PATH_LINUX_DEB = "/usr/lib/mozilla/native-messaging-hosts/";
const MANIFEST_PATH_LINUX_RPM ="/usr/lib64/mozilla/native-messaging-hosts/"; const MANIFEST_PATH_LINUX_RPM =
"/usr/lib64/mozilla/native-messaging-hosts/";
switch (platform) { switch (platform) {
case "win32": case "win32":
switch (arch) { switch (arch) {
case "x86": case "x86":
case "x64": return exports.getExecutablePath(platform, arch); case "x64":
return exports.getExecutablePath(platform, arch);
} }
break; break;
case "darwin": return MANIFEST_PATH_DARWIN; case "darwin":
return MANIFEST_PATH_DARWIN;
case "linux": case "linux":
switch (linuxPackageType) { switch (linuxPackageType) {
case "deb": return MANIFEST_PATH_LINUX_DEB; case "deb":
case "rpm": return MANIFEST_PATH_LINUX_RPM; return MANIFEST_PATH_LINUX_DEB;
case "rpm":
return MANIFEST_PATH_LINUX_RPM;
} }
break; break;

2074
app/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,13 +8,13 @@ for (const faq of document.querySelectorAll(".faq")) {
faq.id = formattedSummary; faq.id = formattedSummary;
if (window.location.hash) { if (window.location.hash) {
faq.open = decodeURIComponent( faq.open =
window.location.hash.slice(1)) === formattedSummary; decodeURIComponent(window.location.hash.slice(1)) ===
formattedSummary;
} }
} }
function updateThemeClass(mediaQuery) {
function updateThemeClass (mediaQuery) {
if (mediaQuery.matches) { if (mediaQuery.matches) {
document.documentElement.classList.remove("theme-dark"); document.documentElement.classList.remove("theme-dark");
document.documentElement.classList.add("theme-light"); document.documentElement.classList.add("theme-light");
@@ -29,10 +29,10 @@ const prefersLightScheme = window.matchMedia("(prefers-color-scheme: light)");
updateThemeClass(prefersLightScheme); updateThemeClass(prefersLightScheme);
prefersLightScheme.addListener(updateThemeClass); prefersLightScheme.addListener(updateThemeClass);
const downloadAppBtn = document.querySelector(".download__app"); const downloadAppBtn = document.querySelector(".download__app");
const downloadAppOther = document.querySelector(".download__app-other"); const downloadAppOther = document.querySelector(".download__app-other");
const downloadAppOtherSummary = downloadAppOther.querySelector(":scope > summary"); const downloadAppOtherSummary =
downloadAppOther.querySelector(":scope > summary");
// Ext download button // Ext download button
const downloadExtBtn = document.querySelector(".download__ext"); const downloadExtBtn = document.querySelector(".download__ext");
@@ -45,7 +45,6 @@ const appListMacBtn = document.querySelector(".app-list__mac");
const appListDebBtn = document.querySelector(".app-list__deb"); const appListDebBtn = document.querySelector(".app-list__deb");
const appListRpmBtn = document.querySelector(".app-list__rpm"); const appListRpmBtn = document.querySelector(".app-list__rpm");
let platform; let platform;
switch (navigator.platform) { switch (navigator.platform) {
@@ -79,8 +78,7 @@ switch (navigator.platform) {
appListRpmBtn.classList.add("button"); appListRpmBtn.classList.add("button");
} }
function populateAppListApp(element, fileUrl, fileName, fileSize, version) {
function populateAppListApp (element, fileUrl, fileName, fileSize, version) {
element.href = fileUrl; element.href = fileUrl;
element.title = `${fileName} (${fileSize})`; element.title = `${fileName} (${fileSize})`;
element.dataset.fileSize = fileSize; element.dataset.fileSize = fileSize;
@@ -88,7 +86,6 @@ function populateAppListApp (element, fileUrl, fileName, fileSize, version) {
element.removeAttribute("disabled"); element.removeAttribute("disabled");
} }
const ENDPOINT_URL = "https://api.github.com/repos/hensm/fx_cast/releases"; const ENDPOINT_URL = "https://api.github.com/repos/hensm/fx_cast/releases";
fetch(ENDPOINT_URL) fetch(ENDPOINT_URL)
@@ -96,7 +93,7 @@ fetch(ENDPOINT_URL)
.then(onResponse) .then(onResponse)
.catch(onError); .catch(onError);
function onResponse (res) { function onResponse(res) {
for (const release of res.reverse()) { for (const release of res.reverse()) {
for (const asset of release.assets) { for (const asset of release.assets) {
const formattedSize = formatSize(asset.size); const formattedSize = formatSize(asset.size);
@@ -113,18 +110,25 @@ function onResponse (res) {
downloadExtBtn.removeAttribute("disabled"); downloadExtBtn.removeAttribute("disabled");
break; break;
case "exe": case "exe":
switch (asset.name.match(REGEX_ARCH).pop()) { switch (asset.name.match(REGEX_ARCH).pop()) {
case "x86": case "x86":
populateAppListApp( populateAppListApp(
appListWin32Btn, asset.browser_download_url appListWin32Btn,
, asset.name, formattedSize, tag_name); asset.browser_download_url,
asset.name,
formattedSize,
tag_name
);
break; break;
case "x64": case "x64":
populateAppListApp( populateAppListApp(
appListWin64Btn, asset.browser_download_url appListWin64Btn,
, asset.name, formattedSize, tag_name); asset.browser_download_url,
asset.name,
formattedSize,
tag_name
);
break; break;
} }
@@ -132,20 +136,32 @@ function onResponse (res) {
case "pkg": case "pkg":
populateAppListApp( populateAppListApp(
appListMacBtn, asset.browser_download_url appListMacBtn,
, asset.name, formattedSize, tag_name); asset.browser_download_url,
asset.name,
formattedSize,
tag_name
);
break; break;
case "deb": case "deb":
populateAppListApp( populateAppListApp(
appListDebBtn, asset.browser_download_url appListDebBtn,
, asset.name, formattedSize, tag_name); asset.browser_download_url,
asset.name,
formattedSize,
tag_name
);
break; break;
case "rpm": case "rpm":
populateAppListApp( populateAppListApp(
appListRpmBtn, asset.browser_download_url appListRpmBtn,
, asset.name, formattedSize, tag_name); asset.browser_download_url,
asset.name,
formattedSize,
tag_name
);
break; break;
} }
} }
@@ -156,7 +172,8 @@ function onResponse (res) {
case "win": case "win":
downloadAppBtn.href = appListWin64Btn.href; downloadAppBtn.href = appListWin64Btn.href;
downloadAppBtn.title = appListWin64Btn.title; downloadAppBtn.title = appListWin64Btn.title;
downloadAppBtn.dataset.version = appListWin64Btn.dataset.version; downloadAppBtn.dataset.version =
appListWin64Btn.dataset.version;
break; break;
case "mac": case "mac":
downloadAppBtn.href = appListMacBtn.href; downloadAppBtn.href = appListMacBtn.href;
@@ -173,12 +190,11 @@ function onResponse (res) {
} }
} }
function onError (err) { function onError(err) {
console.error("Failed to fetch download links", err); console.error("Failed to fetch download links", err);
} }
function formatSize(bytes, precision = 1, useMetric = false) {
function formatSize (bytes, precision = 1, useMetric = false) {
const factor = useMetric ? 1000 : 1024; const factor = useMetric ? 1000 : 1024;
// Sizes in bytes // Sizes in bytes
@@ -190,25 +206,25 @@ function formatSize (bytes, precision = 1, useMetric = false) {
if (bytes >= 0 && bytes < kxbyte) { if (bytes >= 0 && bytes < kxbyte) {
return `${bytes} B`; return `${bytes} B`;
} else if (bytes >= kxbyte && bytes < mxbyte) { } else if (bytes >= kxbyte && bytes < mxbyte) {
return `${(bytes / kxbyte).toFixed(precision)} ${ return `${(bytes / kxbyte).toFixed(precision)} ${
useMetric ? "KB" : "KiB"}`; useMetric ? "KB" : "KiB"
}`;
} else if (bytes >= mxbyte && bytes < gxbyte) { } else if (bytes >= mxbyte && bytes < gxbyte) {
return `${(bytes / mxbyte).toFixed(precision)} ${ return `${(bytes / mxbyte).toFixed(precision)} ${
useMetric ? "MB" : "MiB"}`; useMetric ? "MB" : "MiB"
}`;
} else if (bytes >= gxbyte && bytes < txbyte) { } else if (bytes >= gxbyte && bytes < txbyte) {
return `${(bytes / gxbyte).toFixed(precision)} ${ return `${(bytes / gxbyte).toFixed(precision)} ${
useMetric ? "GB" : "GiB"}`; useMetric ? "GB" : "GiB"
}`;
} else if (bytes >= txbyte && bytes < pxbyte) { } else if (bytes >= txbyte && bytes < pxbyte) {
return `${(bytes / txbyte).toFixed(precision)} ${ return `${(bytes / txbyte).toFixed(precision)} ${
useMetric ? "TB" : "TiB"}`; useMetric ? "TB" : "TiB"
}`;
} else if (bytes >= pxbyte) { } else if (bytes >= pxbyte) {
return `${(bytes / pxbyte).toFixed(precision)} ${ return `${(bytes / pxbyte).toFixed(precision)} ${
useMetric ? "PB" : "PiB"}`; useMetric ? "PB" : "PiB"
}`;
} }
} }

View File

@@ -8,12 +8,12 @@ const mediaManager = new cast.receiver.MediaManager(mediaElement);
mediaElement.height = window.innerHeight; mediaElement.height = window.innerHeight;
mediaElement.width = window.innerWidth; mediaElement.width = window.innerWidth;
let senderId; let senderId;
const messageBus = castReceiverManager.getCastMessageBus( const messageBus = castReceiverManager.getCastMessageBus(
"urn:x-cast:fx_cast" "urn:x-cast:fx_cast",
, cast.receiver.CastMessageBus.MessageType.JSON); cast.receiver.CastMessageBus.MessageType.JSON
);
messageBus.onMessage = async message => { messageBus.onMessage = async message => {
const { subject, data } = message.data; const { subject, data } = message.data;
@@ -27,8 +27,8 @@ messageBus.onMessage = async message => {
await pc.setLocalDescription(desc); await pc.setLocalDescription(desc);
messageBus.send(message.senderId, { messageBus.send(message.senderId, {
subject: "peerConnectionAnswer" subject: "peerConnectionAnswer",
, data: desc data: desc
}); });
break; break;
@@ -46,13 +46,12 @@ messageBus.onMessage = async message => {
} }
}; };
const pc = new RTCPeerConnection(); const pc = new RTCPeerConnection();
pc.addEventListener("icecandidate", ev => { pc.addEventListener("icecandidate", ev => {
messageBus.send(senderId, { messageBus.send(senderId, {
subject: "iceCandidate" subject: "iceCandidate",
, data: ev.candidate data: ev.candidate
}); });
}); });
@@ -64,7 +63,6 @@ pc.addEventListener("addstream", ev => {
splash.classList.add("splash--disabled"); splash.classList.add("splash--disabled");
}); });
// TODO: Fix API shim to make this work // TODO: Fix API shim to make this work
castReceiverManager.onSenderDisconnected = ev => { castReceiverManager.onSenderDisconnected = ev => {
if (castReceiverManager.getSenders().length <= 0) { if (castReceiverManager.getSenders().length <= 0) {

View File

@@ -6,21 +6,19 @@ const path = require("path");
const minimist = require("minimist"); const minimist = require("minimist");
const webExt = require("web-ext"); const webExt = require("web-ext");
const BRIDGE_NAME = "fx_cast_bridge"; const BRIDGE_NAME = "fx_cast_bridge";
const BRIDGE_VERSION = "0.1.0"; const BRIDGE_VERSION = "0.1.0";
const MIRRORING_APP_ID = "19A6F4AE"; const MIRRORING_APP_ID = "19A6F4AE";
const argv = minimist(process.argv.slice(2), { const argv = minimist(process.argv.slice(2), {
boolean: [ "package", "watch" ] boolean: ["package", "watch"],
, string: [ "mirroringAppId", "mode" ] string: ["mirroringAppId", "mode"],
, default: { default: {
package: false package: false,
, watch: false watch: false,
, mirroringAppId: MIRRORING_APP_ID mirroringAppId: MIRRORING_APP_ID,
, mode: "development" mode: "development"
} }
}); });
@@ -34,7 +32,6 @@ if (argv.package) {
argv.mode = "production"; argv.mode = "production";
} }
// Paths // Paths
const rootPath = path.resolve(__dirname, "../"); const rootPath = path.resolve(__dirname, "../");
const srcPath = path.join(rootPath, "src"); const srcPath = path.join(rootPath, "src");
@@ -51,48 +48,50 @@ const preactCompatPlugin = {
*/ */
name: "preact-compat", name: "preact-compat",
setup(build) { setup(build) {
const preactPath = path.resolve(__dirname const preactPath = path.resolve(
, "../node_modules/preact/compat/dist/compat.module.js"); __dirname,
"../node_modules/preact/compat/dist/compat.module.js"
);
build.onResolve( build.onResolve({ filter: /^(react|react-dom)$/ }, args => ({
{ filter: /^(react|react-dom)$/ } path: preactPath
, (args) => ({ path: preactPath })); }));
} }
} };
/** @type esbuild.BuildOptions */ /** @type esbuild.BuildOptions */
const buildOpts = { const buildOpts = {
bundle: true bundle: true,
, target: "firefox64" target: "firefox64",
, logLevel: "info" logLevel: "info",
, sourcemap: "inline" sourcemap: "inline",
, outdir: outPath outdir: outPath,
, outbase: srcPath outbase: srcPath,
, entryPoints: [ entryPoints: [
// Main // Main
`${srcPath}/background/background.ts` `${srcPath}/background/background.ts`,
// Media sender // Media sender
, `${srcPath}/senders/media/index.ts` `${srcPath}/senders/media/index.ts`,
, `${srcPath}/senders/media/overlay/overlayContent.ts` `${srcPath}/senders/media/overlay/overlayContent.ts`,
, `${srcPath}/senders/media/overlay/overlayContentLoader.ts` `${srcPath}/senders/media/overlay/overlayContentLoader.ts`,
// Mirroring sender // Mirroring sender
, `${srcPath}/senders/mirroring.ts` `${srcPath}/senders/mirroring.ts`,
// Shim // Shim
, `${srcPath}/shim/index.ts` `${srcPath}/shim/index.ts`,
, `${srcPath}/shim/content.ts` `${srcPath}/shim/content.ts`,
, `${srcPath}/shim/contentBridge.ts` `${srcPath}/shim/contentBridge.ts`,
// UI // UI
, `${srcPath}/ui/popup/index.tsx` `${srcPath}/ui/popup/index.tsx`,
, `${srcPath}/ui/options/index.tsx` `${srcPath}/ui/options/index.tsx`
] ],
, define: { define: {
BRIDGE_NAME: `"${BRIDGE_NAME}"` BRIDGE_NAME: `"${BRIDGE_NAME}"`,
, BRIDGE_VERSION: `"${BRIDGE_VERSION}"` BRIDGE_VERSION: `"${BRIDGE_VERSION}"`,
, MIRRORING_APP_ID: `"${argv.mirroringAppId}"` MIRRORING_APP_ID: `"${argv.mirroringAppId}"`
} },
, plugins: [ preactCompatPlugin ] plugins: [preactCompatPlugin]
}; };
// Set production options // Set production options
@@ -113,12 +112,13 @@ function onBuildResult(result) {
} }
const manifest = JSON.parse( const manifest = JSON.parse(
fs.readFileSync(`${srcPath}/manifest.json` fs.readFileSync(`${srcPath}/manifest.json`, { encoding: "utf-8" })
, { encoding: "utf-8" })); );
manifest.content_security_policy = argv.mode === "production" manifest.content_security_policy =
? "script-src 'self'; object-src 'self'" argv.mode === "production"
: "script-src 'self' 'unsafe-eval'; object-src 'self'"; ? "script-src 'self'; object-src 'self'"
: "script-src 'self' 'unsafe-eval'; object-src 'self'";
fs.writeFileSync(`${outPath}/manifest.json`, JSON.stringify(manifest)); fs.writeFileSync(`${outPath}/manifest.json`, JSON.stringify(manifest));
@@ -132,14 +132,14 @@ function onBuildResult(result) {
* @param {string} dest Destination path * @param {string} dest Destination path
* @param {RegExp} excludeRegex Match for file exclusion * @param {RegExp} excludeRegex Match for file exclusion
*/ */
function copy(src, dest, excludeRegex) { function copy(src, dest, excludeRegex) {
if (!fs.existsSync(src)) return; if (!fs.existsSync(src)) return;
const stats = fs.statSync(src); const stats = fs.statSync(src);
if (!stats.isDirectory()) { if (!stats.isDirectory()) {
const dirName = path.dirname(dest); const dirName = path.dirname(dest);
if (!fs.existsSync(dirName)) { if (!fs.existsSync(dirName)) {
fs.mkdirSync(dirName , { recursive: true }); fs.mkdirSync(dirName, { recursive: true });
} }
fs.copyFileSync(src, dest); fs.copyFileSync(src, dest);
return; return;
@@ -155,41 +155,49 @@ function onBuildResult(result) {
fs.removeSync(distPath); fs.removeSync(distPath);
if (argv.watch) { if (argv.watch) {
esbuild.build({ esbuild
...buildOpts .build({
, watch: { ...buildOpts,
onRebuild(_err, result) { watch: {
return onBuildResult(result); onRebuild(_err, result) {
return onBuildResult(result);
}
} }
} })
}).then(onBuildResult); .then(onBuildResult);
} else { } else {
esbuild.build(buildOpts).then(result => { esbuild.build(buildOpts).then(result => {
onBuildResult(result); onBuildResult(result);
if (argv.package) { if (argv.package) {
webExt.cmd.build({ webExt.cmd
/** .build(
* Webpack output at sourceDir is built into an extension {
* archive at artifactsDir. /**
*/ * Webpack output at sourceDir is built into an extension
sourceDir: unpackedPath * archive at artifactsDir.
, artifactsDir: distPath */
, overwriteDest: true sourceDir: unpackedPath,
}, { artifactsDir: distPath,
// Prevent auto-exit overwriteDest: true
shouldExitProgram: false },
}).then(result => { {
const outputName = path.basename(result.extensionPath); // Prevent auto-exit
shouldExitProgram: false
}
)
.then(result => {
const outputName = path.basename(result.extensionPath);
// Rename output extension to XPI // Rename output extension to XPI
fs.moveSync(path.join(distPath, outputName) fs.moveSync(
, path.join(distPath, outputName.replace( path.join(distPath, outputName),
"zip", "xpi"))); path.join(distPath, outputName.replace("zip", "xpi"))
);
// Only need the built extension archive // Only need the built extension archive
fs.remove(unpackedPath); fs.remove(unpackedPath);
}); });
} }
}); });
} }

8482
ext/package-lock.json generated

File diff suppressed because it is too large Load Diff

2051
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -29,6 +29,7 @@
"glob": "^7.1.6", "glob": "^7.1.6",
"jasmine-console-reporter": "^3.1.0", "jasmine-console-reporter": "^3.1.0",
"minimist": "^1.2.5", "minimist": "^1.2.5",
"prettier": "^2.3.2",
"selenium-webdriver": "^4.0.0-beta.1", "selenium-webdriver": "^4.0.0-beta.1",
"ws": "^7.4.3" "ws": "^7.4.3"
} }

View File

@@ -9,56 +9,54 @@ const env = jasmine.getEnv();
// Copy to window // Copy to window
Object.assign(window, jasmineRequire.interface(jasmine, env)); Object.assign(window, jasmineRequire.interface(jasmine, env));
// Create query string // Create query string
const queryString = new jasmine.QueryString({ const queryString = new jasmine.QueryString({
getWindowLocation () { getWindowLocation() {
return window.location; return window.location;
} }
}); });
// If spec is present in the query string // If spec is present in the query string
const filterSpecs = !!queryString.getParam("spec"); const filterSpecs = !!queryString.getParam("spec");
// Create HTML reporter // Create HTML reporter
const htmlReporter = new jasmine.HtmlReporter({ const htmlReporter = new jasmine.HtmlReporter({
env env,
, filterSpecs filterSpecs,
, timer: new jasmine.Timer() timer: new jasmine.Timer(),
, getContainer () { getContainer() {
return document.body; return document.body;
} },
// Bound functions // Bound functions
, navigateWithNewParam: queryString.navigateWithNewParam.bind(queryString) navigateWithNewParam: queryString.navigateWithNewParam.bind(queryString),
, addToExistingQueryString: queryString.fullStringWithNewParam.bind(queryString) addToExistingQueryString:
, createElement: document.createElement.bind(document) queryString.fullStringWithNewParam.bind(queryString),
, createTextNode: document.createTextNode.bind(document) createElement: document.createElement.bind(document),
createTextNode: document.createTextNode.bind(document)
}); });
// Create spec filter // Create spec filter
const specFilter = new jasmine.HtmlSpecFilter({ const specFilter = new jasmine.HtmlSpecFilter({
filterString () { filterString() {
return queryString.getParam("spec"); return queryString.getParam("spec");
} }
}); });
// Add reporters // Add reporters
env.addReporter(jsApiReporter); env.addReporter(jsApiReporter);
env.addReporter(htmlReporter); env.addReporter(htmlReporter);
// Configure Env // Configure Env
env.configure({ env.configure({
failFast : queryString.getParam("failFast") failFast: queryString.getParam("failFast"),
, hideDisabled : queryString.getParam("hideDisabled") hideDisabled: queryString.getParam("hideDisabled"),
, oneFailurePerSpec : queryString.getParam("oneFailurePerSpec") oneFailurePerSpec: queryString.getParam("oneFailurePerSpec"),
, random : queryString.getParam("random") random: queryString.getParam("random"),
, seed : queryString.getParam("seed") seed: queryString.getParam("seed"),
, specFilter (spec) { specFilter(spec) {
return specFilter.matches(spec.getFullName()); return specFilter.matches(spec.getFullName());
} }
}); });

View File

@@ -15,20 +15,19 @@ const chrome = require("selenium-webdriver/chrome");
// Webdriver shorthands // Webdriver shorthands
const { By, until } = webdriver; const { By, until } = webdriver;
const { __extensionName, __extensionVersion } = require("../ext/package.json");
const { __extensionName
, __extensionVersion } = require("../ext/package.json");
const extensionArchivePath = path.join( const extensionArchivePath = path.join(
__dirname, "../dist/ext" __dirname,
, `${__extensionName}-${__extensionVersion}.xpi`) "../dist/ext",
`${__extensionName}-${__extensionVersion}.xpi`
);
if (!fs.existsSync(extensionArchivePath)) { if (!fs.existsSync(extensionArchivePath)) {
console.error("Extension archive not found."); console.error("Extension archive not found.");
process.exit(1); process.exit(1);
} }
const TEST_PAGE_URL = `file:///${__dirname}/SpecRunner.html`; const TEST_PAGE_URL = `file:///${__dirname}/SpecRunner.html`;
const POLLING_PAGE_URL = `file:///${__dirname}/polling.html`; const POLLING_PAGE_URL = `file:///${__dirname}/polling.html`;
@@ -37,10 +36,10 @@ const firefoxOptions = new firefox.Options()
.addExtensions(extensionArchivePath) .addExtensions(extensionArchivePath)
.setPreference("xpinstall.signatures.required", false); .setPreference("xpinstall.signatures.required", false);
const chromeOptions = new chrome.Options() const chromeOptions = new chrome.Options().excludeSwitches([
.excludeSwitches([ "disable-background-networking" "disable-background-networking",
, "disable-default-apps"]); "disable-default-apps"
]);
/** /**
* Chrome doesn't load the media router extension immediately * Chrome doesn't load the media router extension immediately
@@ -50,11 +49,11 @@ const chromeOptions = new chrome.Options()
* Workaround is to poll every 100ms, refresh the page, and * Workaround is to poll every 100ms, refresh the page, and
* check whether the chrome.cast API objects are defined. * check whether the chrome.cast API objects are defined.
*/ */
function waitUntilDefined ( function waitUntilDefined(
driver driver,
, pollingTimeout = 10000 pollingTimeout = 10000,
, pollingFrequency = 100) { pollingFrequency = 100
) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
let elapsedTime = pollingFrequency; let elapsedTime = pollingFrequency;
@@ -92,7 +91,7 @@ function waitUntilDefined (
* channel. * channel.
*/ */
class MessageProxy extends EventEmitter { class MessageProxy extends EventEmitter {
constructor () { constructor() {
super(); super();
const wss = new WebSocket.Server({ const wss = new WebSocket.Server({
@@ -104,7 +103,7 @@ class MessageProxy extends EventEmitter {
const messageContent = JSON.parse(message); const messageContent = JSON.parse(message);
this.emit(messageContent.subject, messageContent.data); this.emit(messageContent.subject, messageContent.data);
}); });
}) });
} }
} }
@@ -112,13 +111,13 @@ class MessageProxy extends EventEmitter {
* Ensures cast API is loaded before finding and injecting spec * Ensures cast API is loaded before finding and injecting spec
* file scripts into the test page. * file scripts into the test page.
*/ */
async function injectSpecs (driver) { async function injectSpecs(driver) {
const [ loaded, errorInfo ] = await driver.executeAsyncScript(() => { const [loaded, errorInfo] = await driver.executeAsyncScript(() => {
const callback = arguments[arguments.length - 1]; const callback = arguments[arguments.length - 1];
// If already loaded, return immediately // If already loaded, return immediately
if (chrome.cast !== undefined) { if (chrome.cast !== undefined) {
callback([ true ]); callback([true]);
} }
// Set Cast API callback // Set Cast API callback
@@ -133,7 +132,6 @@ async function injectSpecs (driver) {
return; return;
} }
// Get spec files // Get spec files
const specFiles = glob.sync("spec/**/*.spec.js", { const specFiles = glob.sync("spec/**/*.spec.js", {
cwd: __dirname cwd: __dirname
@@ -171,7 +169,6 @@ async function injectSpecs (driver) {
console.log("Cast extension loaded!"); console.log("Cast extension loaded!");
} }
// Create console reporter and message proxy. // Create console reporter and message proxy.
const reporter = new JasmineConsoleReporter(); const reporter = new JasmineConsoleReporter();
const messageProxy = new MessageProxy(); const messageProxy = new MessageProxy();
@@ -185,12 +182,14 @@ async function injectSpecs (driver) {
* Forward events from Jasmine standlone via message proxy to * Forward events from Jasmine standlone via message proxy to
* console reporter. * console reporter.
*/ */
messageProxy.on("jasmineDone" , result => reporter.jasmineDone(result)); messageProxy.on("jasmineDone", result => reporter.jasmineDone(result));
messageProxy.on("jasmineStarted" , result => reporter.jasmineStarted(result)); messageProxy.on("jasmineStarted", result =>
messageProxy.on("specDone" , result => reporter.specDone(result)); reporter.jasmineStarted(result)
messageProxy.on("specStarted" , result => reporter.specStarted(result)); );
messageProxy.on("suiteDone" , result => reporter.suiteDone(result)); messageProxy.on("specDone", result => reporter.specDone(result));
messageProxy.on("suiteStarted" , result => reporter.suiteStarted(result)); messageProxy.on("specStarted", result => reporter.specStarted(result));
messageProxy.on("suiteDone", result => reporter.suiteDone(result));
messageProxy.on("suiteStarted", result => reporter.suiteStarted(result));
// Load Jasmine test page // Load Jasmine test page
driver.get(TEST_PAGE_URL); driver.get(TEST_PAGE_URL);

View File

@@ -4,18 +4,18 @@
const socket = new WebSocket("ws://localhost:8080"); const socket = new WebSocket("ws://localhost:8080");
window.messageProxy = { window.messageProxy = {
sendMessage (message) { sendMessage(message) {
socket.send(JSON.stringify(message)); socket.send(JSON.stringify(message));
} }
} };
const reporterMethods = [ const reporterMethods = [
"jasmineDone" "jasmineDone",
, "jasmineStarted" "jasmineStarted",
, "specDone" "specDone",
, "specStarted" "specStarted",
, "suiteDone" "suiteDone",
, "suiteStarted" "suiteStarted"
]; ];
const customReporter = {}; const customReporter = {};
@@ -24,10 +24,10 @@ const customReporter = {};
for (const method of reporterMethods) { for (const method of reporterMethods) {
customReporter[method] = function (result) { customReporter[method] = function (result) {
messageProxy.sendMessage({ messageProxy.sendMessage({
subject: method subject: method,
, data: result data: result
}); });
} };
} }
socket.addEventListener("open", ev => { socket.addEventListener("open", ev => {

View File

@@ -16,17 +16,19 @@ describe("chrome.cast.ApiConfig", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const sessionRequest = new chrome.cast.SessionRequest( const sessionRequest = new chrome.cast.SessionRequest(
chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID); chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID
);
function sessionListener () {} function sessionListener() {}
function receiverListener () {} function receiverListener() {}
const apiConfig = new chrome.cast.ApiConfig( const apiConfig = new chrome.cast.ApiConfig(
sessionRequest sessionRequest,
, sessionListener sessionListener,
, receiverListener receiverListener,
, chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED,
, chrome.cast.DefaultActionPolicy.CAST_THIS_TAB); chrome.cast.DefaultActionPolicy.CAST_THIS_TAB
);
expect(typeof apiConfig.sessionListener).toBe("function"); expect(typeof apiConfig.sessionListener).toBe("function");
expect(typeof apiConfig.receiverListener).toBe("function"); expect(typeof apiConfig.receiverListener).toBe("function");

View File

@@ -10,8 +10,9 @@ describe("chrome.cast.DialRequest", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const dialRequest = new chrome.cast.DialRequest( const dialRequest = new chrome.cast.DialRequest(
"testAppName" "testAppName",
, "testLaunchParameter"); "testLaunchParameter"
);
expect(dialRequest.appName).toBe("testAppName"); expect(dialRequest.appName).toBe("testAppName");
expect(dialRequest.launchParameter).toBe("testLaunchParameter"); expect(dialRequest.launchParameter).toBe("testLaunchParameter");

View File

@@ -11,13 +11,13 @@ describe("chrome.cast.Error", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const error = new chrome.cast.Error( const error = new chrome.cast.Error(
chrome.cast.ErrorCode.CANCEL chrome.cast.ErrorCode.CANCEL,
, "testErrorDescription" "testErrorDescription",
, { testErrorDetails: "testErrorDetails" }); { testErrorDetails: "testErrorDetails" }
);
expect(error.code).toBe("cancel"); expect(error.code).toBe("cancel");
expect(error.description).toBe("testErrorDescription"); expect(error.description).toBe("testErrorDescription");
expect(error.details).toEqual( expect(error.details).toEqual({ testErrorDetails: "testErrorDetails" });
{ testErrorDetails: "testErrorDetails" });
}); });
}); });

View File

@@ -15,15 +15,20 @@ describe("chrome.cast.Receiver", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const receiver = new chrome.cast.Receiver( const receiver = new chrome.cast.Receiver(
"testLabel" "testLabel",
, "testFriendlyName" "testFriendlyName",
, [ chrome.cast.Capability.VIDEO_OUT [
, chrome.cast.Capability.AUDIO_OUT ] chrome.cast.Capability.VIDEO_OUT,
, new chrome.cast.Volume(1, false)); chrome.cast.Capability.AUDIO_OUT
],
new chrome.cast.Volume(1, false)
);
expect(receiver.capabilities).toEqual([ "video_out", "audio_out" ]); expect(receiver.capabilities).toEqual(["video_out", "audio_out"]);
expect(receiver.friendlyName).toBe("testFriendlyName"); expect(receiver.friendlyName).toBe("testFriendlyName");
expect(receiver.label).toBe("testLabel"); expect(receiver.label).toBe("testLabel");
expect(receiver.volume).toEqual(jasmine.objectContaining({ level: 1, muted: false })); expect(receiver.volume).toEqual(
jasmine.objectContaining({ level: 1, muted: false })
);
}); });
}); });

View File

@@ -2,8 +2,7 @@
describe("chrome.cast.ReceiverDisplayStatus", () => { describe("chrome.cast.ReceiverDisplayStatus", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const receiverDisplayStatus = const receiverDisplayStatus = new chrome.cast.ReceiverDisplayStatus();
new chrome.cast.ReceiverDisplayStatus();
expect(typeof receiverDisplayStatus.appImages).toBe("undefined"); expect(typeof receiverDisplayStatus.appImages).toBe("undefined");
expect(typeof receiverDisplayStatus.statusText).toBe("undefined"); expect(typeof receiverDisplayStatus.statusText).toBe("undefined");
@@ -12,14 +11,27 @@ describe("chrome.cast.ReceiverDisplayStatus", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const receiverDisplayStatus = new chrome.cast.ReceiverDisplayStatus( const receiverDisplayStatus = new chrome.cast.ReceiverDisplayStatus(
"testStatusText" "testStatusText",
, [ [
new chrome.cast.Image("http://example.com/1") new chrome.cast.Image("http://example.com/1"),
, new chrome.cast.Image("http://example.com/2") new chrome.cast.Image("http://example.com/2")
]); ]
);
expect(receiverDisplayStatus.statusText).toBe("testStatusText"); expect(receiverDisplayStatus.statusText).toBe("testStatusText");
expect(receiverDisplayStatus.appImages).toContain(jasmine.objectContaining({ url: "http://example.com/1", height: null, width: null })) expect(receiverDisplayStatus.appImages).toContain(
expect(receiverDisplayStatus.appImages).toContain(jasmine.objectContaining({ url: "http://example.com/2", height: null, width: null })) jasmine.objectContaining({
url: "http://example.com/1",
height: null,
width: null
})
);
expect(receiverDisplayStatus.appImages).toContain(
jasmine.objectContaining({
url: "http://example.com/2",
height: null,
width: null
})
);
}); });
}); });

View File

@@ -11,7 +11,8 @@ describe("chrome.cast.SenderApplication", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const senderApplication = new chrome.cast.SenderApplication( const senderApplication = new chrome.cast.SenderApplication(
chrome.cast.SenderPlatform.CHROME); chrome.cast.SenderPlatform.CHROME
);
expect(senderApplication.platform).toBe("chrome"); expect(senderApplication.platform).toBe("chrome");
}); });

View File

@@ -19,16 +19,19 @@ describe("chrome.cast.Session", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const session = new chrome.cast.Session( const session = new chrome.cast.Session(
"__sessionId" "__sessionId",
, "__appId" "__appId",
, "__displayName" "__displayName",
, [ new chrome.cast.Image("http://example.com") ] [new chrome.cast.Image("http://example.com")],
, new chrome.cast.Receiver("__label", "__friendlyName")); new chrome.cast.Receiver("__label", "__friendlyName")
);
expect(session.appId).toBe("__appId"); expect(session.appId).toBe("__appId");
expect(session.appImages).toEqual(jasmine.arrayContaining([ expect(session.appImages).toEqual(
jasmine.objectContaining({ url: "http://example.com" }) jasmine.arrayContaining([
])); jasmine.objectContaining({ url: "http://example.com" })
])
);
expect(session.displayName).toBe("__displayName"); expect(session.displayName).toBe("__displayName");
expect(session.receiver).toEqual(jasmine.any(chrome.cast.Receiver)); expect(session.receiver).toEqual(jasmine.any(chrome.cast.Receiver));
expect(session.sessionId).toBe("__sessionId"); expect(session.sessionId).toBe("__sessionId");

View File

@@ -5,7 +5,7 @@ describe("chrome.cast.SessionRequest", () => {
const sessionRequest = new chrome.cast.SessionRequest(); const sessionRequest = new chrome.cast.SessionRequest();
expect(sessionRequest.appId).toBe(undefined); expect(sessionRequest.appId).toBe(undefined);
expect(sessionRequest.capabilities).toEqual([ "video_out", "audio_out" ]); expect(sessionRequest.capabilities).toEqual(["video_out", "audio_out"]);
expect(sessionRequest.dialRequest).toBe(null); expect(sessionRequest.dialRequest).toBe(null);
expect(sessionRequest.language).toBe(null); expect(sessionRequest.language).toBe(null);
expect(sessionRequest.requestSessionTimeout).toBe(60000); expect(sessionRequest.requestSessionTimeout).toBe(60000);
@@ -13,13 +13,13 @@ describe("chrome.cast.SessionRequest", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const sessionRequest = new chrome.cast.SessionRequest( const sessionRequest = new chrome.cast.SessionRequest(
"__appId" "__appId",
, [ chrome.cast.Capability.VIDEO_OUT [chrome.cast.Capability.VIDEO_OUT, chrome.cast.Capability.AUDIO_IN],
, chrome.cast.Capability.AUDIO_IN ] 5000
, 5000); );
expect(sessionRequest.appId).toBe("__appId"); expect(sessionRequest.appId).toBe("__appId");
expect(sessionRequest.capabilities).toEqual([ "video_out", "audio_in" ]); expect(sessionRequest.capabilities).toEqual(["video_out", "audio_in"]);
expect(sessionRequest.requestSessionTimeout).toBe(5000); expect(sessionRequest.requestSessionTimeout).toBe(5000);
}); });
}); });

View File

@@ -41,84 +41,106 @@ describe("chrome", () => {
}); });
it("should have all api enums", () => { it("should have all api enums", () => {
expect(chrome.cast.AutoJoinPolicy).toEqual(jasmine.objectContaining({ expect(chrome.cast.AutoJoinPolicy).toEqual(
CUSTOM_CONTROLLER_SCOPED: "custom_controller_scoped" jasmine.objectContaining({
, TAB_AND_ORIGIN_SCOPED: "tab_and_origin_scoped" CUSTOM_CONTROLLER_SCOPED: "custom_controller_scoped",
, ORIGIN_SCOPED: "origin_scoped" TAB_AND_ORIGIN_SCOPED: "tab_and_origin_scoped",
, PAGE_SCOPED: "page_scoped" ORIGIN_SCOPED: "origin_scoped",
})); PAGE_SCOPED: "page_scoped"
})
);
expect(chrome.cast.Capability).toEqual(jasmine.objectContaining({ expect(chrome.cast.Capability).toEqual(
VIDEO_OUT: "video_out" jasmine.objectContaining({
, AUDIO_OUT: "audio_out" VIDEO_OUT: "video_out",
, VIDEO_IN: "video_in" AUDIO_OUT: "audio_out",
, AUDIO_IN: "audio_in" VIDEO_IN: "video_in",
, MULTIZONE_GROUP: "multizone_group" AUDIO_IN: "audio_in",
})); MULTIZONE_GROUP: "multizone_group"
})
);
expect(chrome.cast.DefaultActionPolicy).toEqual(jasmine.objectContaining({ expect(chrome.cast.DefaultActionPolicy).toEqual(
CREATE_SESSION: "create_session" jasmine.objectContaining({
, CAST_THIS_TAB: "cast_this_tab" CREATE_SESSION: "create_session",
})); CAST_THIS_TAB: "cast_this_tab"
})
);
expect(chrome.cast.DialAppState).toEqual(jasmine.objectContaining({ expect(chrome.cast.DialAppState).toEqual(
RUNNING: "running" jasmine.objectContaining({
, STOPPED: "stopped" RUNNING: "running",
, ERROR: "error" STOPPED: "stopped",
})); ERROR: "error"
})
);
expect(chrome.cast.ErrorCode).toEqual(jasmine.objectContaining({ expect(chrome.cast.ErrorCode).toEqual(
CANCEL: "cancel" jasmine.objectContaining({
, TIMEOUT: "timeout" CANCEL: "cancel",
, API_NOT_INITIALIZED: "api_not_initialized" TIMEOUT: "timeout",
, INVALID_PARAMETER: "invalid_parameter" API_NOT_INITIALIZED: "api_not_initialized",
, EXTENSION_NOT_COMPATIBLE: "extension_not_compatible" INVALID_PARAMETER: "invalid_parameter",
, EXTENSION_MISSING: "extension_missing" EXTENSION_NOT_COMPATIBLE: "extension_not_compatible",
, RECEIVER_UNAVAILABLE: "receiver_unavailable" EXTENSION_MISSING: "extension_missing",
, SESSION_ERROR: "session_error" RECEIVER_UNAVAILABLE: "receiver_unavailable",
, CHANNEL_ERROR: "channel_error" SESSION_ERROR: "session_error",
, LOAD_MEDIA_FAILED: "load_media_failed" CHANNEL_ERROR: "channel_error",
})); LOAD_MEDIA_FAILED: "load_media_failed"
})
);
expect(chrome.cast.ReceiverAction).toEqual(jasmine.objectContaining({ expect(chrome.cast.ReceiverAction).toEqual(
CAST: "cast" jasmine.objectContaining({
, STOP: "stop" CAST: "cast",
})); STOP: "stop"
})
);
expect(chrome.cast.ReceiverAvailability).toEqual(jasmine.objectContaining({ expect(chrome.cast.ReceiverAvailability).toEqual(
AVAILABLE: "available" jasmine.objectContaining({
, UNAVAILABLE: "unavailable" AVAILABLE: "available",
})); UNAVAILABLE: "unavailable"
})
);
expect(chrome.cast.ReceiverType).toEqual(jasmine.objectContaining({ expect(chrome.cast.ReceiverType).toEqual(
CAST: "cast" jasmine.objectContaining({
, DIAL: "dial" CAST: "cast",
, HANGOUT: "hangout" DIAL: "dial",
, CUSTOM: "custom" HANGOUT: "hangout",
})); CUSTOM: "custom"
})
);
expect(chrome.cast.SenderPlatform).toEqual(jasmine.objectContaining({ expect(chrome.cast.SenderPlatform).toEqual(
CHROME: "chrome" jasmine.objectContaining({
, IOS: "ios" CHROME: "chrome",
, ANDROID: "android" IOS: "ios",
})); ANDROID: "android"
})
);
expect(chrome.cast.SessionStatus).toEqual(jasmine.objectContaining({ expect(chrome.cast.SessionStatus).toEqual(
CONNECTED: "connected" jasmine.objectContaining({
, DISCONNECTED: "disconnected" CONNECTED: "connected",
, STOPPED: "stopped" DISCONNECTED: "disconnected",
})); STOPPED: "stopped"
})
);
expect(chrome.cast.VolumeControlType).toEqual(jasmine.objectContaining({ expect(chrome.cast.VolumeControlType).toEqual(
ATTENUATION: "attenuation" jasmine.objectContaining({
, FIXED: "fixed" ATTENUATION: "attenuation",
, MASTER: "master" FIXED: "fixed",
})); MASTER: "master"
})
);
}); });
}); });
describe("chrome.cast.media", () => { describe("chrome.cast.media", () => {
it ("should have all api classes", () => { it("should have all api classes", () => {
expect(chrome.cast.media.EditTracksInfoRequest).toBeDefined(); expect(chrome.cast.media.EditTracksInfoRequest).toBeDefined();
expect(chrome.cast.media.GenericMediaMetadata).toBeDefined(); expect(chrome.cast.media.GenericMediaMetadata).toBeDefined();
expect(chrome.cast.media.GetStatusRequest).toBeDefined(); expect(chrome.cast.media.GetStatusRequest).toBeDefined();
@@ -144,90 +166,116 @@ describe("chrome", () => {
expect(chrome.cast.media.VolumeRequest).toBeDefined(); expect(chrome.cast.media.VolumeRequest).toBeDefined();
}); });
it ("should have all api enums", () => { it("should have all api enums", () => {
expect(chrome.cast.media.IdleReason).toEqual(jasmine.objectContaining({ expect(chrome.cast.media.IdleReason).toEqual(
CANCELLED: "CANCELLED" jasmine.objectContaining({
, INTERRUPTED: "INTERRUPTED" CANCELLED: "CANCELLED",
, FINISHED: "FINISHED" INTERRUPTED: "INTERRUPTED",
, ERROR: "ERROR" FINISHED: "FINISHED",
})); ERROR: "ERROR"
expect(chrome.cast.media.MediaCommand).toEqual(jasmine.objectContaining({ })
PAUSE: "pause" );
, SEEK: "seek" expect(chrome.cast.media.MediaCommand).toEqual(
, STREAM_VOLUME: "stream_volume" jasmine.objectContaining({
, STREAM_MUTE: "stream_mute" PAUSE: "pause",
})); SEEK: "seek",
expect(chrome.cast.media.MetadataType).toEqual(jasmine.objectContaining({ STREAM_VOLUME: "stream_volume",
GENERIC: 0 STREAM_MUTE: "stream_mute"
, MOVIE: 1 })
, TV_SHOW: 2 );
, MUSIC_TRACK: 3 expect(chrome.cast.media.MetadataType).toEqual(
, PHOTO: 4 jasmine.objectContaining({
})); GENERIC: 0,
expect(chrome.cast.media.PlayerState).toEqual(jasmine.objectContaining({ MOVIE: 1,
IDLE: "IDLE" TV_SHOW: 2,
, PLAYING: "PLAYING" MUSIC_TRACK: 3,
, PAUSED: "PAUSED" PHOTO: 4
, BUFFERING: "BUFFERING" })
})); );
expect(chrome.cast.media.RepeatMode).toEqual(jasmine.objectContaining({ expect(chrome.cast.media.PlayerState).toEqual(
OFF: "REPEAT_OFF" jasmine.objectContaining({
, ALL: "REPEAT_ALL" IDLE: "IDLE",
, SINGLE: "REPEAT_SINGLE" PLAYING: "PLAYING",
, ALL_AND_SHUFFLE: "REPEAT_ALL_AND_SHUFFLE" PAUSED: "PAUSED",
})); BUFFERING: "BUFFERING"
expect(chrome.cast.media.ResumeState).toEqual(jasmine.objectContaining({ })
PLAYBACK_START: "PLAYBACK_START" );
, PLAYBACK_PAUSE: "PLAYBACK_PAUSE" expect(chrome.cast.media.RepeatMode).toEqual(
})); jasmine.objectContaining({
expect(chrome.cast.media.StreamType).toEqual(jasmine.objectContaining({ OFF: "REPEAT_OFF",
BUFFERED: "BUFFERED" ALL: "REPEAT_ALL",
, LIVE: "LIVE" SINGLE: "REPEAT_SINGLE",
, OTHER: "OTHER" ALL_AND_SHUFFLE: "REPEAT_ALL_AND_SHUFFLE"
})); })
expect(chrome.cast.media.TextTrackEdgeType).toEqual(jasmine.objectContaining({ );
NONE: "NONE" expect(chrome.cast.media.ResumeState).toEqual(
, OUTLINE: "OUTLINE" jasmine.objectContaining({
, DROP_SHADOW: "DROP_SHADOW" PLAYBACK_START: "PLAYBACK_START",
, RAISED: "RAISED" PLAYBACK_PAUSE: "PLAYBACK_PAUSE"
, DEPRESSED: "DEPRESSED" })
})); );
expect(chrome.cast.media.TextTrackFontGenericFamily).toEqual(jasmine.objectContaining({ expect(chrome.cast.media.StreamType).toEqual(
SANS_SERIF: "SANS_SERIF" jasmine.objectContaining({
, MONOSPACED_SANS_SERIF: "MONOSPACED_SANS_SERIF" BUFFERED: "BUFFERED",
, SERIF: "SERIF" LIVE: "LIVE",
, MONOSPACED_SERIF: "MONOSPACED_SERIF" OTHER: "OTHER"
, CASUAL: "CASUAL" })
, CURSIVE: "CURSIVE" );
, SMALL_CAPITALS: "SMALL_CAPITALS" expect(chrome.cast.media.TextTrackEdgeType).toEqual(
})); jasmine.objectContaining({
expect(chrome.cast.media.TextTrackFontStyle).toEqual(jasmine.objectContaining({ NONE: "NONE",
NORMAL: "NORMAL" OUTLINE: "OUTLINE",
, BOLD: "BOLD" DROP_SHADOW: "DROP_SHADOW",
, BOLD_ITALIC: "BOLD_ITALIC" RAISED: "RAISED",
, ITALIC: "ITALIC" DEPRESSED: "DEPRESSED"
})); })
expect(chrome.cast.media.TextTrackType).toEqual(jasmine.objectContaining({ );
SUBTITLES: "SUBTITLES" expect(chrome.cast.media.TextTrackFontGenericFamily).toEqual(
, CAPTIONS: "CAPTIONS" jasmine.objectContaining({
, DESCRIPTIONS: "DESCRIPTIONS" SANS_SERIF: "SANS_SERIF",
, CHAPTERS: "CHAPTERS" MONOSPACED_SANS_SERIF: "MONOSPACED_SANS_SERIF",
, METADATA: "METADATA" SERIF: "SERIF",
})); MONOSPACED_SERIF: "MONOSPACED_SERIF",
expect(chrome.cast.media.TextTrackWindowType).toEqual(jasmine.objectContaining({ CASUAL: "CASUAL",
NONE: "NONE" CURSIVE: "CURSIVE",
, NORMAL: "NORMAL" SMALL_CAPITALS: "SMALL_CAPITALS"
, ROUNDED_CORNERS: "ROUNDED_CORNERS" })
})); );
expect(chrome.cast.media.TrackType).toEqual(jasmine.objectContaining({ expect(chrome.cast.media.TextTrackFontStyle).toEqual(
TEXT: "TEXT" jasmine.objectContaining({
, AUDIO: "AUDIO" NORMAL: "NORMAL",
, VIDEO: "VIDEO" BOLD: "BOLD",
})); BOLD_ITALIC: "BOLD_ITALIC",
ITALIC: "ITALIC"
})
);
expect(chrome.cast.media.TextTrackType).toEqual(
jasmine.objectContaining({
SUBTITLES: "SUBTITLES",
CAPTIONS: "CAPTIONS",
DESCRIPTIONS: "DESCRIPTIONS",
CHAPTERS: "CHAPTERS",
METADATA: "METADATA"
})
);
expect(chrome.cast.media.TextTrackWindowType).toEqual(
jasmine.objectContaining({
NONE: "NONE",
NORMAL: "NORMAL",
ROUNDED_CORNERS: "ROUNDED_CORNERS"
})
);
expect(chrome.cast.media.TrackType).toEqual(
jasmine.objectContaining({
TEXT: "TEXT",
AUDIO: "AUDIO",
VIDEO: "VIDEO"
})
);
}); });
describe("chrome.cast.media.timeout", () => { describe("chrome.cast.media.timeout", () => {
it ("should have all properties", () => { it("should have all properties", () => {
expect(chrome.cast.media.timeout.editTracksInfo).toBe(0); expect(chrome.cast.media.timeout.editTracksInfo).toBe(0);
expect(chrome.cast.media.timeout.getStatus).toBe(0); expect(chrome.cast.media.timeout.getStatus).toBe(0);
expect(chrome.cast.media.timeout.load).toBe(0); expect(chrome.cast.media.timeout.load).toBe(0);
@@ -237,7 +285,7 @@ describe("chrome", () => {
expect(chrome.cast.media.timeout.seek).toBe(0); expect(chrome.cast.media.timeout.seek).toBe(0);
expect(chrome.cast.media.timeout.setVolume).toBe(0); expect(chrome.cast.media.timeout.setVolume).toBe(0);
expect(chrome.cast.media.timeout.stop).toBe(0); expect(chrome.cast.media.timeout.stop).toBe(0);
}) });
}); });
}); });
}); });

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.EditTracksInfoRequest", () => { describe("chrome.cast.media.EditTracksInfoRequest", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const editTracksInfoRequest = new chrome.cast.media.EditTracksInfoRequest(); const editTracksInfoRequest =
new chrome.cast.media.EditTracksInfoRequest();
expect(editTracksInfoRequest.activeTrackIds).toBe(null); expect(editTracksInfoRequest.activeTrackIds).toBe(null);
expect(editTracksInfoRequest.requestId).toBe(0); expect(editTracksInfoRequest.requestId).toBe(0);
@@ -15,14 +16,19 @@ describe("chrome.cast.media.EditTracksInfoRequest", () => {
textTrackStyle.fontFamily = "__fontFamily"; textTrackStyle.fontFamily = "__fontFamily";
textTrackStyle.windowRoundedCornerRadius = 5; textTrackStyle.windowRoundedCornerRadius = 5;
const editTracksInfoRequest = new chrome.cast.media.EditTracksInfoRequest( const editTracksInfoRequest =
[ 5, 8, 12 ], textTrackStyle); new chrome.cast.media.EditTracksInfoRequest(
[5, 8, 12],
textTrackStyle
);
expect(editTracksInfoRequest.activeTrackIds).toEqual([ 5, 8, 12 ]); expect(editTracksInfoRequest.activeTrackIds).toEqual([5, 8, 12]);
expect(editTracksInfoRequest.textTrackStyle).toEqual(jasmine.objectContaining({ expect(editTracksInfoRequest.textTrackStyle).toEqual(
backgroundColor: "#fefefeff" jasmine.objectContaining({
, fontFamily: "__fontFamily" backgroundColor: "#fefefeff",
, windowRoundedCornerRadius: 5 fontFamily: "__fontFamily",
})); windowRoundedCornerRadius: 5
})
);
}); });
}); });

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.GenericMediaMetadata", () => { describe("chrome.cast.media.GenericMediaMetadata", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const genericMediaMetadata = new chrome.cast.media.GenericMediaMetadata(); const genericMediaMetadata =
new chrome.cast.media.GenericMediaMetadata();
expect(genericMediaMetadata.images).toBe(undefined); expect(genericMediaMetadata.images).toBe(undefined);
expect(genericMediaMetadata.metadataType).toBe(0); expect(genericMediaMetadata.metadataType).toBe(0);

View File

@@ -16,12 +16,16 @@ describe("chrome.cast.media.LoadRequest", () => {
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const mediaInfo = new chrome.cast.media.MediaInfo( const mediaInfo = new chrome.cast.media.MediaInfo(
"__contentId", "video/mp4"); "__contentId",
"video/mp4"
);
const loadRequest = new chrome.cast.media.LoadRequest(mediaInfo); const loadRequest = new chrome.cast.media.LoadRequest(mediaInfo);
expect(loadRequest.media).toEqual(jasmine.objectContaining({ expect(loadRequest.media).toEqual(
contentId: "__contentId" jasmine.objectContaining({
, contentType: "video/mp4" contentId: "__contentId",
})); contentType: "video/mp4"
})
);
}); });
}); });

View File

@@ -19,10 +19,12 @@ describe("chrome.cast.media.Media", () => {
expect(media.repeatMode).toBe("REPEAT_OFF"); expect(media.repeatMode).toBe("REPEAT_OFF");
expect(media.sessionId).toBe(undefined); expect(media.sessionId).toBe(undefined);
expect(media.supportedMediaCommands).toEqual([]); expect(media.supportedMediaCommands).toEqual([]);
expect(media.volume).toEqual(jasmine.objectContaining({ expect(media.volume).toEqual(
level: null jasmine.objectContaining({
, muted: null level: null,
})); muted: null
})
);
}); });
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {

View File

@@ -15,7 +15,10 @@ describe("chrome.cast.media.MediaInfo", () => {
}); });
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const mediaInfo = new chrome.cast.media.MediaInfo("__contentId", "video/mp4"); const mediaInfo = new chrome.cast.media.MediaInfo(
"__contentId",
"video/mp4"
);
expect(mediaInfo.contentId).toBe("__contentId"); expect(mediaInfo.contentId).toBe("__contentId");
expect(mediaInfo.contentType).toBe("video/mp4"); expect(mediaInfo.contentType).toBe("video/mp4");

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.MusicTrackMediaMetadata", () => { describe("chrome.cast.media.MusicTrackMediaMetadata", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const musicTrackMediaMetadata = new chrome.cast.media.MusicTrackMediaMetadata(); const musicTrackMediaMetadata =
new chrome.cast.media.MusicTrackMediaMetadata();
expect(musicTrackMediaMetadata.albumArtist).toBe(undefined); expect(musicTrackMediaMetadata.albumArtist).toBe(undefined);
expect(musicTrackMediaMetadata.albumName).toBe(undefined); expect(musicTrackMediaMetadata.albumName).toBe(undefined);

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.QueueInsertItemsRequest", () => { describe("chrome.cast.media.QueueInsertItemsRequest", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const queueInsertItemsRequest = new chrome.cast.media.QueueInsertItemsRequest(); const queueInsertItemsRequest =
new chrome.cast.media.QueueInsertItemsRequest();
expect(queueInsertItemsRequest.customData).toBe(null); expect(queueInsertItemsRequest.customData).toBe(null);
expect(queueInsertItemsRequest.insertBefore).toBe(null); expect(queueInsertItemsRequest.insertBefore).toBe(null);
@@ -16,20 +17,25 @@ describe("chrome.cast.media.QueueInsertItemsRequest", () => {
const media1 = new chrome.cast.media.MediaInfo("media1", "video/mp4"); const media1 = new chrome.cast.media.MediaInfo("media1", "video/mp4");
const media2 = new chrome.cast.media.MediaInfo("media2", "audio/mp3"); const media2 = new chrome.cast.media.MediaInfo("media2", "audio/mp3");
const queueInsertItemsRequest = new chrome.cast.media.QueueInsertItemsRequest([ const queueInsertItemsRequest =
new chrome.cast.media.QueueItem(media1) new chrome.cast.media.QueueInsertItemsRequest([
, new chrome.cast.media.QueueItem(media2) new chrome.cast.media.QueueItem(media1),
]); new chrome.cast.media.QueueItem(media2)
]);
expect(queueInsertItemsRequest.items).toEqual([ expect(queueInsertItemsRequest.items).toEqual([
jasmine.objectContaining({ media: jasmine.objectContaining({ jasmine.objectContaining({
contentId: "media1" media: jasmine.objectContaining({
, contentType: "video/mp4" contentId: "media1",
})}) contentType: "video/mp4"
, jasmine.objectContaining({ media: jasmine.objectContaining({ })
contentId: "media2" }),
, contentType: "audio/mp3" jasmine.objectContaining({
})}) media: jasmine.objectContaining({
contentId: "media2",
contentType: "audio/mp3"
})
})
]); ]);
}); });
}); });

View File

@@ -15,12 +15,17 @@ describe("chrome.cast.media.QueueItem", () => {
}); });
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const media = new chrome.cast.media.MediaInfo("__contentId", "video/mp4"); const media = new chrome.cast.media.MediaInfo(
"__contentId",
"video/mp4"
);
const queueItem = new chrome.cast.media.QueueItem(media); const queueItem = new chrome.cast.media.QueueItem(media);
expect(queueItem.media).toEqual(jasmine.objectContaining({ expect(queueItem.media).toEqual(
contentId: "__contentId" jasmine.objectContaining({
, contentType: "video/mp4" contentId: "__contentId",
})); contentType: "video/mp4"
})
);
}); });
}); });

View File

@@ -18,19 +18,23 @@ describe("chrome.cast.media.QueueLoadRequest", () => {
const media2 = new chrome.cast.media.MediaInfo("media2", "audio/mp3"); const media2 = new chrome.cast.media.MediaInfo("media2", "audio/mp3");
const queueLoadRequest = new chrome.cast.media.QueueLoadRequest([ const queueLoadRequest = new chrome.cast.media.QueueLoadRequest([
new chrome.cast.media.QueueItem(media1) new chrome.cast.media.QueueItem(media1),
, new chrome.cast.media.QueueItem(media2) new chrome.cast.media.QueueItem(media2)
]); ]);
expect(queueLoadRequest.items).toEqual([ expect(queueLoadRequest.items).toEqual([
jasmine.objectContaining({ media: jasmine.objectContaining({ jasmine.objectContaining({
contentId: "media1" media: jasmine.objectContaining({
, contentType: "video/mp4" contentId: "media1",
})}) contentType: "video/mp4"
, jasmine.objectContaining({ media: jasmine.objectContaining({ })
contentId: "media2" }),
, contentType: "audio/mp3" jasmine.objectContaining({
})}) media: jasmine.objectContaining({
contentId: "media2",
contentType: "audio/mp3"
})
})
]); ]);
}); });
}); });

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.QueueRemoveItemsRequest", () => { describe("chrome.cast.media.QueueRemoveItemsRequest", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const queueRemoveItemsRequest = new chrome.cast.media.QueueRemoveItemsRequest(); const queueRemoveItemsRequest =
new chrome.cast.media.QueueRemoveItemsRequest();
expect(queueRemoveItemsRequest.customData).toBe(null); expect(queueRemoveItemsRequest.customData).toBe(null);
expect(queueRemoveItemsRequest.itemIds).toBe(undefined); expect(queueRemoveItemsRequest.itemIds).toBe(undefined);
@@ -12,9 +13,9 @@ describe("chrome.cast.media.QueueRemoveItemsRequest", () => {
}); });
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const queueRemoveItemsRequest = new chrome.cast.media.QueueRemoveItemsRequest( const queueRemoveItemsRequest =
[ 5, 8, 12 ]); new chrome.cast.media.QueueRemoveItemsRequest([5, 8, 12]);
expect(queueRemoveItemsRequest.itemIds).toEqual([ 5, 8, 12 ]); expect(queueRemoveItemsRequest.itemIds).toEqual([5, 8, 12]);
}); });
}); });

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.QueueReorderItemsRequest", () => { describe("chrome.cast.media.QueueReorderItemsRequest", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const queueReorderItemsRequest = new chrome.cast.media.QueueReorderItemsRequest(); const queueReorderItemsRequest =
new chrome.cast.media.QueueReorderItemsRequest();
expect(queueReorderItemsRequest.customData).toBe(null); expect(queueReorderItemsRequest.customData).toBe(null);
expect(queueReorderItemsRequest.insertBefore).toBe(null); expect(queueReorderItemsRequest.insertBefore).toBe(null);
@@ -13,9 +14,9 @@ describe("chrome.cast.media.QueueReorderItemsRequest", () => {
}); });
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const queueReorderItemsRequest = new chrome.cast.media.QueueReorderItemsRequest( const queueReorderItemsRequest =
[ 5, 8, 12 ]); new chrome.cast.media.QueueReorderItemsRequest([5, 8, 12]);
expect(queueReorderItemsRequest.itemIds).toEqual([ 5, 8, 12 ]); expect(queueReorderItemsRequest.itemIds).toEqual([5, 8, 12]);
}); });
}); });

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.QueueSetPropertiesRequest", () => { describe("chrome.cast.media.QueueSetPropertiesRequest", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const queueSetPropertiesRequest = new chrome.cast.media.QueueSetPropertiesRequest(); const queueSetPropertiesRequest =
new chrome.cast.media.QueueSetPropertiesRequest();
expect(queueSetPropertiesRequest.customData).toBe(null); expect(queueSetPropertiesRequest.customData).toBe(null);
expect(queueSetPropertiesRequest.repeatMode).toBe(null); expect(queueSetPropertiesRequest.repeatMode).toBe(null);

View File

@@ -2,7 +2,8 @@
describe("chrome.cast.media.QueueUpdateItemsRequest", () => { describe("chrome.cast.media.QueueUpdateItemsRequest", () => {
it("should have all properties", async () => { it("should have all properties", async () => {
const queueUpdateItemsRequest = new chrome.cast.media.QueueUpdateItemsRequest(); const queueUpdateItemsRequest =
new chrome.cast.media.QueueUpdateItemsRequest();
expect(queueUpdateItemsRequest.customData).toBe(null); expect(queueUpdateItemsRequest.customData).toBe(null);
expect(queueUpdateItemsRequest.items).toBe(undefined); expect(queueUpdateItemsRequest.items).toBe(undefined);
@@ -15,20 +16,25 @@ describe("chrome.cast.media.QueueUpdateItemsRequest", () => {
const media1 = new chrome.cast.media.MediaInfo("media1", "video/mp4"); const media1 = new chrome.cast.media.MediaInfo("media1", "video/mp4");
const media2 = new chrome.cast.media.MediaInfo("media2", "audio/mp3"); const media2 = new chrome.cast.media.MediaInfo("media2", "audio/mp3");
const queueUpdateItemsRequest = new chrome.cast.media.QueueUpdateItemsRequest([ const queueUpdateItemsRequest =
new chrome.cast.media.QueueItem(media1) new chrome.cast.media.QueueUpdateItemsRequest([
, new chrome.cast.media.QueueItem(media2) new chrome.cast.media.QueueItem(media1),
]); new chrome.cast.media.QueueItem(media2)
]);
expect(queueUpdateItemsRequest.items).toEqual([ expect(queueUpdateItemsRequest.items).toEqual([
jasmine.objectContaining({ media: jasmine.objectContaining({ jasmine.objectContaining({
contentId: "media1" media: jasmine.objectContaining({
, contentType: "video/mp4" contentId: "media1",
})}) contentType: "video/mp4"
, jasmine.objectContaining({ media: jasmine.objectContaining({ })
contentId: "media2" }),
, contentType: "audio/mp3" jasmine.objectContaining({
})}) media: jasmine.objectContaining({
contentId: "media2",
contentType: "audio/mp3"
})
})
]); ]);
}); });
}); });

View File

@@ -15,7 +15,10 @@ describe("chrome.cast.media.Track", () => {
}); });
it("should have expected assigned properties", async () => { it("should have expected assigned properties", async () => {
const track = new chrome.cast.media.Track(5, chrome.cast.media.TrackType.TEXT); const track = new chrome.cast.media.Track(
5,
chrome.cast.media.TrackType.TEXT
);
expect(track.trackId).toBe(5); expect(track.trackId).toBe(5);
expect(track.type).toBe("TEXT"); expect(track.type).toBe("TEXT");

View File

@@ -12,9 +12,11 @@ describe("chrome.cast.media.VolumeRequest", () => {
const volume = new chrome.cast.Volume(0.5, false); const volume = new chrome.cast.Volume(0.5, false);
const volumeRequest = new chrome.cast.media.VolumeRequest(volume); const volumeRequest = new chrome.cast.media.VolumeRequest(volume);
expect(volumeRequest.volume).toEqual(jasmine.objectContaining({ expect(volumeRequest.volume).toEqual(
level: 0.5 jasmine.objectContaining({
, muted: false level: 0.5,
})); muted: false
})
);
}); });
}); });