Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Even more cleanups #40

Merged
merged 9 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"debounce-promise": "^3.1.2",
"howler": "^2.1.2",
"lz-string": "^1.4.4",
"rusha": "^0.8.13",
"semver": "^7.3.5"
},
"devDependencies": {
Expand Down
20 changes: 2 additions & 18 deletions src/js/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,6 @@ import { SettingsState } from "./states/settings";

const logger = createLogger("application");

// Set the name of the hidden property and the change event for visibility
let pageHiddenPropName, pageVisibilityEventName;
if (typeof document.hidden !== "undefined") {
// Opera 12.10 and Firefox 18 and later support
pageHiddenPropName = "hidden";
pageVisibilityEventName = "visibilitychange";
// @ts-ignore
} else if (typeof document.msHidden !== "undefined") {
pageHiddenPropName = "msHidden";
pageVisibilityEventName = "msvisibilitychange";
// @ts-ignore
} else if (typeof document.webkitHidden !== "undefined") {
pageHiddenPropName = "webkitHidden";
pageVisibilityEventName = "webkitvisibilitychange";
}

export class Application {
/**
* Boots the application
Expand Down Expand Up @@ -176,7 +160,7 @@ export class Application {
// Unload events
window.addEventListener("beforeunload", this.onBeforeUnload.bind(this), true);

document.addEventListener(pageVisibilityEventName, this.handleVisibilityChange.bind(this), false);
document.addEventListener("visibilitychange", this.handleVisibilityChange.bind(this), false);

// Track touches so we can update the focus appropriately
document.addEventListener("touchstart", this.updateFocusAfterUserInteraction.bind(this), true);
Expand Down Expand Up @@ -217,7 +201,7 @@ export class Application {
*/
handleVisibilityChange(event) {
window.focus();
const pageVisible = !document[pageHiddenPropName];
const pageVisible = !document.hidden;
if (pageVisible !== this.pageVisible) {
this.pageVisible = pageVisible;
logger.log("Visibility changed:", this.pageVisible);
Expand Down
23 changes: 2 additions & 21 deletions src/js/core/async_compression.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,12 @@
// @ts-ignore
// @ts-expect-error FIXME: missing typings
import CompressionWorker from "../webworkers/compression.worker";

import { createLogger } from "./logging";
import { round2Digits } from "./utils";

const logger = createLogger("async_compression");

export let compressionPrefix = String.fromCodePoint(1);

function checkCryptPrefix(prefix) {
try {
window.localStorage.setItem("prefix_test", prefix);
window.localStorage.removeItem("prefix_test");
return true;
} catch (ex) {
logger.warn("Prefix '" + prefix + "' not available");
return false;
}
}

if (!checkCryptPrefix(compressionPrefix)) {
logger.warn("Switching to basic prefix");
compressionPrefix = " ";
if (!checkCryptPrefix(compressionPrefix)) {
logger.warn("Prefix not available, ls seems to be unavailable");
}
}
export const compressionPrefix = String.fromCodePoint(1);

/**
* @typedef {{
Expand Down
6 changes: 1 addition & 5 deletions src/js/core/buffer_utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { globalConfig } from "./config";
import { fastArrayDelete } from "./utils";
import { createLogger } from "./logging";
import { fastArrayDelete } from "./utils";

const logger = createLogger("buffer_utils");

Expand All @@ -10,9 +10,6 @@ const logger = createLogger("buffer_utils");
*/
export function enableImageSmoothing(context) {
context.imageSmoothingEnabled = true;
context.webkitImageSmoothingEnabled = true;

// @ts-ignore
context.imageSmoothingQuality = globalConfig.smoothing.quality;
}

Expand All @@ -22,7 +19,6 @@ export function enableImageSmoothing(context) {
*/
export function disableImageSmoothing(context) {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
}

/**
Expand Down
10 changes: 1 addition & 9 deletions src/js/core/config.js → src/js/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,24 +108,16 @@ export const globalConfig = {

smoothing: {
smoothMainCanvas: smoothCanvas && true,
quality: "low", // Low is CRUCIAL for mobile performance!
quality: "low" as ImageSmoothingQuality, // Low is CRUCIAL for mobile performance!
},

rendering: {},
debug,

currentDiscount: 0,

// Secret vars
info: {
// Binary file salt
file: "Ec'])@^+*9zMevK3uMV4432x9%iK'=",

// Savegame salt
sgSalt: "}95Q3%8/.837Lqym_BJx%q7)pAHJbF",

// Analytics key
analyticsApiKey: "baf6a50f0cc7dfdec5a0e21c88a1c69a4b34bc4a",
},
};

Expand Down
4 changes: 0 additions & 4 deletions src/js/core/dpi_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,9 @@ export function prepareHighDPIContext(context, smooth = true) {

if (smooth) {
context.imageSmoothingEnabled = true;
context.webkitImageSmoothingEnabled = true;

// @ts-ignore
context.imageSmoothingQuality = globalConfig.smoothing.quality;
} else {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
}
}

Expand Down
83 changes: 0 additions & 83 deletions src/js/core/polyfills.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,79 +10,6 @@ function mathPolyfills() {
};
}

function stringPolyfills() {
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
padString = String(typeof padString !== "undefined" ? padString : " ");
if (this.length >= targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this);
}
};
}

// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
if (!String.prototype.padEnd) {
String.prototype.padEnd = function padEnd(targetLength, padString) {
targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
padString = String(typeof padString !== "undefined" ? padString : " ");
if (this.length > targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return String(this) + padString.slice(0, targetLength);
}
};
}
}

function objectPolyfills() {
// https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js

// @ts-ignore
const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
// @ts-ignore
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
// @ts-ignore
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;

// @ts-ignore
if (!Object.values) {
// @ts-ignore
Object.values = function values(O) {
return reduce(
keys(O),
(v, k) => concat(v, typeof k === "string" && isEnumerable(O, k) ? [O[k]] : []),
[]
);
};
}

if (!Object.entries) {
// @ts-ignore
Object.entries = function entries(O) {
return reduce(
keys(O),
(e, k) => concat(e, typeof k === "string" && isEnumerable(O, k) ? [[k, O[k]]] : []),
[]
);
};
}
}

function domPolyfills() {
// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
(function (arr) {
Expand All @@ -104,18 +31,8 @@ function domPolyfills() {

function initPolyfills() {
mathPolyfills();
stringPolyfills();
objectPolyfills();
domPolyfills();
}

function initExtensions() {
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
}

// Other polyfills
initPolyfills();
initExtensions();
23 changes: 9 additions & 14 deletions src/js/core/read_write_proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,20 @@
import { Application } from "../application";
/* typehints:end */

import { sha1, CRC_PREFIX, computeCrc } from "./sensitive_utils.encrypt";
import { createLogger } from "./logging";
import { FILE_NOT_FOUND } from "../platform/storage";
import { accessNestedPropertyReverse } from "./utils";
import { compressObject, decompressObject } from "../savegame/savegame_compressor";
import { asyncCompressor, compressionPrefix } from "./async_compression";
import { IS_DEBUG, globalConfig } from "./config";
import { ExplainedResult } from "./explained_result";
import { decompressX64, compressX64 } from "./lzstring";
import { asyncCompressor, compressionPrefix } from "./async_compression";
import { compressObject, decompressObject } from "../savegame/savegame_compressor";
import { createLogger } from "./logging";
import { compressX64, decompressX64 } from "./lzstring";
import { computeCrc } from "./sensitive_utils.encrypt";

import debounce from "debounce-promise";

const logger = createLogger("read_write_proxy");

const salt = accessNestedPropertyReverse(globalConfig, ["file", "info"]);
const salt = globalConfig.info.file;

// Helper which only writes / reads if verify() works. Also performs migration
export class ReadWriteProxy {
Expand Down Expand Up @@ -110,9 +109,7 @@ export class ReadWriteProxy {
const checksum = decompressed.substring(0, 40);
const jsonString = decompressed.substr(40);

const desiredChecksum = checksum.startsWith(CRC_PREFIX)
? computeCrc(jsonString + salt)
: sha1(jsonString + salt);
const desiredChecksum = computeCrc(jsonString + salt);

if (desiredChecksum !== checksum) {
// Checksum mismatch
Expand Down Expand Up @@ -199,11 +196,9 @@ export class ReadWriteProxy {

// Compare stored checksum with actual checksum
const checksum = decompressed.substring(0, 40);
const jsonString = decompressed.substr(40);
const jsonString = decompressed.slice(40);

const desiredChecksum = checksum.startsWith(CRC_PREFIX)
? computeCrc(jsonString + salt)
: sha1(jsonString + salt);
const desiredChecksum = computeCrc(jsonString + salt);

if (desiredChecksum !== checksum) {
// Checksum mismatch
Expand Down
11 changes: 0 additions & 11 deletions src/js/core/sensitive_utils.encrypt.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,4 @@
import { createHash } from "rusha";
import crc32 from "crc/crc32";
import { decompressX64 } from "./lzstring";

export function sha1(str) {
return createHash().update(str).digest("hex");
}

// Window.location.host
export function getNameOfProvider() {
return window[decompressX64("DYewxghgLgliB2Q")][decompressX64("BYewzgLgdghgtgUyA")];
}

// Distinguish legacy crc prefixes
export const CRC_PREFIX = "crc32".padEnd(32, "-");
Expand Down
19 changes: 3 additions & 16 deletions src/js/core/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,6 @@ export function randomInt(start, end) {
return Math.floor(Math.random() * (end - start + 1) + start);
}

/**
* Access an object in a very annoying way, used for obsfuscation.
* @param {any} obj
* @param {Array<string>} keys
*/
export function accessNestedPropertyReverse(obj, keys) {
let result = obj;
for (let i = keys.length - 1; i >= 0; --i) {
result = result[keys[i]];
}
return result;
}

/**
* Chooses a random entry of an array
* @template T
Expand Down Expand Up @@ -406,7 +393,7 @@ export function makeButton(parent, classes = [], innerHTML = "") {
*/
export function removeAllChildren(elem) {
if (elem) {
var range = document.createRange();
const range = document.createRange();
range.selectNodeContents(elem);
range.deleteContents();
}
Expand Down Expand Up @@ -618,7 +605,7 @@ export function fillInLinkIntoTranslation(translation, link) {
* @param {string} text
*/
export function generateFileDownload(filename, text) {
var element = document.createElement("a");
const element = document.createElement("a");
element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(text));
element.setAttribute("download", filename);

Expand All @@ -634,7 +621,7 @@ export function generateFileDownload(filename, text) {
* @param {string} acceptedType
*/
export function startFileChoose(acceptedType = ".bin") {
var input = document.createElement("input");
const input = document.createElement("input");
input.type = "file";
input.accept = acceptedType;

Expand Down
5 changes: 1 addition & 4 deletions src/js/core/vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,6 @@ export class Vector {
}
default: {
assertAlways(false, "Invalid fast inplace rotation: " + angle);
return this;
}
}
// return new Vector(this.x * cos - this.y * sin, this.x * sin + this.y * cos);
Expand Down Expand Up @@ -519,7 +518,6 @@ export class Vector {
}
default: {
assertAlways(false, "Invalid fast inplace rotation: " + angle);
return new Vector();
}
}
}
Expand Down Expand Up @@ -593,7 +591,6 @@ export class Vector {
}
default:
assertAlways(false, "Invalid angle: " + angle);
return;
}
}

Expand All @@ -603,7 +600,7 @@ export class Vector {
* @returns {Boolean}
*/
equalsEpsilon(v, epsilon = 1e-5) {
return Math.abs(this.x - v.x) < 1e-5 && Math.abs(this.y - v.y) < epsilon;
return Math.abs(this.x - v.x) < epsilon && Math.abs(this.y - v.y) < epsilon;
}

/**
Expand Down
Loading
Loading