The captcha solver made by and for japanese high school girls!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

24925 lines
743 KiB

var app = (function (exports) {
'use strict';
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
var runtime = {exports: {}};
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (module) {
var runtime = (function (exports) {
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined$1; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = GeneratorFunctionPrototype;
define(Gp, "constructor", GeneratorFunctionPrototype);
define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
});
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined$1) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined$1;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined$1;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
define(Gp, iteratorSymbol, function() {
return this;
});
define(Gp, "toString", function() {
return "[object Generator]";
});
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined$1;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined$1, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined$1;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined$1;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined$1;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined$1;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined$1;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
module.exports
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, in modern engines
// we can explicitly access globalThis. In older engines we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
}(runtime));
var regeneratorRuntime$1 = runtime.exports;
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
var inited = false;
function init$4 () {
inited = true;
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;
}
function toByteArray (b64) {
if (!inited) {
init$4();
}
var i, j, l, tmp, placeHolders, arr;
var len = b64.length;
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(len * 3 / 4 - placeHolders);
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len;
var L = 0;
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
arr[L++] = (tmp >> 16) & 0xFF;
arr[L++] = (tmp >> 8) & 0xFF;
arr[L++] = tmp & 0xFF;
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
arr[L++] = tmp & 0xFF;
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
arr[L++] = (tmp >> 8) & 0xFF;
arr[L++] = tmp & 0xFF;
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
output.push(tripletToBase64(tmp));
}
return output.join('')
}
function fromByteArray (uint8) {
if (!inited) {
init$4();
}
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var output = '';
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
output += lookup[tmp >> 2];
output += lookup[(tmp << 4) & 0x3F];
output += '==';
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
output += lookup[tmp >> 10];
output += lookup[(tmp >> 4) & 0x3F];
output += lookup[(tmp << 2) & 0x3F];
output += '=';
}
parts.push(output);
return parts.join('')
}
function read (buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? (nBytes - 1) : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
function write (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
var i = isLE ? 0 : (nBytes - 1);
var d = isLE ? 1 : -1;
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
}
var toString = {}.toString;
var isArray = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var INSPECT_MAX_BYTES = 50;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
? global$1.TYPED_ARRAY_SUPPORT
: true;
function kMaxLength () {
return Buffer$1.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length);
that.__proto__ = Buffer$1.prototype;
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer$1(length);
}
that.length = length;
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer$1 (arg, encodingOrOffset, length) {
if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
return new Buffer$1(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer$1.poolSize = 8192; // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer$1._augment = function (arr) {
arr.__proto__ = Buffer$1.prototype;
return arr
};
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer$1.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
};
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
Buffer$1.prototype.__proto__ = Uint8Array.prototype;
Buffer$1.__proto__ = Uint8Array;
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer$1.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
};
function allocUnsafe (that, size) {
assertSize(size);
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0;
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer$1.allocUnsafe = function (size) {
return allocUnsafe(null, size)
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer$1.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
};
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8';
}
if (!Buffer$1.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0;
that = createBuffer(that, length);
var actual = that.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual);
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
that = createBuffer(that, length);
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255;
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength; // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array);
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset);
} else {
array = new Uint8Array(array, byteOffset, length);
}
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array;
that.__proto__ = Buffer$1.prototype;
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array);
}
return that
}
function fromObject (that, obj) {
if (internalIsBuffer(obj)) {
var len = checked(obj.length) | 0;
that = createBuffer(that, len);
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len);
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
Buffer$1.isBuffer = isBuffer;
function internalIsBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer$1.compare = function compare (a, b) {
if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
};
Buffer$1.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
};
Buffer$1.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer$1.alloc(0)
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer$1.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (!internalIsBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer
};
function byteLength (string, encoding) {
if (internalIsBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string;
}
var len = string.length;
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer$1.byteLength = byteLength;
function slowToString (encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8';
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer$1.prototype._isBuffer = true;
function swap (b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer$1.prototype.swap16 = function swap16 () {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this
};
Buffer$1.prototype.swap32 = function swap32 () {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this
};
Buffer$1.prototype.swap64 = function swap64 () {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this
};
Buffer$1.prototype.toString = function toString () {
var length = this.length | 0;
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
};
Buffer$1.prototype.equals = function equals (b) {
if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer$1.compare(this, b) === 0
};
Buffer$1.prototype.inspect = function inspect () {
var str = '';
var max = INSPECT_MAX_BYTES;
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
if (this.length > max) str += ' ... ';
}
return '<Buffer ' + str + '>'
};
Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!internalIsBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1);
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer$1.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (internalIsBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF; // Search for a byte value [0-255]
if (Buffer$1.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break
}
}
if (found) return i
}
}
return -1
}
Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
};
Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
};
Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
};
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
// must be an even number of digits
var strLen = string.length;
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (isNaN(parsed)) return i
buf[offset + i] = parsed;
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer$1.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8';
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0;
if (isFinite(length)) {
length = length | 0;
if (encoding === undefined) encoding = 'utf8';
} else {
encoding = length;
length = undefined;
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8';
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer$1.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
};
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return fromByteArray(buf)
} else {
return fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint;
}
}
break
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint;
}
}
break
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD;
bytesPerSequence = 1;
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray (codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = '';
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
);
}
return res
}
function asciiSlice (buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F);
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = '';
for (var i = start; i < end; ++i) {
out += toHex(buf[i]);
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end);
var res = '';
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res
}
Buffer$1.prototype.slice = function slice (start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf;
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end);
newBuf.__proto__ = Buffer$1.prototype;
} else {
var sliceLen = end - start;
newBuf = new Buffer$1(sliceLen, undefined);
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start];
}
}
return newBuf
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val
};
Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val
};
Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset]
};
Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | (this[offset + 1] << 8)
};
Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
return (this[offset] << 8) | this[offset + 1]
};
Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
};
Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
};
Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val
};
Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val
};
Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
};
Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | (this[offset + 1] << 8);
return (val & 0x8000) ? val | 0xFFFF0000 : val
};
Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | (this[offset] << 8);
return (val & 0x8000) ? val | 0xFFFF0000 : val
};
Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
};
Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
};
Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return read(this, offset, true, 23, 4)
};
Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return read(this, offset, false, 23, 4)
};
Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length);
return read(this, offset, true, 52, 8)
};
Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length);
return read(this, offset, false, 52, 8)
};
function checkInt (buf, value, offset, ext, max, min) {
if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF;
}
return offset + byteLength
};
Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF;
}
return offset + byteLength
};
Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
this[offset] = (value & 0xff);
return offset + 1
};
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1;
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8;
}
}
Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff);
this[offset + 1] = (value >>> 8);
} else {
objectWriteUInt16(this, value, offset, true);
}
return offset + 2
};
Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8);
this[offset + 1] = (value & 0xff);
} else {
objectWriteUInt16(this, value, offset, false);
}
return offset + 2
};
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1;
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
}
}
Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24);
this[offset + 2] = (value >>> 16);
this[offset + 1] = (value >>> 8);
this[offset] = (value & 0xff);
} else {
objectWriteUInt32(this, value, offset, true);
}
return offset + 4
};
Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24);
this[offset + 1] = (value >>> 16);
this[offset + 2] = (value >>> 8);
this[offset + 3] = (value & 0xff);
} else {
objectWriteUInt32(this, value, offset, false);
}
return offset + 4
};
Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
}
return offset + byteLength
};
Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
}
return offset + byteLength
};
Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
if (value < 0) value = 0xff + value + 1;
this[offset] = (value & 0xff);
return offset + 1
};
Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff);
this[offset + 1] = (value >>> 8);
} else {
objectWriteUInt16(this, value, offset, true);
}
return offset + 2
};
Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8);
this[offset + 1] = (value & 0xff);
} else {
objectWriteUInt16(this, value, offset, false);
}
return offset + 2
};
Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff);
this[offset + 1] = (value >>> 8);
this[offset + 2] = (value >>> 16);
this[offset + 3] = (value >>> 24);
} else {
objectWriteUInt32(this, value, offset, true);
}
return offset + 4
};
Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24);
this[offset + 1] = (value >>> 16);
this[offset + 2] = (value >>> 8);
this[offset + 3] = (value & 0xff);
} else {
objectWriteUInt32(this, value, offset, false);
}
return offset + 4
};
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4);
}
write(buf, value, offset, littleEndian, 23, 4);
return offset + 4
}
Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
};
Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
};
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8);
}
write(buf, value, offset, littleEndian, 52, 8);
return offset + 8
}
Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
};
Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer$1.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
var i;
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start];
}
} else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start];
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
);
}
return len
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer$1.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if (code < 256) {
val = code;
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255;
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = internalIsBuffer(val)
? val
: utf8ToBytes(new Buffer$1(val, encoding).toString());
var len = bytes.length;
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '');
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '=';
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue
}
// valid lead
leadSurrogate = codePoint;
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
leadSurrogate = codePoint;
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
);
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF);
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray
}
function base64ToBytes (str) {
return toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i];
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
function isBuffer(obj) {
return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
}
function isFastBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
}
function noop$1() { }
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run$2(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run$2);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
let src_url_equal_anchor;
function src_url_equal(element_src, url) {
if (!src_url_equal_anchor) {
src_url_equal_anchor = document.createElement('a');
}
src_url_equal_anchor.href = url;
return element_src === src_url_equal_anchor.href;
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop$1;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function get_all_dirty_from_scope($$scope) {
if ($$scope.ctx.length > 32) {
const dirty = [];
const length = $$scope.ctx.length / 32;
for (let i = 0; i < length; i++) {
dirty[i] = -1;
}
return dirty;
}
return -1;
}
function null_to_empty(value) {
return value == null ? '' : value;
}
function set_store_value(store, ret, value) {
store.set(value);
return ret;
}
function append(target, node) {
target.appendChild(node);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function text$1(data) {
return document.createTextNode(data);
}
function space() {
return text$1(' ');
}
function empty() {
return text$1('');
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function to_number(value) {
return value === '' ? null : +value;
}
function children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.wholeText !== data)
text.data = data;
}
function set_input_value(input, value) {
input.value = value == null ? '' : value;
}
function set_style(node, key, value, important) {
node.style.setProperty(key, value, important ? 'important' : '');
}
function select_option(select, value) {
for (let i = 0; i < select.options.length; i += 1) {
const option = select.options[i];
if (option.__value === value) {
option.selected = true;
return;
}
}
select.selectedIndex = -1; // no option should be selected
}
function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
return selected_option && selected_option.__value;
}
function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function custom_event(type, detail, bubbles = false) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, bubbles, false, detail);
return e;
}
class HtmlTag {
constructor() {
this.e = this.n = null;
}
c(html) {
this.h(html);
}
m(html, target, anchor = null) {
if (!this.e) {
this.e = element(target.nodeName);
this.t = target;
this.c(html);
}
this.i(anchor);
}
h(html) {
this.e.innerHTML = html;
this.n = Array.from(this.e.childNodes);
}
i(anchor) {
for (let i = 0; i < this.n.length; i += 1) {
insert(this.t, this.n[i], anchor);
}
}
p(html) {
this.d();
this.h(html);
this.i(this.a);
}
d() {
this.n.forEach(detach);
}
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error('Function called outside component initialization');
return current_component;
}
function beforeUpdate(fn) {
get_current_component().$$.before_update.push(fn);
}
function onMount(fn) {
get_current_component().$$.on_mount.push(fn);
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
// @ts-ignore
callbacks.slice().forEach(fn => fn.call(this, event));
}
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
// flush() calls callbacks in this order:
// 1. All beforeUpdate callbacks, in order: parents before children
// 2. All bind:this callbacks, in reverse order: children before parents.
// 3. All afterUpdate callbacks, in order: parents before children. EXCEPT
// for afterUpdates called during the initial onMount, which are called in
// reverse order: children before parents.
// Since callbacks might update component values, which could trigger another
// call to flush(), the following steps guard against this:
// 1. During beforeUpdate, any updated components will be added to the
// dirty_components array and will cause a reentrant call to flush(). Because
// the flush index is kept outside the function, the reentrant call will pick
// up where the earlier call left off and go through all dirty components. The
// current_component value is saved and restored so that the reentrant call will
// not interfere with the "parent" flush() call.
// 2. bind:this callbacks cannot trigger new flush() calls.
// 3. During afterUpdate, any updated components will NOT have their afterUpdate
// callback called a second time; the seen_callbacks set, outside the flush()
// function, guarantees this behavior.
const seen_callbacks = new Set();
let flushidx = 0; // Do *not* move this inside the flush() function
function flush() {
const saved_component = current_component;
do {
// first, call beforeUpdate functions
// and update components
while (flushidx < dirty_components.length) {
const component = dirty_components[flushidx];
flushidx++;
set_current_component(component);
update(component.$$);
}
set_current_component(null);
dirty_components.length = 0;
flushidx = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
seen_callbacks.clear();
set_current_component(saved_component);
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
const outroing = new Set();
let outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros // parent group
};
}
function check_outros() {
if (!outros.r) {
run_all(outros.c);
}
outros = outros.p;
}
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
function destroy_block(block, lookup) {
block.d(1);
lookup.delete(block.key);
}
function outro_and_destroy_block(block, lookup) {
transition_out(block, 1, 1, () => {
lookup.delete(block.key);
});
}
function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block, next, get_context) {
let o = old_blocks.length;
let n = list.length;
let i = o;
const old_indexes = {};
while (i--)
old_indexes[old_blocks[i].key] = i;
const new_blocks = [];
const new_lookup = new Map();
const deltas = new Map();
i = n;
while (i--) {
const child_ctx = get_context(ctx, list, i);
const key = get_key(child_ctx);
let block = lookup.get(key);
if (!block) {
block = create_each_block(key, child_ctx);
block.c();
}
else if (dynamic) {
block.p(child_ctx, dirty);
}
new_lookup.set(key, new_blocks[i] = block);
if (key in old_indexes)
deltas.set(key, Math.abs(i - old_indexes[key]));
}
const will_move = new Set();
const did_move = new Set();
function insert(block) {
transition_in(block, 1);
block.m(node, next);
lookup.set(block.key, block);
next = block.first;
n--;
}
while (o && n) {
const new_block = new_blocks[n - 1];
const old_block = old_blocks[o - 1];
const new_key = new_block.key;
const old_key = old_block.key;
if (new_block === old_block) {
// do nothing
next = new_block.first;
o--;
n--;
}
else if (!new_lookup.has(old_key)) {
// remove old block
destroy(old_block, lookup);
o--;
}
else if (!lookup.has(new_key) || will_move.has(new_key)) {
insert(new_block);
}
else if (did_move.has(old_key)) {
o--;
}
else if (deltas.get(new_key) > deltas.get(old_key)) {
did_move.add(new_key);
insert(new_block);
}
else {
will_move.add(old_key);
o--;
}
}
while (o--) {
const old_block = old_blocks[o];
if (!new_lookup.has(old_block.key))
destroy(old_block, lookup);
}
while (n)
insert(new_blocks[n - 1]);
return new_blocks;
}
function create_component(block) {
block && block.c();
}
function mount_component(component, target, anchor, customElement) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
if (!customElement) {
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run$2).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
}
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init$3(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop$1,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
// everything else
callbacks: blank_object(),
dirty,
skip_bound: false,
root: options.target || parent_component.$$.root
};
append_styles && append_styles($$.root);
let ready = false;
$$.ctx = instance
? instance(component, options.props || {}, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if (!$$.skip_bound && $$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor, options.customElement);
flush();
}
set_current_component(parent_component);
}
/**
* Base class for Svelte components. Used when dev=false.
*/
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop$1;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
}
const subscriber_queue = [];
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop$1) {
let stop;
const subscribers = new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop$1) {
const subscriber = [run, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set) || noop$1;
}
run(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
function _defineProperty$3(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread$3(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_defineProperty$3(target, key, source[key]);
});
}
return target;
}
var localLoad = function(key, def) {
return "__pee__" + key in localStorage ? JSON.parse(localStorage.getItem("__pee__" + key)) : def;
};
var localSet = function(key, value) {
return localStorage.setItem("__pee__" + key, JSON.stringify(value));
};
var initial_settings = localLoad("settingsv2", _objectSpread$3({}, localLoad("settings", {}), {
loop: true,
dh: false,
xpv: false,
xpi: false,
hyd: false,
ak: "",
auto_embed: 0,
auto_tags: "",
te: false,
eye: false,
ca: false,
pre: false,
prev: false,
sh: false,
ep: false,
tm: false,
expte: false,
mdist: -1,
phash: false,
hotlink: false,
vercheck: false,
fhost: 0,
maxe: 5,
conc: 8,
ho: false,
blacklist: [
"guro",
"scat",
"ryona",
"gore"
],
rsources: [
{
name: "Gelbooru",
domain: "gelbooru.com",
endpoint: "/index.php?page=dapi&s=post&q=index&json=1&tags=md5:",
view: "https://gelbooru.com/index.php?page=post&s=view&id="
},
{
name: "Yandere",
domain: "yande.re",
endpoint: "/post.json?tags=md5:",
view: "https://yande.re/post/show/"
},
{
name: "Sankaku",
domain: "capi-v2.sankakucomplex.com",
endpoint: "/posts/keyset?tags=md5:",
view: "https://chan.sankakucomplex.com/post/show/"
},
{
name: "Rule34",
domain: "api.rule34.xxx",
endpoint: "/index.php?page=dapi&s=post&q=index&json=1&tags=md5:",
// note: rule34 do not seem to give source in their API
view: "https://rule34.xxx/index.php?page=post&s=view&id="
},
{
name: "Danbooru",
domain: "danbooru.donmai.us",
endpoint: "/posts.json?tags=md5:",
view: "https://danbooru.donmai.us/posts/"
},
{
name: "Lolibooru",
domain: "lolibooru.moe",
endpoint: "/post.json?tags=md5:",
view: "https://lolibooru.moe/post/show/"
},
{
name: "ATFbooru",
domain: "booru.allthefallen.moe",
endpoint: "/posts.json?tags=md5:",
view: "https://booru.allthefallen.moe/posts/"
}
]
}, localLoad("settingsv2", {})));
var settings = writable(initial_settings);
var appState = writable({
isCatalog: false,
is4chanX: false,
akValid: false,
herror: "",
client: null,
foundPosts: []
});
settings.subscribe(function(newVal) {
localSet("settingsv2", newVal);
});
var nativeMax = Math.max;
var nativeMin = Math.min;
function debounce(func, wait, options) {
var invokeFunc = function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result1 = func.apply(thisArg, args);
return result1;
};
var leadingEdge = function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result1;
};
var remainingWait = function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall;
console.log("remainingWait");
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
};
var shouldInvoke = function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the trailing
// edge, the system time has gone backwards and we're treating it as the
// trailing edge, or we've hit the `maxWait` limit.
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
};
var trailingEdge = function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been debounced at
// least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result1;
};
var cancel = function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
};
var flush = function flush() {
return timerId === undefined ? result1 : trailingEdge(Date.now());
};
var debounced = function debounced() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var time = Date.now(), isInvoking = shouldInvoke(time);
lastArgs = args;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result1;
};
var lastArgs, lastThis, maxWait, result1, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
wait = Number(wait) || 0;
if (typeof options === "object") {
leading = !!options.leading;
maxing = "maxWait" in options;
maxWait = maxing ? nativeMax(Number(options.maxWait) || 0, wait) : maxWait;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function timerExpired() {
var time = Date.now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
var globalCss = ".pee-hidden {\n display: none;\n}\n\n.extractedImg {\n width: auto;\n height: auto;\n max-width: 125px;\n max-height: 125px;\n cursor: pointer;\n}\n\n#delform .postContainer>div.embedfound {\n border-right: 3px dashed green !important;\n}\n\n#delform .postContainer>div.hasembed {\n border-right: 3px dashed deeppink !important;\n}\n\n.hasembed.catalog-post {\n border: 3px dashed deeppink !important;\n}\n\n#delform .postContainer>div.hasext {\n border-right: 3px dashed goldenrod !important;\n}\n\n#delform .postContainer>div.hasmultiple {\n border-right: 3px dashed cornflowerblue !important;\n}\n\n.post_wrapper.embedfound {\n border-right: 3px dashed green !important;\n}\n\n.post_wrapper.hasembed {\n border-right: 3px dashed deeppink !important;\n}\n\n.post_wrapper.hasext {\n border-right: 3px dashed goldenrod !important;\n}\n\n.post_wrapper.hasmultiple {\n border-right: 3px dashed cornflowerblue !important;\n}\n\n.hasext.catalog-post {\n border: 3px dashed goldenrod !important;\n}\n\n.expanded-image>.post>.file .fileThumb>img[data-md5] {\n display: none;\n}\n\n.expanded-image>.post>.file .fileThumb .full-image {\n display: inline;\n}\n\n.pee-settings {\n position: fixed;\n top: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n}\n\ndiv.hasemb .catalog-host img {\n border: 1px solid deeppink;\n}\n\ndiv.hasext .catalog-host img {\n border: 1px solid goldenrod;\n}\n\ndiv.hasmultiple .catalog-host img {\n border: 1px solid cornflowerblue;\n}\n\n.catalog-host img {\n position: absolute;\n top: -5px;\n right: 0px;\n max-width: 80px;\n max-height: 80px;\n box-shadow: 0px 0px 4px 2px #00000090;\n}\n\n.fileThumb.filehost {\n margin-left: 0 !important;\n display: flex;\n gap: 20px;\n}\n\n#qr > form {\n overflow: visible !important;\n}\n\n.theme_default .post_wrapper > .thread_image_box {\n display: flex;\n}\n\n.theme_default .post_wrapper > .thread_image_box > a {\n margin-right: 20px;\n}\n";
var crc32 = {};
/* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
(function (exports) {
(function (factory) {
/*jshint ignore:start */
/*eslint-disable */
if(typeof DO_NOT_EXPORT_CRC === 'undefined') {
{
factory(exports);
}
} else {
factory({});
}
/*eslint-enable */
/*jshint ignore:end */
}(function(CRC32) {
CRC32.version = '1.2.0';
/* see perf/crc32table.js */
/*global Int32Array */
function signed_crc_table() {
var c = 0, table = new Array(256);
for(var n =0; n != 256; ++n){
c = n;
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
table[n] = c;
}
return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
}
var T = signed_crc_table();
function crc32_bstr(bstr, seed) {
var C = seed ^ -1, L = bstr.length - 1;
for(var i = 0; i < L;) {
C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
}
if(i === L) C = (C>>>8) ^ T[(C ^ bstr.charCodeAt(i))&0xFF];
return C ^ -1;
}
function crc32_buf(buf, seed) {
if(buf.length > 10000) return crc32_buf_8(buf, seed);
var C = seed ^ -1, L = buf.length - 3;
for(var i = 0; i < L;) {
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
}
while(i < L+3) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
return C ^ -1;
}
function crc32_buf_8(buf, seed) {
var C = seed ^ -1, L = buf.length - 7;
for(var i = 0; i < L;) {
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
}
while(i < L+7) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
return C ^ -1;
}
function crc32_str(str, seed) {
var C = seed ^ -1;
for(var i = 0, L=str.length, c, d; i < L;) {
c = str.charCodeAt(i++);
if(c < 0x80) {
C = (C>>>8) ^ T[(C ^ c)&0xFF];
} else if(c < 0x800) {
C = (C>>>8) ^ T[(C ^ (192|((c>>6)&31)))&0xFF];
C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
} else if(c >= 0xD800 && c < 0xE000) {
c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
C = (C>>>8) ^ T[(C ^ (240|((c>>8)&7)))&0xFF];
C = (C>>>8) ^ T[(C ^ (128|((c>>2)&63)))&0xFF];
C = (C>>>8) ^ T[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
C = (C>>>8) ^ T[(C ^ (128|(d&63)))&0xFF];
} else {
C = (C>>>8) ^ T[(C ^ (224|((c>>12)&15)))&0xFF];
C = (C>>>8) ^ T[(C ^ (128|((c>>6)&63)))&0xFF];
C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
}
}
return C ^ -1;
}
CRC32.table = T;
// $FlowIgnore
CRC32.bstr = crc32_bstr;
// $FlowIgnore
CRC32.buf = crc32_buf;
// $FlowIgnore
CRC32.str = crc32_str;
}));
}(crc32));
function AsyncGenerator$1(gen) {
var front, back;
function send(key, arg) {
return new Promise(function(resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
var wrappedAwait = value instanceof _AwaitValue$1;
Promise.resolve(wrappedAwait ? value.wrapped : value).then(function(arg) {
if (wrappedAwait) {
resume("next", arg);
return;
}
settle(result.done ? "return" : "normal", arg);
}, function(err) {
resume("throw", err);
});
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch(type){
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator$1.prototype[Symbol.asyncIterator] = function() {
return this;
};
}
AsyncGenerator$1.prototype.next = function(arg) {
return this._invoke("next", arg);
};
AsyncGenerator$1.prototype.throw = function(arg) {
return this._invoke("throw", arg);
};
AsyncGenerator$1.prototype.return = function(arg) {
return this._invoke("return", arg);
};
function asyncGeneratorStep$c(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$c(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$c(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$c(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _awaitAsyncGenerator$1(value) {
return new _AwaitValue$1(value);
}
function _AwaitValue$1(value) {
this.wrapped = value;
}
function _classCallCheck$5(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _wrapAsyncGenerator$1(fn) {
return function() {
return new AsyncGenerator$1(fn.apply(this, arguments));
};
}
var PNGDecoder = /*#__PURE__*/ function() {
function PNGDecoder(reader) {
_classCallCheck$5(this, PNGDecoder);
this.reader = reader;
this.req = 8;
this.ptr = 8;
this.repr = Buffer$1.from([]);
}
var _proto = PNGDecoder.prototype;
_proto.catchup = function catchup() {
var _this = this;
return _asyncToGenerator$c(regeneratorRuntime$1.mark(function _callee() {
var chunk;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (!(_this.repr.byteLength < _this.req)) {
_ctx.next = 9;
break;
}
_ctx.next = 3;
return _this.reader.read();
case 3:
chunk = _ctx.sent;
if (!chunk.done) {
_ctx.next = 6;
break;
}
throw new Error("Unexpected EOF, got ".concat(_this.repr.byteLength, ", required ").concat(_this.req, ", ").concat(chunk.value));
case 6:
_this.repr = Buffer$1.concat([
_this.repr,
chunk.value
]);
_ctx.next = 0;
break;
case 9:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_proto.chunks = function chunks() {
var _this = this;
return _wrapAsyncGenerator$1(regeneratorRuntime$1.mark(function _callee1() {
var length, name, pos;
return regeneratorRuntime$1.wrap(function _callee$(_ctx1) {
while(1)switch(_ctx1.prev = _ctx1.next){
case 0:
_this.req += 8; // req length and name
_ctx1.next = 4;
return _awaitAsyncGenerator$1(_this.catchup());
case 4:
length = _this.repr.readUInt32BE(_this.ptr);
name = _this.repr.slice(_this.ptr + 4, _this.ptr + 8).toString();
_this.ptr += 4;
_this.req += length + 4; // crc
pos = _this.ptr;
_ctx1.next = 11;
return [
name,
_asyncToGenerator$c(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return _this.catchup();
case 2:
return _ctx.abrupt("return", _this.repr.slice(pos, pos + length + 4));
case 3:
case "end":
return _ctx.stop();
}
}, _callee);
})),
_asyncToGenerator$c(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return _this.catchup();
case 2:
return _ctx.abrupt("return", _this.repr.readUInt32BE(_this.ptr + length + 4));
case 3:
case "end":
return _ctx.stop();
}
}, _callee);
})),
_this.ptr
];
case 11:
_this.ptr += length + 8;
if (!(name == "IEND")) {
_ctx1.next = 14;
break;
}
return _ctx1.abrupt("break", 16);
case 14:
_ctx1.next = 0;
break;
case 16:
case "end":
return _ctx1.stop();
}
}, _callee1);
}))();
};
_proto.dtor = function dtor() {
return _asyncToGenerator$c(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
case "end":
return _ctx.stop();
}
}, _callee);
//ugh
}))();
};
return PNGDecoder;
}();
var PNGEncoder = /*#__PURE__*/ function() {
function PNGEncoder(bytes) {
_classCallCheck$5(this, PNGEncoder);
this.writer = bytes.getWriter();
this.writer.write(Buffer$1.from([
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A
]));
}
var _proto = PNGEncoder.prototype;
_proto.insertchunk = function insertchunk(chunk) {
var _this = this;
return _asyncToGenerator$c(regeneratorRuntime$1.mark(function _callee() {
var b, buff;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
b = Buffer$1.alloc(4);
_ctx.next = 3;
return chunk[1]();
case 3:
buff = _ctx.sent;
b.writeInt32BE(buff.length - 4, 0);
_ctx.next = 7;
return _this.writer.write(b);
case 7:
_ctx.next = 9;
return _this.writer.write(buff);
case 9:
b.writeInt32BE(crc32.buf(buff), 0);
_ctx.next = 12;
return _this.writer.write(b);
case 12:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_proto.dtor = function dtor() {
var _this = this;
return _asyncToGenerator$c(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_this.writer.releaseLock();
_ctx.next = 3;
return _this.writer.close();
case 3:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
return PNGEncoder;
}();
var BufferWriteStream$1 = function() {
var b = Buffer$1.from([]);
var ret = new WritableStream({
write: function write(chunk) {
b = Buffer$1.concat([
b,
chunk
]);
}
});
return [
ret,
function() {
return b;
}
];
};
function base64ToBuffer(base64) {
const binary = window.atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; ++i) { bytes[i] = binary.charCodeAt(i); }
return bytes.buffer;
}
var thumbnail = base64ToBuffer("iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAMAAABHPGVmAAAAMFBMVEX+/v3c3c2moZhda1ODfnfKvK49RDgCAgIbHxpsGhv6BQT9hIOV0Hh4pWO03Z//5coEk9oIAAAHdUlEQVR42qWZDXurIAyFhcDJsS31///bKzEWHX6sd2fPVqYbLycJwXXDTiGKSMrDkQKGc8WwjhCHa0WoSY5u5guIYIUk5BuGEc4oUYZTaVztUq4ZWZtSfzulCyPrCAjXEGgT+9vncQhoRtI1I1BnIdEouYecG5FmZPhNRsLn9T4l3fIjwq8gcXlFv9xwXpPriDLcKHjGYeX1RW0J2uBWUid3FsPPm+flz7Qd3FtJbqhzkuSiYHIzcq8Ybb7KiCRju5PlqirdNdLwewlT2u/IcNUrEvyVwzfKAbvEhHS1RrBF6ysK1ZRvGW0DxhbekGOSlGKzfxgIbpyE8XqJEI9W8GZN6ioi2VU9osSWk8jx8byCMC1zw5JHEiIwOY4YHmM8PDx0sZ/Gx6w9JeQcq3JoRZUUFeFLD+G1qBSh6vB4jBchjzI8NpSQE6BNgAiiodQINg4hvF9NxeYY02mFShw+lAogCUCAFhAiW3wpS/wNsGPQphjloP2FmINtkIdJoCSkvH5OIYZUxAURXk0CcsmJaQRi2IVdLGe1dJ7z7ZEkDNApDEFY27drYwRqC1shdR4dIalKBBhbwg3RCB3Edj39KNmnQ1QtZeoQJ4lIijF4kKzQZkaLUq+3zQ0iz+kwwkYFygrZUaahyr7m52TbHYa4gQxFwBT7u0XICtGO0fZFhAfqzskyHV69KkUbxeeefOQ2XjeyXEjx2JQDCgbdUAbTh5fdxr2RSBpFDillUNMmXB9bibxFFGOEIv6z9tqlxSH6CVirNL1nENGrtlCPKJWuNEijNFHlykHxfYCU1vyqXRRFo1CVJAzSU0bVKxsgpKyzoBRrLrTpy7ZWyroZDylm/lxic9ugYhapmvnSAmbfBId0FD2OlZQWB5JiSzWJFBGSHsMNRWGQnkJ2DDdP+SQDJPzk8/wV240esGY67SG6JgTHmVCQCo9JEiNQZZq82sUpdiaUspoOg/YU8n1sJE3zfLBoCGk2INT5aiTFKFoxhl9ro9QS7ijUGA4hzFNVpMKObskZBBTzxSykRUp1xkFjSIB6cRhkRxk1DXsI1zxMroRqw5iJBKRSUjVTaCbEn3SMUzhoJ/jp1hzI6z3vamBalaEEYUOSFWdmzOE6yeAcooNQ47A4efsRJCyhXmKamiIISh0FKhd8qGZIxMRGGQI6iN99z2sf3BGY67BodoDPqOpJEmX0OFo5LIPho9A7yX6jyijUWHugp6RppsBtESs6qiqMkhqlgzSbwb6E4t0CmH4okqu5sE2XWQbDOUTWe2kZVQjKLMr0UwEy9YrKClOcQ8rbjdhSLExWSYVp6oWpV6DWFAnzOcQO1DkJ5Dx428FdP4T5aNU2q6gydlbIMwjs1A7WDV5vY8xieQmnE2U1bRYhmtzKMUTs8eNlkLL0CQRhKcAZg+qU0LBmBXIMYakbJBhEizE0TplSKOdGXOmHFeIAQlmiFd4VQpUCUnReICCMJ5B0AAnKXRVvI1VsR1SEQQBy2YMgKutQoqvihly/SR3EMuAnu0NYjQEWXup0oqir8rSz0kNgrXAHsXr27QHV6UyfxG8vQvM2XG6jhxjZ22KyhnRdXnlfDjJxB+Hr1UP8JKUvN0/nygKJnT+2Humh6iCiSraOFacvlZRxWGWMc4gH4Xvl7TuyjbFWl2DNCUUw/a+IBnFGgxRygRAk/x8iG8jrFBInIfN/QwLCCUQsTss4b3dHTpK+BGo8hlBLg4QpKnZbQb6DSAcxoUKgxSETkv+8K32f+R4iNV5CMUhN3o9Gy/AFBAqEDuInlRDGu26090oKQo6cKDwp4BEkfQUpRYC+ulTFkrKHpP+F1NgjO6T1xE+8yKMTNn8JMQq2ENEqWbYjscuhiV9Vl3fCAg47I1WweBmkSayTfbcbSZ8Xw86IaYnXz1Mq5/BlW1G+XMPOiAkFykJMf1M6hOhW0PhHCCjrzMPWiItI1L9Cco27SVripblItjPyH6NFfmb+QLBrHVn1z9Fqjw5DlxF6zf6NEeup0RK/jGUHyRHyXXAQfrZgvhoErJSCLSRSVZF/v2wwHRtxiD8FcwuBplQx4Xd1hH5BXI2UskAUxVKygcyfjFDG35VR6tuWwpyQhJRBjSIbSJ6gFTKlOr6PlIR+j0AAKyeRkWoQFWqTTBEzJNUSS3eR4kHqApmGNEqFxOH5GBcIdCPa2Z5gfyyH60jhKKBkPXRH1iyE+ob5AqFuZcs3K8R1Og6NUsdh1nOmCOeBQTr5O0tMWeOUbk+RnvEYqsYRglOI0mudFUd+QwmV8Xi6FT2HtHd/kjn6gpJJ+fxr4TFyfObnGURl37Tl18c607zy1crD/mnVIL2XJlX+MlRknqduVkynECoRg/1mAvmr5xSxsnLIdA/xomaVklKZt91FvaxunTQRIqgQyHIQMN8hPBeTG7mFeG+uascmTjBBqMpHczANpucdhHht9LkYekLCksN1wqbHDYQsHcTE/V91GcaOWXvK4xYiW0bplgCA9OKQmRq1UZ7ZY3UDIXZGuAOQ68AApqROabqHlDMjNKlKzGG31a8o/wBpRk19RswBZgAAAABJRU5ErkJggg==");
function _arrayLikeToArray$9(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles$6(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles$6(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$9(arr);
}
function asyncGeneratorStep$b(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$b(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$b(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$b(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperty$2(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _iterableToArray$6(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit$6(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$6() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread$6() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _objectSpread$2(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_defineProperty$2(target, key, source[key]);
});
}
return target;
}
function _slicedToArray$6(arr, i) {
return _arrayWithHoles$6(arr) || _iterableToArrayLimit$6(arr, i) || _unsupportedIterableToArray$9(arr, i) || _nonIterableRest$6();
}
function _toArray(arr) {
return _arrayWithHoles$6(arr) || _iterableToArray$6(arr) || _unsupportedIterableToArray$9(arr, i) || _nonIterableRest$6();
}
function _toConsumableArray$6(arr) {
return _arrayWithoutHoles$6(arr) || _iterableToArray$6(arr) || _unsupportedIterableToArray$9(arr) || _nonIterableSpread$6();
}
function _unsupportedIterableToArray$9(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$9(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$9(o, minLen);
}
var xmlhttprequest = typeof GM_xmlhttpRequest != "undefined" ? GM_xmlhttpRequest : typeof GM != "undefined" ? GM.xmlHttpRequest : window["GM_xmlhttpRequest"];
var headerStringToObject = function(s) {
return Object.fromEntries(s.split("\n").map(function(e) {
var ref = _toArray(e.split(":")), name = ref[0], rest = ref.slice(1);
return [
name.toLowerCase(),
rest.join(":").trim()
];
}));
};
var GM_fetch = function() {
for(var _len1 = arguments.length, _tmp = new Array(_len1), _key1 = 0; _key1 < _len1; _key1++){
_tmp[_key1] = arguments[_key1];
}
var __tmp = _slicedToArray$6(_tmp, 3), url = __tmp[0], opt = __tmp[1], lisn = __tmp[2];
var blobTo = function blobTo(to, blob) {
if (to == "arrayBuffer" && blob.arrayBuffer) {
var ret = blob.arrayBuffer(); // Fuck TM
if (ret) return ret;
}
return new Promise(function(resolve, reject) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
if (!event) return;
if (to == "base64") resolve(event.target.result);
else resolve(event.target.result);
};
if (to == "arrayBuffer") fileReader.readAsArrayBuffer(blob);
else if (to == "base64") fileReader.readAsDataURL(blob); // "data:*/*;base64,......"
else if (to == "text") fileReader.readAsText(blob, "utf-8");
else reject(new Error("unknown to"));
});
};
return new Promise(function(resolve, reject) {
// https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest
var gmopt = _objectSpread$2({
url: url.toString(),
data: opt === null || opt === void 0 ? void 0 : opt.body,
responseType: "blob",
headers: opt === null || opt === void 0 ? void 0 : opt.headers,
method: (opt === null || opt === void 0 ? void 0 : opt.method) || "GET"
}, lisn ? {
onprogress: function(prog) {
if (prog.loaded != prog.total && prog.total != 0) lisn.dispatchEvent(new CustomEvent("progress", {
detail: [
prog.loaded,
prog.total
]
}));
}
} : {}, {
onload: function(resp) {
if (resp.status / 100 >= 4) {
reject(new Error("Server Error: " + resp.status));
return;
}
var blob = resp.response;
var ref = resp;
ref.blob = function() {
return Promise.resolve(blob);
};
ref.arrayBuffer = function() {
return blobTo("arrayBuffer", blob);
};
ref.text = function() {
return blobTo("text", blob);
};
ref.json = _asyncToGenerator$b(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.t0 = JSON;
_ctx.next = 3;
return blobTo("text", blob);
case 3:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", _ctx.t0.parse.call(_ctx.t0, _ctx.t1));
case 5:
case "end":
return _ctx.stop();
}
}, _callee);
}));
resolve(resp);
},
ontimeout: function() {
return reject(new Error("fetch timeout"));
},
onerror: function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
reject(new Error("fetch error"));
},
onabort: function() {
return reject(new Error("fetch abort"));
}
});
xmlhttprequest(gmopt);
});
};
if (window["pagemode"]) GM_fetch = fetch;
var makePoolable = function(fun, getPoolSize) {
var pending = 0;
var poolFree = [];
return _asyncToGenerator$b(regeneratorRuntime$1.mark(function _callee() {
var _len, args, _key, prom, _args = arguments;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
for(_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = _args[_key];
}
case 1:
if (!(pending >= getPoolSize())) {
_ctx.next = 6;
break;
}
_ctx.next = 4;
return new Promise(function(_) {
return poolFree.push(_);
});
case 4:
_ctx.next = 1;
break;
case 6:
pending++;
prom = fun.apply(void 0, _toConsumableArray$6(args));
prom.then(function() {
pending--;
poolFree.forEach(function(_) {
return _();
});
poolFree.length = 0;
});
return _ctx.abrupt("return", prom);
case 10:
case "end":
return _ctx.stop();
}
}, _callee);
}));
};
var csettings$3 = localLoad("settingsv2", {});
settings.subscribe(function(s) {
csettings$3 = s;
});
makePoolable(GM_fetch, function() {
return csettings$3.conc;
});
function _arrayLikeToArray$8(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles$5(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles$5(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$8(arr);
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function(resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
var wrappedAwait = value instanceof _AwaitValue;
Promise.resolve(wrappedAwait ? value.wrapped : value).then(function(arg) {
if (wrappedAwait) {
resume("next", arg);
return;
}
settle(result.done ? "return" : "normal", arg);
}, function(err) {
resume("throw", err);
});
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch(type){
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function() {
return this;
};
}
AsyncGenerator.prototype.next = function(arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function(arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function(arg) {
return this._invoke("return", arg);
};
function asyncGeneratorStep$a(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$a(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$a(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$a(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _awaitAsyncGenerator(value) {
return new _AwaitValue(value);
}
function _AwaitValue(value) {
this.wrapped = value;
}
function _classCallCheck$4(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _iterableToArray$5(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit$5(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$5() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread$5() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray$5(arr, i) {
return _arrayWithHoles$5(arr) || _iterableToArrayLimit$5(arr, i) || _unsupportedIterableToArray$8(arr, i) || _nonIterableRest$5();
}
function _toConsumableArray$5(arr) {
return _arrayWithoutHoles$5(arr) || _iterableToArray$5(arr) || _unsupportedIterableToArray$8(arr) || _nonIterableSpread$5();
}
function _unsupportedIterableToArray$8(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$8(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$8(o, minLen);
}
function _wrapAsyncGenerator(fn) {
return function() {
return new AsyncGenerator(fn.apply(this, arguments));
};
}
var _class;
var port;
var gid = 0;
var bridge = function(name, f) {
return function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var id = gid++;
var prom = new Promise(function(_) {
port.postMessage({
id: id,
name: name,
args: args
});
});
return prom;
};
};
// eslint-disable-next-line @typescript-eslint/ban-types
var Bridged = function(ctor) {
var keys = Object.getOwnPropertyNames(ctor).filter(function(k) {
return typeof ctor[k] == "function";
});
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var k1 = _step.value;
ctor[k1] = bridge(k1, ctor[k1]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
function supportedAltDomain(s) {
return false;
}
var Platform = _class = Bridged((_class = /*#__PURE__*/ function() {
function Platform() {
_classCallCheck$4(this, Platform);
}
Platform.openInTab = function openInTab(src, opts) {
return _asyncToGenerator$a(regeneratorRuntime$1.mark(function _callee() {
var obj, i;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
{
_ctx.next = 2;
break;
}
case 2:
obj = browser;
{
_ctx.next = 11;
break;
}
case 8:
_ctx.t0 = _ctx.sent.index;
i = _ctx.t0 + 1;
case 10:
return _ctx.abrupt("return", obj.tabs.create({
active: opts.active,
url: src,
index: i
}));
case 11:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
return Platform;
}()) || _class) || _class;
function getHeaders(s) {
return _getHeaders.apply(this, arguments);
}
function _getHeaders() {
_getHeaders = _asyncToGenerator$a(regeneratorRuntime$1.mark(function _callee(s) {
var res;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
{
_ctx.next = 6;
break;
}
case 4:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", (0, _ctx.t0)(_ctx.t1));
case 6:
_ctx.next = 8;
return fetch(s, {
method: "HEAD"
});
case 8:
res = _ctx.sent;
return _ctx.abrupt("return", _toConsumableArray$5(res.headers.entries()).reduce(function(a, b) {
return a[b[0]] = b[1], a;
}, {}));
case 10:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return _getHeaders.apply(this, arguments);
}
function ifetch() {
return _ifetch.apply(this, arguments);
}
function _ifetch() {
_ifetch = _asyncToGenerator$a(regeneratorRuntime$1.mark(function _callee() {
var _len, _tmp, _key, __tmp, url, opt, lisn, _args = arguments;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
for(_len = _args.length, _tmp = new Array(_len), _key = 0; _key < _len; _key++){
_tmp[_key] = _args[_key];
}
__tmp = _slicedToArray$5(_tmp, 3), url = __tmp[0], opt = __tmp[1], lisn = __tmp[2];
return _ctx.abrupt("return", fetch(url, opt));
case 4:
return _ctx.abrupt("return", GM_fetch(url, opt, lisn));
case 5:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return _ifetch.apply(this, arguments);
}
// most pngs are encoded with 65k idat chunks
function streamRemote(url) {
return _streamRemote.apply(this, arguments);
}
function _streamRemote() {
_streamRemote = _wrapAsyncGenerator(regeneratorRuntime$1.mark(function _callee(url) {
var chunkSize, fetchRestOnNonCanceled, res, reader, stream, buff, e, headers, size, ptr, fetchSize, res1, obj, len, val, e1, _args = arguments;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
chunkSize = _args.length > 1 && _args[1] !== void 0 ? _args[1] : 72 * 1024, fetchRestOnNonCanceled = _args.length > 2 && _args[2] !== void 0 ? _args[2] : true;
_ctx.next = 4;
return _awaitAsyncGenerator(fetch(url));
case 4:
res = _ctx.sent;
reader = res.body;
stream = reader === null || reader === void 0 ? void 0 : reader.getReader();
case 7:
if (stream === null || stream === void 0 ? void 0 : stream.closed) {
_ctx.next = 23;
break;
}
_ctx.next = 10;
return _awaitAsyncGenerator(stream === null || stream === void 0 ? void 0 : stream.read());
case 10:
buff = _ctx.sent;
if (!(buff === null || buff === void 0 ? void 0 : buff.done)) {
_ctx.next = 13;
break;
}
return _ctx.abrupt("break", 23);
case 13:
if (!(buff === null || buff === void 0 ? void 0 : buff.value)) {
_ctx.next = 21;
break;
}
_ctx.next = 16;
return buff.value;
case 16:
e = _ctx.sent;
if (!e) {
_ctx.next = 21;
break;
}
stream === null || stream === void 0 ? void 0 : stream.cancel();
reader === null || reader === void 0 ? void 0 : reader.cancel();
return _ctx.abrupt("break", 23);
case 21:
_ctx.next = 7;
break;
case 23:
stream === null || stream === void 0 ? void 0 : stream.releaseLock();
return _ctx.abrupt("return");
case 25:
_ctx.next = 27;
return _awaitAsyncGenerator(getHeaders(url));
case 27:
headers = _ctx.sent;
size = +headers["content-length"];
ptr = 0;
fetchSize = chunkSize;
case 31:
if (!(ptr != size)) {
_ctx.next = 54;
break;
}
_ctx.next = 34;
return _awaitAsyncGenerator(ifetch(url, {
headers: {
range: "bytes=".concat(ptr, "-").concat(ptr + fetchSize - 1)
}
}));
case 34:
res1 = _ctx.sent;
obj = headerStringToObject(res1.responseHeaders);
if ("content-length" in obj) {
_ctx.next = 39;
break;
}
console.warn("no content lenght???", url);
return _ctx.abrupt("break", 54);
case 39:
len = +obj["content-length"];
ptr += len;
if (fetchRestOnNonCanceled) fetchSize = size;
_ctx.t0 = Buffer;
_ctx.next = 45;
return _awaitAsyncGenerator(res1.arrayBuffer());
case 45:
_ctx.t1 = _ctx.sent;
val = _ctx.t0.from.call(_ctx.t0, _ctx.t1);
_ctx.next = 49;
return val;
case 49:
e1 = _ctx.sent;
if (!e1) {
_ctx.next = 52;
break;
}
return _ctx.abrupt("break", 54);
case 52:
_ctx.next = 31;
break;
case 54:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return _streamRemote.apply(this, arguments);
}
function _arrayLikeToArray$7(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles$4(arr) {
if (Array.isArray(arr)) return arr;
}
function asyncGeneratorStep$9(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$9(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$9(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$9(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArrayLimit$4(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$4() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray$4(arr, i) {
return _arrayWithHoles$4(arr) || _iterableToArrayLimit$4(arr, i) || _unsupportedIterableToArray$7(arr, i) || _nonIterableRest$4();
}
function _unsupportedIterableToArray$7(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$7(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$7(o, minLen);
}
function parseForm(data) {
var form = new FormData();
Object.entries(data).filter(function(param) {
var _param = _slicedToArray$4(param, 2); _param[0]; var value = _param[1];
return value !== null;
}).map(function(param) {
var _param = _slicedToArray$4(param, 2), key = _param[0], value = _param[1];
return form.append(key, value);
});
return form;
}
var lolisafe = function(domain) {
var serving = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : domain;
return {
domain: domain,
serving: serving,
uploadFile: function uploadFile(f) {
return _asyncToGenerator$9(regeneratorRuntime$1.mark(function _callee() {
var resp, res;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return ifetch("https://".concat(domain, "/api/upload"), {
headers: {
accept: "application/json"
},
"body": parseForm({
reqtype: "fileupload",
"files[]": new File([
f
], "f.pee")
}),
"method": "POST"
});
case 2:
resp = _ctx.sent;
_ctx.next = 5;
return resp.json();
case 5:
res = _ctx.sent;
return _ctx.abrupt("return", res.files.map(function(e) {
return e.url;
})[0]);
case 7:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
}
};
};
var catbox = function(domain, serving) {
return {
domain: domain,
serving: serving,
uploadFile: function uploadFile(inj) {
return _asyncToGenerator$9(regeneratorRuntime$1.mark(function _callee() {
var resp;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return ifetch("https://".concat(domain, "/user/api.php"), {
method: "POST",
body: parseForm({
reqtype: "fileupload",
fileToUpload: inj
})
});
case 2:
resp = _ctx.sent;
return _ctx.abrupt("return", resp.text());
case 4:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
}
};
};
var filehosts = [
catbox("catbox.moe", "files.catbox.moe"),
lolisafe("zz.ht", "z.zz.fo"),
lolisafe("imouto.kawaii.su"),
lolisafe("take-me-to.space"),
];
const defaultMessages = 'End-Of-Stream';
/**
* Thrown on read operation of the end of file or stream has been reached
*/
class EndOfStreamError extends Error {
constructor() {
super(defaultMessages);
}
}
/**
* Core tokenizer
*/
class AbstractTokenizer {
constructor(fileInfo) {
/**
* Tokenizer-stream position
*/
this.position = 0;
this.numBuffer = new Uint8Array(8);
this.fileInfo = fileInfo ? fileInfo : {};
}
/**
* Read a token from the tokenizer-stream
* @param token - The token to read
* @param position - If provided, the desired position in the tokenizer-stream
* @returns Promise with token data
*/
async readToken(token, position = this.position) {
const uint8Array = Buffer$1.alloc(token.len);
const len = await this.readBuffer(uint8Array, { position });
if (len < token.len)
throw new EndOfStreamError();
return token.get(uint8Array, 0);
}
/**
* Peek a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
* @returns Promise with token data
*/
async peekToken(token, position = this.position) {
const uint8Array = Buffer$1.alloc(token.len);
const len = await this.peekBuffer(uint8Array, { position });
if (len < token.len)
throw new EndOfStreamError();
return token.get(uint8Array, 0);
}
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
async readNumber(token) {
const len = await this.readBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new EndOfStreamError();
return token.get(this.numBuffer, 0);
}
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
async peekNumber(token) {
const len = await this.peekBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new EndOfStreamError();
return token.get(this.numBuffer, 0);
}
/**
* Ignore number of bytes, advances the pointer in under tokenizer-stream.
* @param length - Number of bytes to ignore
* @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available
*/
async ignore(length) {
if (this.fileInfo.size !== undefined) {
const bytesLeft = this.fileInfo.size - this.position;
if (length > bytesLeft) {
this.position += bytesLeft;
return bytesLeft;
}
}
this.position += length;
return length;
}
async close() {
// empty
}
normalizeOptions(uint8Array, options) {
if (options && options.position !== undefined && options.position < this.position) {
throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
}
if (options) {
return {
mayBeLess: options.mayBeLess === true,
offset: options.offset ? options.offset : 0,
length: options.length ? options.length : (uint8Array.length - (options.offset ? options.offset : 0)),
position: options.position ? options.position : this.position
};
}
return {
mayBeLess: false,
offset: 0,
length: uint8Array.length,
position: this.position
};
}
}
class BufferTokenizer extends AbstractTokenizer {
/**
* Construct BufferTokenizer
* @param uint8Array - Uint8Array to tokenize
* @param fileInfo - Pass additional file information to the tokenizer
*/
constructor(uint8Array, fileInfo) {
super(fileInfo);
this.uint8Array = uint8Array;
this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length;
}
/**
* Read buffer from tokenizer
* @param uint8Array - Uint8Array to tokenize
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
async readBuffer(uint8Array, options) {
if (options && options.position) {
if (options.position < this.position) {
throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
}
this.position = options.position;
}
const bytesRead = await this.peekBuffer(uint8Array, options);
this.position += bytesRead;
return bytesRead;
}
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);
if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) {
throw new EndOfStreamError();
}
else {
uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset);
return bytes2read;
}
}
async close() {
// empty
}
}
/**
* Construct ReadStreamTokenizer from given Buffer.
* @param uint8Array - Uint8Array to tokenize
* @param fileInfo - Pass additional file information to the tokenizer
* @returns BufferTokenizer
*/
function fromBuffer(uint8Array, fileInfo) {
return new BufferTokenizer(uint8Array, fileInfo);
}
// Primitive types
function dv(array) {
return new DataView(array.buffer, array.byteOffset);
}
/**
* 8-bit unsigned integer
*/
const UINT8 = {
len: 1,
get(array, offset) {
return dv(array).getUint8(offset);
},
put(array, offset, value) {
dv(array).setUint8(offset, value);
return offset + 1;
}
};
/**
* 16-bit unsigned integer, Little Endian byte order
*/
const UINT16_LE = {
len: 2,
get(array, offset) {
return dv(array).getUint16(offset, true);
},
put(array, offset, value) {
dv(array).setUint16(offset, value, true);
return offset + 2;
}
};
/**
* 16-bit unsigned integer, Big Endian byte order
*/
const UINT16_BE = {
len: 2,
get(array, offset) {
return dv(array).getUint16(offset);
},
put(array, offset, value) {
dv(array).setUint16(offset, value);
return offset + 2;
}
};
/**
* 32-bit unsigned integer, Little Endian byte order
*/
const UINT32_LE = {
len: 4,
get(array, offset) {
return dv(array).getUint32(offset, true);
},
put(array, offset, value) {
dv(array).setUint32(offset, value, true);
return offset + 4;
}
};
/**
* 32-bit unsigned integer, Big Endian byte order
*/
const UINT32_BE = {
len: 4,
get(array, offset) {
return dv(array).getUint32(offset);
},
put(array, offset, value) {
dv(array).setUint32(offset, value);
return offset + 4;
}
};
/**
* 32-bit signed integer, Big Endian byte order
*/
const INT32_BE = {
len: 4,
get(array, offset) {
return dv(array).getInt32(offset);
},
put(array, offset, value) {
dv(array).setInt32(offset, value);
return offset + 4;
}
};
/**
* 64-bit unsigned integer, Little Endian byte order
*/
const UINT64_LE = {
len: 8,
get(array, offset) {
return dv(array).getBigUint64(offset, true);
},
put(array, offset, value) {
dv(array).setBigUint64(offset, value, true);
return offset + 8;
}
};
/**
* Consume a fixed number of bytes from the stream and return a string with a specified encoding.
*/
class StringType {
constructor(len, encoding) {
this.len = len;
this.encoding = encoding;
}
get(uint8Array, offset) {
return Buffer$1.from(uint8Array).toString(this.encoding, offset, offset + this.len);
}
}
function stringToBytes(string) {
return [...string].map(character => character.charCodeAt(0));
}
/**
Checks whether the TAR checksum is valid.
@param {Buffer} buffer - The TAR header `[offset ... offset + 512]`.
@param {number} offset - TAR header offset.
@returns {boolean} `true` if the TAR checksum is valid, otherwise `false`.
*/
function tarHeaderChecksumMatches(buffer, offset = 0) {
const readSum = Number.parseInt(buffer.toString('utf8', 148, 154).replace(/\0.*$/, '').trim(), 8); // Read sum in header
if (Number.isNaN(readSum)) {
return false;
}
let sum = 8 * 0x20; // Initialize signed bit sum
for (let i = offset; i < offset + 148; i++) {
sum += buffer[i];
}
for (let i = offset + 156; i < offset + 512; i++) {
sum += buffer[i];
}
return readSum === sum;
}
/**
ID3 UINT32 sync-safe tokenizer token.
28 bits (representing up to 256MB) integer, the msb is 0 to avoid "false syncsignals".
*/
const uint32SyncSafeToken = {
get: (buffer, offset) => (buffer[offset + 3] & 0x7F) | ((buffer[offset + 2]) << 7) | ((buffer[offset + 1]) << 14) | ((buffer[offset]) << 21),
len: 4,
};
const minimumBytes = 4100; // A fair amount of file-types are detectable within this range.
async function fileTypeFromBuffer(input) {
if (!(input instanceof Uint8Array || input instanceof ArrayBuffer)) {
throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof input}\``);
}
const buffer = input instanceof Uint8Array ? input : new Uint8Array(input);
if (!(buffer && buffer.length > 1)) {
return;
}
return fileTypeFromTokenizer(fromBuffer(buffer));
}
function _check(buffer, headers, options) {
options = {
offset: 0,
...options,
};
for (const [index, header] of headers.entries()) {
// If a bitmask is set
if (options.mask) {
// If header doesn't equal `buf` with bits masked off
if (header !== (options.mask[index] & buffer[index + options.offset])) {
return false;
}
} else if (header !== buffer[index + options.offset]) {
return false;
}
}
return true;
}
async function fileTypeFromTokenizer(tokenizer) {
try {
return new FileTypeParser().parse(tokenizer);
} catch (error) {
if (!(error instanceof EndOfStreamError)) {
throw error;
}
}
}
class FileTypeParser {
check(header, options) {
return _check(this.buffer, header, options);
}
checkString(header, options) {
return this.check(stringToBytes(header), options);
}
async parse(tokenizer) {
this.buffer = Buffer$1.alloc(minimumBytes);
// Keep reading until EOF if the file size is unknown.
if (tokenizer.fileInfo.size === undefined) {
tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;
}
// Keep reading until EOF if the file size is unknown.
if (tokenizer.fileInfo.size === undefined) {
tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;
}
this.tokenizer = tokenizer;
await tokenizer.peekBuffer(this.buffer, {length: 12, mayBeLess: true});
// -- 2-byte signatures --
if (this.check([0x42, 0x4D])) {
return {
ext: 'bmp',
mime: 'image/bmp',
};
}
if (this.check([0x0B, 0x77])) {
return {
ext: 'ac3',
mime: 'audio/vnd.dolby.dd-raw',
};
}
if (this.check([0x78, 0x01])) {
return {
ext: 'dmg',
mime: 'application/x-apple-diskimage',
};
}
if (this.check([0x4D, 0x5A])) {
return {
ext: 'exe',
mime: 'application/x-msdownload',
};
}
if (this.check([0x25, 0x21])) {
await tokenizer.peekBuffer(this.buffer, {length: 24, mayBeLess: true});
if (
this.checkString('PS-Adobe-', {offset: 2})
&& this.checkString(' EPSF-', {offset: 14})
) {
return {
ext: 'eps',
mime: 'application/eps',
};
}
return {
ext: 'ps',
mime: 'application/postscript',
};
}
if (
this.check([0x1F, 0xA0])
|| this.check([0x1F, 0x9D])
) {
return {
ext: 'Z',
mime: 'application/x-compress',
};
}
// -- 3-byte signatures --
if (this.check([0x47, 0x49, 0x46])) {
return {
ext: 'gif',
mime: 'image/gif',
};
}
if (this.check([0xFF, 0xD8, 0xFF])) {
return {
ext: 'jpg',
mime: 'image/jpeg',
};
}
if (this.check([0x49, 0x49, 0xBC])) {
return {
ext: 'jxr',
mime: 'image/vnd.ms-photo',
};
}
if (this.check([0x1F, 0x8B, 0x8])) {
return {
ext: 'gz',
mime: 'application/gzip',
};
}
if (this.check([0x42, 0x5A, 0x68])) {
return {
ext: 'bz2',
mime: 'application/x-bzip2',
};
}
if (this.checkString('ID3')) {
await tokenizer.ignore(6); // Skip ID3 header until the header size
const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken);
if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) {
// Guess file type based on ID3 header for backward compatibility
return {
ext: 'mp3',
mime: 'audio/mpeg',
};
}
await tokenizer.ignore(id3HeaderLength);
return fileTypeFromTokenizer(tokenizer); // Skip ID3 header, recursion
}
// Musepack, SV7
if (this.checkString('MP+')) {
return {
ext: 'mpc',
mime: 'audio/x-musepack',
};
}
if (
(this.buffer[0] === 0x43 || this.buffer[0] === 0x46)
&& this.check([0x57, 0x53], {offset: 1})
) {
return {
ext: 'swf',
mime: 'application/x-shockwave-flash',
};
}
// -- 4-byte signatures --
if (this.checkString('FLIF')) {
return {
ext: 'flif',
mime: 'image/flif',
};
}
if (this.checkString('8BPS')) {
return {
ext: 'psd',
mime: 'image/vnd.adobe.photoshop',
};
}
if (this.checkString('WEBP', {offset: 8})) {
return {
ext: 'webp',
mime: 'image/webp',
};
}
// Musepack, SV8
if (this.checkString('MPCK')) {
return {
ext: 'mpc',
mime: 'audio/x-musepack',
};
}
if (this.checkString('FORM')) {
return {
ext: 'aif',
mime: 'audio/aiff',
};
}
if (this.checkString('icns', {offset: 0})) {
return {
ext: 'icns',
mime: 'image/icns',
};
}
// Zip-based file formats
// Need to be before the `zip` check
if (this.check([0x50, 0x4B, 0x3, 0x4])) { // Local file header signature
try {
while (tokenizer.position + 30 < tokenizer.fileInfo.size) {
await tokenizer.readBuffer(this.buffer, {length: 30});
// https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
const zipHeader = {
compressedSize: this.buffer.readUInt32LE(18),
uncompressedSize: this.buffer.readUInt32LE(22),
filenameLength: this.buffer.readUInt16LE(26),
extraFieldLength: this.buffer.readUInt16LE(28),
};
zipHeader.filename = await tokenizer.readToken(new StringType(zipHeader.filenameLength, 'utf-8'));
await tokenizer.ignore(zipHeader.extraFieldLength);
// Assumes signed `.xpi` from addons.mozilla.org
if (zipHeader.filename === 'META-INF/mozilla.rsa') {
return {
ext: 'xpi',
mime: 'application/x-xpinstall',
};
}
if (zipHeader.filename.endsWith('.rels') || zipHeader.filename.endsWith('.xml')) {
const type = zipHeader.filename.split('/')[0];
switch (type) {
case '_rels':
break;
case 'word':
return {
ext: 'docx',
mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
};
case 'ppt':
return {
ext: 'pptx',
mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
};
case 'xl':
return {
ext: 'xlsx',
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
default:
break;
}
}
if (zipHeader.filename.startsWith('xl/')) {
return {
ext: 'xlsx',
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
}
if (zipHeader.filename.startsWith('3D/') && zipHeader.filename.endsWith('.model')) {
return {
ext: '3mf',
mime: 'model/3mf',
};
}
// The docx, xlsx and pptx file types extend the Office Open XML file format:
// https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
// We look for:
// - one entry named '[Content_Types].xml' or '_rels/.rels',
// - one entry indicating specific type of file.
// MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.
if (zipHeader.filename === 'mimetype' && zipHeader.compressedSize === zipHeader.uncompressedSize) {
const mimeType = await tokenizer.readToken(new StringType(zipHeader.compressedSize, 'utf-8'));
switch (mimeType) {
case 'application/epub+zip':
return {
ext: 'epub',
mime: 'application/epub+zip',
};
case 'application/vnd.oasis.opendocument.text':
return {
ext: 'odt',
mime: 'application/vnd.oasis.opendocument.text',
};
case 'application/vnd.oasis.opendocument.spreadsheet':
return {
ext: 'ods',
mime: 'application/vnd.oasis.opendocument.spreadsheet',
};
case 'application/vnd.oasis.opendocument.presentation':
return {
ext: 'odp',
mime: 'application/vnd.oasis.opendocument.presentation',
};
default:
}
}
// Try to find next header manually when current one is corrupted
if (zipHeader.compressedSize === 0) {
let nextHeaderIndex = -1;
while (nextHeaderIndex < 0 && (tokenizer.position < tokenizer.fileInfo.size)) {
await tokenizer.peekBuffer(this.buffer, {mayBeLess: true});
nextHeaderIndex = this.buffer.indexOf('504B0304', 0, 'hex');
// Move position to the next header if found, skip the whole buffer otherwise
await tokenizer.ignore(nextHeaderIndex >= 0 ? nextHeaderIndex : this.buffer.length);
}
} else {
await tokenizer.ignore(zipHeader.compressedSize);
}
}
} catch (error) {
if (!(error instanceof EndOfStreamError)) {
throw error;
}
}
return {
ext: 'zip',
mime: 'application/zip',
};
}
if (this.checkString('OggS')) {
// This is an OGG container
await tokenizer.ignore(28);
const type = Buffer$1.alloc(8);
await tokenizer.readBuffer(type);
// Needs to be before `ogg` check
if (_check(type, [0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64])) {
return {
ext: 'opus',
mime: 'audio/opus',
};
}
// If ' theora' in header.
if (_check(type, [0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61])) {
return {
ext: 'ogv',
mime: 'video/ogg',
};
}
// If '\x01video' in header.
if (_check(type, [0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00])) {
return {
ext: 'ogm',
mime: 'video/ogg',
};
}
// If ' FLAC' in header https://xiph.org/flac/faq.html
if (_check(type, [0x7F, 0x46, 0x4C, 0x41, 0x43])) {
return {
ext: 'oga',
mime: 'audio/ogg',
};
}
// 'Speex ' in header https://en.wikipedia.org/wiki/Speex
if (_check(type, [0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20])) {
return {
ext: 'spx',
mime: 'audio/ogg',
};
}
// If '\x01vorbis' in header
if (_check(type, [0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73])) {
return {
ext: 'ogg',
mime: 'audio/ogg',
};
}
// Default OGG container https://www.iana.org/assignments/media-types/application/ogg
return {
ext: 'ogx',
mime: 'application/ogg',
};
}
if (
this.check([0x50, 0x4B])
&& (this.buffer[2] === 0x3 || this.buffer[2] === 0x5 || this.buffer[2] === 0x7)
&& (this.buffer[3] === 0x4 || this.buffer[3] === 0x6 || this.buffer[3] === 0x8)
) {
return {
ext: 'zip',
mime: 'application/zip',
};
}
//
// File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
// It's not required to be first, but it's recommended to be. Almost all ISO base media files start with `ftyp` box.
// `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.
// Here we check for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).
if (
this.checkString('ftyp', {offset: 4})
&& (this.buffer[8] & 0x60) !== 0x00 // Brand major, first character ASCII?
) {
// They all can have MIME `video/mp4` except `application/mp4` special-case which is hard to detect.
// For some cases, we're specific, everything else falls to `video/mp4` with `mp4` extension.
const brandMajor = this.buffer.toString('binary', 8, 12).replace('\0', ' ').trim();
switch (brandMajor) {
case 'avif':
case 'avis':
return {ext: 'avif', mime: 'image/avif'};
case 'mif1':
return {ext: 'heic', mime: 'image/heif'};
case 'msf1':
return {ext: 'heic', mime: 'image/heif-sequence'};
case 'heic':
case 'heix':
return {ext: 'heic', mime: 'image/heic'};
case 'hevc':
case 'hevx':
return {ext: 'heic', mime: 'image/heic-sequence'};
case 'qt':
return {ext: 'mov', mime: 'video/quicktime'};
case 'M4V':
case 'M4VH':
case 'M4VP':
return {ext: 'm4v', mime: 'video/x-m4v'};
case 'M4P':
return {ext: 'm4p', mime: 'video/mp4'};
case 'M4B':
return {ext: 'm4b', mime: 'audio/mp4'};
case 'M4A':
return {ext: 'm4a', mime: 'audio/x-m4a'};
case 'F4V':
return {ext: 'f4v', mime: 'video/mp4'};
case 'F4P':
return {ext: 'f4p', mime: 'video/mp4'};
case 'F4A':
return {ext: 'f4a', mime: 'audio/mp4'};
case 'F4B':
return {ext: 'f4b', mime: 'audio/mp4'};
case 'crx':
return {ext: 'cr3', mime: 'image/x-canon-cr3'};
default:
if (brandMajor.startsWith('3g')) {
if (brandMajor.startsWith('3g2')) {
return {ext: '3g2', mime: 'video/3gpp2'};
}
return {ext: '3gp', mime: 'video/3gpp'};
}
return {ext: 'mp4', mime: 'video/mp4'};
}
}
if (this.checkString('MThd')) {
return {
ext: 'mid',
mime: 'audio/midi',
};
}
if (
this.checkString('wOFF')
&& (
this.check([0x00, 0x01, 0x00, 0x00], {offset: 4})
|| this.checkString('OTTO', {offset: 4})
)
) {
return {
ext: 'woff',
mime: 'font/woff',
};
}
if (
this.checkString('wOF2')
&& (
this.check([0x00, 0x01, 0x00, 0x00], {offset: 4})
|| this.checkString('OTTO', {offset: 4})
)
) {
return {
ext: 'woff2',
mime: 'font/woff2',
};
}
if (this.check([0xD4, 0xC3, 0xB2, 0xA1]) || this.check([0xA1, 0xB2, 0xC3, 0xD4])) {
return {
ext: 'pcap',
mime: 'application/vnd.tcpdump.pcap',
};
}
// Sony DSD Stream File (DSF)
if (this.checkString('DSD ')) {
return {
ext: 'dsf',
mime: 'audio/x-dsf', // Non-standard
};
}
if (this.checkString('LZIP')) {
return {
ext: 'lz',
mime: 'application/x-lzip',
};
}
if (this.checkString('fLaC')) {
return {
ext: 'flac',
mime: 'audio/x-flac',
};
}
if (this.check([0x42, 0x50, 0x47, 0xFB])) {
return {
ext: 'bpg',
mime: 'image/bpg',
};
}
if (this.checkString('wvpk')) {
return {
ext: 'wv',
mime: 'audio/wavpack',
};
}
if (this.checkString('%PDF')) {
await tokenizer.ignore(1350);
const maxBufferSize = 10 * 1024 * 1024;
const buffer = Buffer$1.alloc(Math.min(maxBufferSize, tokenizer.fileInfo.size));
await tokenizer.readBuffer(buffer, {mayBeLess: true});
// Check if this is an Adobe Illustrator file
if (buffer.includes(Buffer$1.from('AIPrivateData'))) {
return {
ext: 'ai',
mime: 'application/postscript',
};
}
// Assume this is just a normal PDF
return {
ext: 'pdf',
mime: 'application/pdf',
};
}
if (this.check([0x00, 0x61, 0x73, 0x6D])) {
return {
ext: 'wasm',
mime: 'application/wasm',
};
}
// TIFF, little-endian type
if (this.check([0x49, 0x49])) {
const fileType = await this.readTiffHeader(false);
if (fileType) {
return fileType;
}
}
// TIFF, big-endian type
if (this.check([0x4D, 0x4D])) {
const fileType = await this.readTiffHeader(true);
if (fileType) {
return fileType;
}
}
if (this.checkString('MAC ')) {
return {
ext: 'ape',
mime: 'audio/ape',
};
}
// https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
if (this.check([0x1A, 0x45, 0xDF, 0xA3])) { // Root element: EBML
async function readField() {
const msb = await tokenizer.peekNumber(UINT8);
let mask = 0x80;
let ic = 0; // 0 = A, 1 = B, 2 = C, 3
// = D
while ((msb & mask) === 0) {
++ic;
mask >>= 1;
}
const id = Buffer$1.alloc(ic + 1);
await tokenizer.readBuffer(id);
return id;
}
async function readElement() {
const id = await readField();
const lengthField = await readField();
lengthField[0] ^= 0x80 >> (lengthField.length - 1);
const nrLength = Math.min(6, lengthField.length); // JavaScript can max read 6 bytes integer
return {
id: id.readUIntBE(0, id.length),
len: lengthField.readUIntBE(lengthField.length - nrLength, nrLength),
};
}
async function readChildren(level, children) {
while (children > 0) {
const element = await readElement();
if (element.id === 0x42_82) {
const rawValue = await tokenizer.readToken(new StringType(element.len, 'utf-8'));
return rawValue.replace(/\00.*$/g, ''); // Return DocType
}
await tokenizer.ignore(element.len); // ignore payload
--children;
}
}
const re = await readElement();
const docType = await readChildren(1, re.len);
switch (docType) {
case 'webm':
return {
ext: 'webm',
mime: 'video/webm',
};
case 'matroska':
return {
ext: 'mkv',
mime: 'video/x-matroska',
};
default:
return;
}
}
// RIFF file format which might be AVI, WAV, QCP, etc
if (this.check([0x52, 0x49, 0x46, 0x46])) {
if (this.check([0x41, 0x56, 0x49], {offset: 8})) {
return {
ext: 'avi',
mime: 'video/vnd.avi',
};
}
if (this.check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {
return {
ext: 'wav',
mime: 'audio/vnd.wave',
};
}
// QLCM, QCP file
if (this.check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {
return {
ext: 'qcp',
mime: 'audio/qcelp',
};
}
}
if (this.checkString('SQLi')) {
return {
ext: 'sqlite',
mime: 'application/x-sqlite3',
};
}
if (this.check([0x4E, 0x45, 0x53, 0x1A])) {
return {
ext: 'nes',
mime: 'application/x-nintendo-nes-rom',
};
}
if (this.checkString('Cr24')) {
return {
ext: 'crx',
mime: 'application/x-google-chrome-extension',
};
}
if (
this.checkString('MSCF')
|| this.checkString('ISc(')
) {
return {
ext: 'cab',
mime: 'application/vnd.ms-cab-compressed',
};
}
if (this.check([0xED, 0xAB, 0xEE, 0xDB])) {
return {
ext: 'rpm',
mime: 'application/x-rpm',
};
}
if (this.check([0xC5, 0xD0, 0xD3, 0xC6])) {
return {
ext: 'eps',
mime: 'application/eps',
};
}
if (this.check([0x28, 0xB5, 0x2F, 0xFD])) {
return {
ext: 'zst',
mime: 'application/zstd',
};
}
if (this.check([0x7F, 0x45, 0x4C, 0x46])) {
return {
ext: 'elf',
mime: 'application/x-elf',
};
}
// -- 5-byte signatures --
if (this.check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
return {
ext: 'otf',
mime: 'font/otf',
};
}
if (this.checkString('#!AMR')) {
return {
ext: 'amr',
mime: 'audio/amr',
};
}
if (this.checkString('{\\rtf')) {
return {
ext: 'rtf',
mime: 'application/rtf',
};
}
if (this.check([0x46, 0x4C, 0x56, 0x01])) {
return {
ext: 'flv',
mime: 'video/x-flv',
};
}
if (this.checkString('IMPM')) {
return {
ext: 'it',
mime: 'audio/x-it',
};
}
if (
this.checkString('-lh0-', {offset: 2})
|| this.checkString('-lh1-', {offset: 2})
|| this.checkString('-lh2-', {offset: 2})
|| this.checkString('-lh3-', {offset: 2})
|| this.checkString('-lh4-', {offset: 2})
|| this.checkString('-lh5-', {offset: 2})
|| this.checkString('-lh6-', {offset: 2})
|| this.checkString('-lh7-', {offset: 2})
|| this.checkString('-lzs-', {offset: 2})
|| this.checkString('-lz4-', {offset: 2})
|| this.checkString('-lz5-', {offset: 2})
|| this.checkString('-lhd-', {offset: 2})
) {
return {
ext: 'lzh',
mime: 'application/x-lzh-compressed',
};
}
// MPEG program stream (PS or MPEG-PS)
if (this.check([0x00, 0x00, 0x01, 0xBA])) {
// MPEG-PS, MPEG-1 Part 1
if (this.check([0x21], {offset: 4, mask: [0xF1]})) {
return {
ext: 'mpg', // May also be .ps, .mpeg
mime: 'video/MP1S',
};
}
// MPEG-PS, MPEG-2 Part 1
if (this.check([0x44], {offset: 4, mask: [0xC4]})) {
return {
ext: 'mpg', // May also be .mpg, .m2p, .vob or .sub
mime: 'video/MP2P',
};
}
}
if (this.checkString('ITSF')) {
return {
ext: 'chm',
mime: 'application/vnd.ms-htmlhelp',
};
}
// -- 6-byte signatures --
if (this.check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
return {
ext: 'xz',
mime: 'application/x-xz',
};
}
if (this.checkString('<?xml ')) {
return {
ext: 'xml',
mime: 'application/xml',
};
}
if (this.check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
return {
ext: '7z',
mime: 'application/x-7z-compressed',
};
}
if (
this.check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7])
&& (this.buffer[6] === 0x0 || this.buffer[6] === 0x1)
) {
return {
ext: 'rar',
mime: 'application/x-rar-compressed',
};
}
if (this.checkString('solid ')) {
return {
ext: 'stl',
mime: 'model/stl',
};
}
// -- 7-byte signatures --
if (this.checkString('BLENDER')) {
return {
ext: 'blend',
mime: 'application/x-blender',
};
}
if (this.checkString('!<arch>')) {
await tokenizer.ignore(8);
const string = await tokenizer.readToken(new StringType(13, 'ascii'));
if (string === 'debian-binary') {
return {
ext: 'deb',
mime: 'application/x-deb',
};
}
return {
ext: 'ar',
mime: 'application/x-unix-archive',
};
}
// -- 8-byte signatures --
if (this.check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
// APNG format (https://wiki.mozilla.org/APNG_Specification)
// 1. Find the first IDAT (image data) chunk (49 44 41 54)
// 2. Check if there is an "acTL" chunk before the IDAT one (61 63 54 4C)
// Offset calculated as follows:
// - 8 bytes: PNG signature
// - 4 (length) + 4 (chunk type) + 13 (chunk data) + 4 (CRC): IHDR chunk
await tokenizer.ignore(8); // ignore PNG signature
async function readChunkHeader() {
return {
length: await tokenizer.readToken(INT32_BE),
type: await tokenizer.readToken(new StringType(4, 'binary')),
};
}
do {
const chunk = await readChunkHeader();
if (chunk.length < 0) {
return; // Invalid chunk length
}
switch (chunk.type) {
case 'IDAT':
return {
ext: 'png',
mime: 'image/png',
};
case 'acTL':
return {
ext: 'apng',
mime: 'image/apng',
};
default:
await tokenizer.ignore(chunk.length + 4); // Ignore chunk-data + CRC
}
} while (tokenizer.position + 8 < tokenizer.fileInfo.size);
return {
ext: 'png',
mime: 'image/png',
};
}
if (this.check([0x41, 0x52, 0x52, 0x4F, 0x57, 0x31, 0x00, 0x00])) {
return {
ext: 'arrow',
mime: 'application/x-apache-arrow',
};
}
if (this.check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {
return {
ext: 'glb',
mime: 'model/gltf-binary',
};
}
// `mov` format variants
if (
this.check([0x66, 0x72, 0x65, 0x65], {offset: 4}) // `free`
|| this.check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) // `mdat` MJPEG
|| this.check([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) // `moov`
|| this.check([0x77, 0x69, 0x64, 0x65], {offset: 4}) // `wide`
) {
return {
ext: 'mov',
mime: 'video/quicktime',
};
}
if (this.check([0xEF, 0xBB, 0xBF]) && this.checkString('<?xml', {offset: 3})) { // UTF-8-BOM
return {
ext: 'xml',
mime: 'application/xml',
};
}
// -- 9-byte signatures --
if (this.check([0x49, 0x49, 0x52, 0x4F, 0x08, 0x00, 0x00, 0x00, 0x18])) {
return {
ext: 'orf',
mime: 'image/x-olympus-orf',
};
}
if (this.checkString('gimp xcf ')) {
return {
ext: 'xcf',
mime: 'image/x-xcf',
};
}
// -- 12-byte signatures --
if (this.check([0x49, 0x49, 0x55, 0x00, 0x18, 0x00, 0x00, 0x00, 0x88, 0xE7, 0x74, 0xD8])) {
return {
ext: 'rw2',
mime: 'image/x-panasonic-rw2',
};
}
// ASF_Header_Object first 80 bytes
if (this.check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
async function readHeader() {
const guid = Buffer$1.alloc(16);
await tokenizer.readBuffer(guid);
return {
id: guid,
size: Number(await tokenizer.readToken(UINT64_LE)),
};
}
await tokenizer.ignore(30);
// Search for header should be in first 1KB of file.
while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
const header = await readHeader();
let payload = header.size - 24;
if (_check(header.id, [0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65])) {
// Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)
const typeId = Buffer$1.alloc(16);
payload -= await tokenizer.readBuffer(typeId);
if (_check(typeId, [0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {
// Found audio:
return {
ext: 'asf',
mime: 'audio/x-ms-asf',
};
}
if (_check(typeId, [0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {
// Found video:
return {
ext: 'asf',
mime: 'video/x-ms-asf',
};
}
break;
}
await tokenizer.ignore(payload);
}
// Default to ASF generic extension
return {
ext: 'asf',
mime: 'application/vnd.ms-asf',
};
}
if (this.check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
return {
ext: 'ktx',
mime: 'image/ktx',
};
}
if ((this.check([0x7E, 0x10, 0x04]) || this.check([0x7E, 0x18, 0x04])) && this.check([0x30, 0x4D, 0x49, 0x45], {offset: 4})) {
return {
ext: 'mie',
mime: 'application/x-mie',
};
}
if (this.check([0x27, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], {offset: 2})) {
return {
ext: 'shp',
mime: 'application/x-esri-shape',
};
}
if (this.check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
// JPEG-2000 family
await tokenizer.ignore(20);
const type = await tokenizer.readToken(new StringType(4, 'ascii'));
switch (type) {
case 'jp2 ':
return {
ext: 'jp2',
mime: 'image/jp2',
};
case 'jpx ':
return {
ext: 'jpx',
mime: 'image/jpx',
};
case 'jpm ':
return {
ext: 'jpm',
mime: 'image/jpm',
};
case 'mjp2':
return {
ext: 'mj2',
mime: 'image/mj2',
};
default:
return;
}
}
if (
this.check([0xFF, 0x0A])
|| this.check([0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A])
) {
return {
ext: 'jxl',
mime: 'image/jxl',
};
}
if (
this.check([0xFE, 0xFF, 0, 60, 0, 63, 0, 120, 0, 109, 0, 108]) // UTF-16-BOM-LE
|| this.check([0xFF, 0xFE, 60, 0, 63, 0, 120, 0, 109, 0, 108, 0]) // UTF-16-BOM-LE
) {
return {
ext: 'xml',
mime: 'application/xml',
};
}
// -- Unsafe signatures --
if (
this.check([0x0, 0x0, 0x1, 0xBA])
|| this.check([0x0, 0x0, 0x1, 0xB3])
) {
return {
ext: 'mpg',
mime: 'video/mpeg',
};
}
if (this.check([0x00, 0x01, 0x00, 0x00, 0x00])) {
return {
ext: 'ttf',
mime: 'font/ttf',
};
}
if (this.check([0x00, 0x00, 0x01, 0x00])) {
return {
ext: 'ico',
mime: 'image/x-icon',
};
}
if (this.check([0x00, 0x00, 0x02, 0x00])) {
return {
ext: 'cur',
mime: 'image/x-icon',
};
}
if (this.check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
// Detected Microsoft Compound File Binary File (MS-CFB) Format.
return {
ext: 'cfb',
mime: 'application/x-cfb',
};
}
// Increase sample size from 12 to 256.
await tokenizer.peekBuffer(this.buffer, {length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true});
// -- 15-byte signatures --
if (this.checkString('BEGIN:')) {
if (this.checkString('VCARD', {offset: 6})) {
return {
ext: 'vcf',
mime: 'text/vcard',
};
}
if (this.checkString('VCALENDAR', {offset: 6})) {
return {
ext: 'ics',
mime: 'text/calendar',
};
}
}
// `raf` is here just to keep all the raw image detectors together.
if (this.checkString('FUJIFILMCCD-RAW')) {
return {
ext: 'raf',
mime: 'image/x-fujifilm-raf',
};
}
if (this.checkString('Extended Module:')) {
return {
ext: 'xm',
mime: 'audio/x-xm',
};
}
if (this.checkString('Creative Voice File')) {
return {
ext: 'voc',
mime: 'audio/x-voc',
};
}
if (this.check([0x04, 0x00, 0x00, 0x00]) && this.buffer.length >= 16) { // Rough & quick check Pickle/ASAR
const jsonSize = this.buffer.readUInt32LE(12);
if (jsonSize > 12 && this.buffer.length >= jsonSize + 16) {
try {
const header = this.buffer.slice(16, jsonSize + 16).toString();
const json = JSON.parse(header);
// Check if Pickle is ASAR
if (json.files) { // Final check, assuring Pickle/ASAR format
return {
ext: 'asar',
mime: 'application/x-asar',
};
}
} catch {}
}
}
if (this.check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
return {
ext: 'mxf',
mime: 'application/mxf',
};
}
if (this.checkString('SCRM', {offset: 44})) {
return {
ext: 's3m',
mime: 'audio/x-s3m',
};
}
// Raw MPEG-2 transport stream (188-byte packets)
if (this.check([0x47]) && this.check([0x47], {offset: 188})) {
return {
ext: 'mts',
mime: 'video/mp2t',
};
}
// Blu-ray Disc Audio-Video (BDAV) MPEG-2 transport stream has 4-byte TP_extra_header before each 188-byte packet
if (this.check([0x47], {offset: 4}) && this.check([0x47], {offset: 196})) {
return {
ext: 'mts',
mime: 'video/mp2t',
};
}
if (this.check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {
return {
ext: 'mobi',
mime: 'application/x-mobipocket-ebook',
};
}
if (this.check([0x44, 0x49, 0x43, 0x4D], {offset: 128})) {
return {
ext: 'dcm',
mime: 'application/dicom',
};
}
if (this.check([0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46])) {
return {
ext: 'lnk',
mime: 'application/x.ms.shortcut', // Invented by us
};
}
if (this.check([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x72, 0x6B, 0x00, 0x00, 0x00, 0x00])) {
return {
ext: 'alias',
mime: 'application/x.apple.alias', // Invented by us
};
}
if (
this.check([0x4C, 0x50], {offset: 34})
&& (
this.check([0x00, 0x00, 0x01], {offset: 8})
|| this.check([0x01, 0x00, 0x02], {offset: 8})
|| this.check([0x02, 0x00, 0x02], {offset: 8})
)
) {
return {
ext: 'eot',
mime: 'application/vnd.ms-fontobject',
};
}
if (this.check([0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D])) {
return {
ext: 'indd',
mime: 'application/x-indesign',
};
}
// Increase sample size from 256 to 512
await tokenizer.peekBuffer(this.buffer, {length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true});
// Requires a buffer size of 512 bytes
if (tarHeaderChecksumMatches(this.buffer)) {
return {
ext: 'tar',
mime: 'application/x-tar',
};
}
if (this.check([0xFF, 0xFE, 0xFF, 0x0E, 0x53, 0x00, 0x6B, 0x00, 0x65, 0x00, 0x74, 0x00, 0x63, 0x00, 0x68, 0x00, 0x55, 0x00, 0x70, 0x00, 0x20, 0x00, 0x4D, 0x00, 0x6F, 0x00, 0x64, 0x00, 0x65, 0x00, 0x6C, 0x00])) {
return {
ext: 'skp',
mime: 'application/vnd.sketchup.skp',
};
}
if (this.checkString('-----BEGIN PGP MESSAGE-----')) {
return {
ext: 'pgp',
mime: 'application/pgp-encrypted',
};
}
// Check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE)
if (this.buffer.length >= 2 && this.check([0xFF, 0xE0], {offset: 0, mask: [0xFF, 0xE0]})) {
if (this.check([0x10], {offset: 1, mask: [0x16]})) {
// Check for (ADTS) MPEG-2
if (this.check([0x08], {offset: 1, mask: [0x08]})) {
return {
ext: 'aac',
mime: 'audio/aac',
};
}
// Must be (ADTS) MPEG-4
return {
ext: 'aac',
mime: 'audio/aac',
};
}
// MPEG 1 or 2 Layer 3 header
// Check for MPEG layer 3
if (this.check([0x02], {offset: 1, mask: [0x06]})) {
return {
ext: 'mp3',
mime: 'audio/mpeg',
};
}
// Check for MPEG layer 2
if (this.check([0x04], {offset: 1, mask: [0x06]})) {
return {
ext: 'mp2',
mime: 'audio/mpeg',
};
}
// Check for MPEG layer 1
if (this.check([0x06], {offset: 1, mask: [0x06]})) {
return {
ext: 'mp1',
mime: 'audio/mpeg',
};
}
}
}
async readTiffTag(bigEndian) {
const tagId = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
this.tokenizer.ignore(10);
switch (tagId) {
case 50_341:
return {
ext: 'arw',
mime: 'image/x-sony-arw',
};
case 50_706:
return {
ext: 'dng',
mime: 'image/x-adobe-dng',
};
}
}
async readTiffIFD(bigEndian) {
const numberOfTags = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
for (let n = 0; n < numberOfTags; ++n) {
const fileType = await this.readTiffTag(bigEndian);
if (fileType) {
return fileType;
}
}
}
async readTiffHeader(bigEndian) {
const version = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 2);
const ifdOffset = (bigEndian ? UINT32_BE : UINT32_LE).get(this.buffer, 4);
if (version === 42) {
// TIFF file header
if (ifdOffset >= 6) {
if (this.checkString('CR', {offset: 8})) {
return {
ext: 'cr2',
mime: 'image/x-canon-cr2',
};
}
if (ifdOffset >= 8 && (this.check([0x1C, 0x00, 0xFE, 0x00], {offset: 8}) || this.check([0x1F, 0x00, 0x0B, 0x00], {offset: 8}))) {
return {
ext: 'nef',
mime: 'image/x-nikon-nef',
};
}
}
await this.tokenizer.ignore(ifdOffset);
const fileType = await this.readTiffIFD(false);
return fileType ? fileType : {
ext: 'tif',
mime: 'image/tiff',
};
}
if (version === 43) { // Big TIFF file header
return {
ext: 'tif',
mime: 'image/tiff',
};
}
}
}
function _arrayLikeToArray$6(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithoutHoles$4(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$6(arr);
}
function asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$8(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArray$4(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread$4() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray$4(arr) {
return _arrayWithoutHoles$4(arr) || _iterableToArray$4(arr) || _unsupportedIterableToArray$6(arr) || _nonIterableSpread$4();
}
function _unsupportedIterableToArray$6(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$6(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$6(o, minLen);
}
var csettings$2;
settings.subscribe(function(b) {
csettings$2 = b;
});
var generateThumbnail = function() {
var _ref = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee(f) {
var can, sw, sh, url, source, iw, ih, imgElem, ref, vidElem, ref1, scale, dims, ctx, blob;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
can = document.createElement("canvas");
can.width = 125;
can.height = 125;
sw = 125, sh = 125;
url = URL.createObjectURL(f);
if (!f.type.startsWith("image")) {
_ctx.next = 17;
break;
}
imgElem = document.createElement("img");
imgElem.src = url;
_ctx.next = 12;
return new Promise(function(_) {
return imgElem.onload = _;
});
case 12:
ref = [
imgElem.naturalWidth,
imgElem.naturalHeight
], iw = ref[0], ih = ref[1];
source = imgElem;
_ctx.next = 37;
break;
case 17:
if (!f.type.startsWith("video")) {
_ctx.next = 36;
break;
}
vidElem = document.createElement("video");
vidElem.src = url;
_ctx.next = 22;
return new Promise(function(_) {
return vidElem.onloadedmetadata = _;
});
case 22:
vidElem.currentTime = 0;
_ctx.next = 25;
return new Promise(function(_) {
return vidElem.onloadeddata = _;
});
case 25:
_ctx.next = 27;
return new Promise(requestAnimationFrame);
case 27:
_ctx.next = 29;
return new Promise(requestAnimationFrame);
case 29:
_ctx.next = 31;
return new Promise(requestAnimationFrame);
case 31:
ref1 = [
vidElem.videoWidth,
vidElem.videoHeight
], iw = ref1[0], ih = ref1[1];
source = vidElem;
_ctx.next = 37;
break;
case 36:
return _ctx.abrupt("return", Buffer$1.alloc(0));
case 37:
scale = Math.min(1, sw / iw, sh / ih);
dims = [
~~(iw * scale),
~~(ih * scale)
];
can.width = dims[0];
can.height = dims[1];
ctx = can.getContext("2d");
if (ctx) {
_ctx.next = 44;
break;
}
return _ctx.abrupt("return", Buffer$1.alloc(0));
case 44:
ctx.drawImage(source, 0, 0, dims[0], dims[1]);
_ctx.next = 47;
return new Promise(function(_) {
return can.toBlob(_, "image/jpg");
});
case 47:
blob = _ctx.sent;
if (blob) {
_ctx.next = 50;
break;
}
return _ctx.abrupt("return", Buffer$1.alloc(0));
case 50:
_ctx.t0 = Buffer$1;
_ctx.next = 53;
return blob.arrayBuffer();
case 53:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", _ctx.t0.from.call(_ctx.t0, _ctx.t1));
case 55:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function generateThumbnail(f) {
return _ref.apply(this, arguments);
};
}();
var buildPeeFile = function() {
var _ref = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee(f) {
var thumbnail1, namebuf, ret, ptr;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
thumbnail1 = Buffer$1.alloc(0);
_ctx.next = 3;
return generateThumbnail(f);
case 3:
thumbnail1 = _ctx.sent;
namebuf = Buffer$1.from(f.name);
ret = Buffer$1.alloc(4 /* Magic */ + 1 /* Flags */ + namebuf.byteLength + 1 + (thumbnail1.byteLength != 0 ? 4 + thumbnail1.byteLength : 0) + f.size /*Teh file*/ );
ptr = 0;
ret.write("PEE\0", 0);
ptr += 4;
ret[ptr++] = 1 | +(thumbnail1.length != 0) << 2;
namebuf.copy(ret, ptr);
ptr += namebuf.byteLength;
ret[ptr++] = 0;
if (thumbnail1.length > 0) {
ret.writeInt32LE(thumbnail1.byteLength, ptr);
ptr += 4;
thumbnail1.copy(ret, ptr);
ptr += thumbnail1.byteLength;
}
_ctx.t0 = Buffer$1;
_ctx.next = 17;
return f.arrayBuffer();
case 17:
_ctx.t1 = _ctx.sent;
_ctx.t0.from.call(_ctx.t0, _ctx.t1).copy(ret, ptr);
return _ctx.abrupt("return", new Blob([
ret
]));
case 20:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function buildPeeFile(f) {
return _ref.apply(this, arguments);
};
}();
/*
header (must be < 2k): [1 byte bitfield](if hasfilename: null terminated string)(if has tags: [X null terminated string, tags are whitespace-separated])
(if has thumbnail: [thumbnail size X]
rest: [X bytes of thumbnail data])[file bytes]
&1 => has filename
&2 => has tags
&4 => has thumbnail
*/ var decodeCoom3Payload = function() {
var _ref1 = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee1(buff) {
var allowed_domains, pees;
return regeneratorRuntime$1.wrap(function _callee$(_ctx1) {
while(1)switch(_ctx1.prev = _ctx1.next){
case 0:
allowed_domains = filehosts.map(function(e) {
return e.serving.replaceAll(".", "\\.");
});
pees = buff.toString().split(" ").slice(0, csettings$2.maxe).filter(function(e) {
return allowed_domains.some(function(v) {
return e.match("https://(.*\\.)?".concat(v, "/"));
});
});
_ctx1.next = 4;
return Promise.all(pees.map(function() {
var _ref2 = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee2(pee) {
var m, _groups, domain, file, headers, res, size, header, hptr, flags, hasFn, hasTags, hasThumbnail, ref, ptr, ptr2, fn, thumb, thumbsize, data;
return regeneratorRuntime$1.wrap(function _callee$(_ctx2) {
while(1)switch(_ctx2.prev = _ctx2.next){
case 0:
_ctx2.prev = 0;
m = pee.match(RegExp("(?<protocol>https?):\\/\\/(?<domain>.*?)(?<file>\\/.*)"));
if (m) {
_ctx2.next = 4;
break;
}
return _ctx2.abrupt("return");
case 4:
_groups = m.groups, domain = _groups.domain, file = _groups.file;
_ctx2.next = 7;
return getHeaders(pee);
case 7:
headers = _ctx2.sent;
_ctx2.next = 10;
return ifetch(pee, {
headers: {
range: "bytes=0-2048",
"user-agent": ""
},
mode: "cors",
referrerPolicy: "no-referrer"
});
case 10:
res = _ctx2.sent;
size = +headers["content-length"] || 0;
_ctx2.t0 = Buffer$1;
_ctx2.next = 15;
return res.arrayBuffer();
case 15:
_ctx2.t1 = _ctx2.sent;
header = _ctx2.t0.from.call(_ctx2.t0, _ctx2.t1);
hptr = 0;
if (!(header.slice(0, 4).toString() == "PEE\0")) {
_ctx2.next = 22;
break;
}
hptr += 4;
_ctx2.next = 23;
break;
case 22:
return _ctx2.abrupt("return");
case 23:
flags = header[hptr];
hasFn = !!(flags & 1);
hasTags = !!(flags & 2);
hasThumbnail = !!(flags & 4);
ref = [
hptr + 1,
hptr + 1
], ptr = ref[0], ptr2 = ref[1];
fn = "embedded";
thumb = Buffer$1.from(thumbnail);
if (hasFn) {
while(header[ptr2] != 0)ptr2++;
fn = header.slice(ptr, ptr2).toString();
ptr = ++ptr2;
}
if (hasTags) {
while(header[ptr2] != 0)ptr2++;
header.slice(ptr, ptr2).toString().split(/\s+/);
}
thumbsize = 0;
if (!hasThumbnail) {
_ctx2.next = 49;
break;
}
thumbsize = header.readInt32LE(ptr);
ptr += 4;
{
_ctx2.next = 47;
break;
}
case 41:
_ctx2.next = 43;
return _ctx2.sent.arrayBuffer();
case 43:
_ctx2.t3 = _ctx2.sent;
thumb = _ctx2.t2.from.call(_ctx2.t2, _ctx2.t3);
_ctx2.next = 48;
break;
case 47:
thumb = "https://loli.piss/".concat(domain).concat(file, "/").concat(ptr, "/").concat(ptr + thumbsize);
case 48:
ptr += thumbsize;
case 49:
(function() {
var _ref = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee(lsn) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.t0 = Buffer$1;
_ctx.next = 3;
return ifetch(pee, {
headers: {
"user-agent": "",
range: "bytes=".concat(ptr, "-").concat(size - 1)
}
}, lsn);
case 3:
_ctx.next = 5;
return _ctx.sent.arrayBuffer();
case 5:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", _ctx.t0.from.call(_ctx.t0, _ctx.t1));
case 7:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function unzip(lsn) {
return _ref.apply(this, arguments);
};
})();
{
_ctx2.next = 59;
break;
}
case 56:
thumb = data = _ctx2.sent;
case 57:
_ctx2.next = 60;
break;
case 59:
{
data = "https://loli.piss/".concat(domain).concat(file, "/").concat(ptr, "/").concat(size - 1);
}
case 60:
return _ctx2.abrupt("return", {
filename: fn,
// if file is small, then just get it fully
data: data,
thumbnail: thumb
});
case 63:
_ctx2.prev = 63;
_ctx2.t4 = _ctx2["catch"](0);
// niggers trying to fuck with bad links
console.warn(_ctx2.t4);
case 66:
case "end":
return _ctx2.stop();
}
}, _callee2, null, [
[
0,
63
]
]);
}));
return function(pee) {
return _ref2.apply(this, arguments);
};
}()));
case 4:
return _ctx1.abrupt("return", _ctx1.sent.filter(function(e) {
return e;
}));
case 5:
case "end":
return _ctx1.stop();
}
}, _callee1);
}));
return function decodeCoom3Payload(buff) {
return _ref1.apply(this, arguments);
};
}();
var fireNotification = function(type, content) {
var lifetime = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 3;
document.dispatchEvent(new CustomEvent("CreateNotification", {
detail: {
type: type,
content: content,
lifetime: lifetime
}
}));
};
var uploadFiles = function() {
var _ref3 = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee3(injs) {
var total;
return regeneratorRuntime$1.wrap(function _callee$(_ctx3) {
while(1)switch(_ctx3.prev = _ctx3.next){
case 0:
total = 0;
fireNotification("info", "Uploading ".concat(injs.length, " files..."));
_ctx3.next = 4;
return Promise.all(injs.map(function() {
var _ref = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee(inj) {
var ret;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.t0 = filehosts[csettings$2.fhost || 0];
_ctx.next = 3;
return buildPeeFile(inj);
case 3:
_ctx.t1 = _ctx.sent;
_ctx.next = 6;
return _ctx.t0.uploadFile.call(_ctx.t0, _ctx.t1);
case 6:
ret = _ctx.sent;
fireNotification("info", "Uploaded files [".concat(++total, "/").concat(injs.length, "] ").concat(ret));
return _ctx.abrupt("return", ret);
case 9:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function(inj) {
return _ref.apply(this, arguments);
};
}()));
case 4:
return _ctx3.abrupt("return", _ctx3.sent);
case 5:
case "end":
return _ctx3.stop();
}
}, _callee3);
}));
return function uploadFiles(injs) {
return _ref3.apply(this, arguments);
};
}();
var getSelectedFile = function() {
return new Promise(function(res) {
document.addEventListener("QRFile", function(e) {
return res(e.detail);
}, {
once: true
});
document.dispatchEvent(new CustomEvent("QRGetFile"));
});
};
function embeddedToBlob() {
return _embeddedToBlob.apply(this, arguments);
}
function _embeddedToBlob() {
_embeddedToBlob = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee4() {
var _len, efs, _key, _args = arguments;
return regeneratorRuntime$1.wrap(function _callee$(_ctx4) {
while(1)switch(_ctx4.prev = _ctx4.next){
case 0:
for(_len = _args.length, efs = new Array(_len), _key = 0; _key < _len; _key++){
efs[_key] = _args[_key];
}
_ctx4.next = 3;
return Promise.all(efs.map(function() {
var _ref = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee(ef) {
var buff, req, mim, file;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (!(typeof ef.data == "string")) {
_ctx.next = 12;
break;
}
_ctx.next = 4;
return GM_fetch(ef.data);
case 4:
req = _ctx.sent;
_ctx.t0 = Buffer$1;
_ctx.next = 8;
return req.arrayBuffer();
case 8:
_ctx.t1 = _ctx.sent;
buff = _ctx.t0.from.call(_ctx.t0, _ctx.t1);
_ctx.next = 19;
break;
case 12:
if (Buffer$1.isBuffer(ef.data)) {
_ctx.next = 18;
break;
}
_ctx.next = 15;
return ef.data();
case 15:
buff = _ctx.sent;
_ctx.next = 19;
break;
case 18:
buff = ef.data;
case 19:
_ctx.next = 21;
return fileTypeFromBuffer(buff);
case 21:
mim = _ctx.sent;
file = new File([
buff
], ef.filename, {
type: mim === null || mim === void 0 ? void 0 : mim.mime
});
return _ctx.abrupt("return", file);
case 24:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function(ef) {
return _ref.apply(this, arguments);
};
}()));
case 3:
return _ctx4.abrupt("return", _ctx4.sent.filter(function(e) {
return e;
}));
case 4:
case "end":
return _ctx4.stop();
}
}, _callee4);
}));
return _embeddedToBlob.apply(this, arguments);
}
function addToEmbeds() {
return _addToEmbeds.apply(this, arguments);
}
function _addToEmbeds() {
_addToEmbeds = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee() {
var _len, efs, _key, files, links, _args = arguments;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
for(_len = _args.length, efs = new Array(_len), _key = 0; _key < _len; _key++){
efs[_key] = _args[_key];
}
_ctx.next = 3;
return embeddedToBlob.apply(void 0, _toConsumableArray$4(efs));
case 3:
files = _ctx.sent;
_ctx.next = 6;
return uploadFiles(files);
case 6:
links = _ctx.sent;
document.dispatchEvent(new CustomEvent("AddPEE", {
detail: links
}));
case 8:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return _addToEmbeds.apply(this, arguments);
}
function getFileFromHydrus(client, tags, args) {
return _getFileFromHydrus.apply(this, arguments);
}
function _getFileFromHydrus() {
_getFileFromHydrus = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee5(client, tags, args) {
var results, metas;
return regeneratorRuntime$1.wrap(function _callee$(_ctx5) {
while(1)switch(_ctx5.prev = _ctx5.next){
case 0:
_ctx5.next = 2;
return client.idsByTags(tags, args);
case 2:
results = _ctx5.sent.file_ids;
_ctx5.next = 5;
return client.getMetaDataByIds(results);
case 5:
metas = _ctx5.sent;
_ctx5.next = 8;
return Promise.all(results.map(function() {
var _ref = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee6(id, idx) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx6) {
while(1)switch(_ctx6.prev = _ctx6.next){
case 0:
_ctx6.t0 = id;
_ctx6.t1 = Buffer$1;
_ctx6.next = 4;
return client.getThumbnail(id);
case 4:
_ctx6.t2 = _ctx6.sent;
_ctx6.t3 = _ctx6.t1.from.call(_ctx6.t1, _ctx6.t2);
_ctx6.t4 = _asyncToGenerator$8(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.t0 = Buffer$1;
_ctx.next = 3;
return client.getFile(id);
case 3:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", _ctx.t0.from.call(_ctx.t0, _ctx.t1));
case 5:
case "end":
return _ctx.stop();
}
}, _callee);
}));
_ctx6.t5 = metas.metadata[idx].hash + metas.metadata[idx].ext;
_ctx6.t6 = {
thumbnail: _ctx6.t3,
data: _ctx6.t4,
filename: _ctx6.t5
};
return _ctx6.abrupt("return", [
_ctx6.t0,
_ctx6.t6,
]);
case 10:
case "end":
return _ctx6.stop();
}
}, _callee6);
}));
return function(id, idx) {
return _ref.apply(this, arguments);
};
}()));
case 8:
return _ctx5.abrupt("return", _ctx5.sent);
case 9:
case "end":
return _ctx5.stop();
}
}, _callee5);
}));
return _getFileFromHydrus.apply(this, arguments);
}
function _arrayLikeToArray$5(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles$3(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles$3(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$5(arr);
}
function _asyncIterator(iterable) {
var method;
if (typeof Symbol === "function") {
if (Symbol.asyncIterator) {
method = iterable[Symbol.asyncIterator];
if (method != null) return method.call(iterable);
}
if (Symbol.iterator) {
method = iterable[Symbol.iterator];
if (method != null) return method.call(iterable);
}
}
throw new TypeError("Object is not async iterable");
}
function asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$7(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArray$3(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit$3(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$3() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread$3() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray$3(arr, i) {
return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i) || _unsupportedIterableToArray$5(arr, i) || _nonIterableRest$3();
}
function _toConsumableArray$3(arr) {
return _arrayWithoutHoles$3(arr) || _iterableToArray$3(arr) || _unsupportedIterableToArray$5(arr) || _nonIterableSpread$3();
}
function _unsupportedIterableToArray$5(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$5(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen);
}
var CUM3 = Buffer$1.from("doo\0" + "m");
var BufferReadStream = function(b) {
var ret = new ReadableStream({
pull: function pull(cont) {
cont.enqueue(b);
cont.close();
}
});
return ret;
};
var extract$4 = function() {
var _ref = _asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee(png) {
var reader, sneed, ret, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, __value, name, chunk, buff, _ret, k;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
reader = BufferReadStream(png).getReader();
sneed = new PNGDecoder(reader);
ret = [];
_ctx.prev = 3;
_iteratorAbruptCompletion = false, _didIteratorError = false;
_ctx.prev = 5;
_iterator = _asyncIterator(sneed.chunks());
case 7:
_ctx.next = 9;
return _iterator.next();
case 9:
if (!(_iteratorAbruptCompletion = !(_step = _ctx.sent).done)) {
_ctx.next = 31;
break;
}
_value = _step.value;
__value = _slicedToArray$3(_value, 4), name = __value[0], chunk = __value[1];
buff = void 0;
_ctx.t0 = name;
_ctx.next = _ctx.t0 === "tEXt" ? 16 : _ctx.t0 === "IDAT" ? 26 : _ctx.t0 === "IEND" ? 26 : 27;
break;
case 16:
_ctx.next = 18;
return chunk();
case 18:
buff = _ctx.sent;
if (!buff.slice(4, 4 + CUM3.length).equals(CUM3)) {
_ctx.next = 25;
break;
}
_ctx.next = 23;
return decodeCoom3Payload(buff.slice(4 + CUM3.length));
case 23:
k = _ctx.sent;
(_ret = ret).push.apply(_ret, _toConsumableArray$3(k.filter(function(e) {
return e;
}).map(function(e) {
return e;
})));
case 25:
return _ctx.abrupt("break", 28);
case 26:
return _ctx.abrupt("return", ret);
case 27:
return _ctx.abrupt("break", 28);
case 28:
_iteratorAbruptCompletion = false;
_ctx.next = 7;
break;
case 31:
_ctx.next = 37;
break;
case 33:
_ctx.prev = 33;
_ctx.t1 = _ctx["catch"](5);
_didIteratorError = true;
_iteratorError = _ctx.t1;
case 37:
_ctx.prev = 37;
_ctx.prev = 38;
if (!(_iteratorAbruptCompletion && _iterator.return != null)) {
_ctx.next = 42;
break;
}
_ctx.next = 42;
return _iteratorError.return();
case 42:
_ctx.prev = 42;
if (!_didIteratorError) {
_ctx.next = 45;
break;
}
throw _iteratorError;
case 45:
return _ctx.finish(42);
case 46:
return _ctx.finish(37);
case 47:
_ctx.next = 52;
break;
case 49:
_ctx.prev = 49;
_ctx.t2 = _ctx["catch"](3);
console.error(_ctx.t2);
case 52:
_ctx.prev = 52;
reader.releaseLock();
return _ctx.finish(52);
case 55:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
3,
49,
52,
55
],
[
5,
33,
37,
47
],
[
38,
,
42,
46
]
]);
}));
return function extract(png) {
return _ref.apply(this, arguments);
};
}();
var buildChunk = function(tag, data) {
var ret = Buffer$1.alloc(data.byteLength + 4);
ret.write(tag.slice(0, 4), 0);
data.copy(ret, 4);
return ret;
};
var BufferWriteStream = function() {
var b = Buffer$1.from([]);
var ret = new WritableStream({
write: function write(chunk) {
b = Buffer$1.concat([
b,
chunk
]);
}
});
return [
ret,
function() {
return b;
}
];
};
var inject_data = function() {
var _ref = _asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee1(container, injb) {
var magic, ref, writestream, extract, encoder, decoder, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, __value, name, chunk, crc, offset;
return regeneratorRuntime$1.wrap(function _callee$(_ctx1) {
while(1)switch(_ctx1.prev = _ctx1.next){
case 0:
magic = false;
ref = _slicedToArray$3(BufferWriteStream(), 2), writestream = ref[0], extract = ref[1];
encoder = new PNGEncoder(writestream);
decoder = new PNGDecoder(container.stream().getReader());
_iteratorAbruptCompletion = false, _didIteratorError = false;
_ctx1.prev = 5;
_iterator = _asyncIterator(decoder.chunks());
case 7:
_ctx1.next = 9;
return _iterator.next();
case 9:
if (!(_iteratorAbruptCompletion = !(_step = _ctx1.sent).done)) {
_ctx1.next = 23;
break;
}
_value = _step.value;
__value = _slicedToArray$3(_value, 4), name = __value[0], chunk = __value[1], crc = __value[2], offset = __value[3];
if (!(magic && name != "IDAT")) {
_ctx1.next = 14;
break;
}
return _ctx1.abrupt("break", 23);
case 14:
if (!(!magic && name == "IDAT")) {
_ctx1.next = 18;
break;
}
_ctx1.next = 17;
return encoder.insertchunk([
"tEXt",
_asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
return _ctx.abrupt("return", buildChunk("tEXt", Buffer$1.concat([
CUM3,
injb
])));
case 1:
case "end":
return _ctx.stop();
}
}, _callee);
})),
function() {
return Promise.resolve(0);
},
0
]);
case 17:
magic = true;
case 18:
_ctx1.next = 20;
return encoder.insertchunk([
name,
chunk,
crc,
offset
]);
case 20:
_iteratorAbruptCompletion = false;
_ctx1.next = 7;
break;
case 23:
_ctx1.next = 29;
break;
case 25:
_ctx1.prev = 25;
_ctx1.t0 = _ctx1["catch"](5);
_didIteratorError = true;
_iteratorError = _ctx1.t0;
case 29:
_ctx1.prev = 29;
_ctx1.prev = 30;
if (!(_iteratorAbruptCompletion && _iterator.return != null)) {
_ctx1.next = 34;
break;
}
_ctx1.next = 34;
return _iteratorError.return();
case 34:
_ctx1.prev = 34;
if (!_didIteratorError) {
_ctx1.next = 37;
break;
}
throw _iteratorError;
case 37:
return _ctx1.finish(34);
case 38:
return _ctx1.finish(29);
case 39:
_ctx1.next = 41;
return encoder.insertchunk([
"IEND",
_asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
return _ctx.abrupt("return", Promise.resolve(buildChunk("IEND", Buffer$1.from([]))));
case 1:
case "end":
return _ctx.stop();
}
}, _callee);
})),
_asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
return _ctx.abrupt("return", Promise.resolve(0));
case 1:
case "end":
return _ctx.stop();
}
}, _callee);
})),
0
]);
case 41:
return _ctx1.abrupt("return", extract());
case 42:
case "end":
return _ctx1.stop();
}
}, _callee1, null, [
[
5,
25,
29,
39
],
[
30,
,
34,
38
]
]);
}));
return function inject_data(container, injb) {
return _ref.apply(this, arguments);
};
}();
var inject$3 = function() {
var _ref = _asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee(container, links) {
var injb;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
injb = Buffer$1.from(links.join(" "));
return _ctx.abrupt("return", inject_data(container, injb));
case 2:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function inject(container, links) {
return _ref.apply(this, arguments);
};
}();
var has_embed$4 = function() {
var _ref = _asyncToGenerator$7(regeneratorRuntime$1.mark(function _callee(png) {
var reader, sneed, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, __value, name, chunk, buff;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
reader = BufferReadStream(png).getReader();
sneed = new PNGDecoder(reader);
_ctx.prev = 2;
_iteratorAbruptCompletion = false, _didIteratorError = false;
_ctx.prev = 4;
_iterator = _asyncIterator(sneed.chunks());
case 6:
_ctx.next = 8;
return _iterator.next();
case 8:
if (!(_iteratorAbruptCompletion = !(_step = _ctx.sent).done)) {
_ctx.next = 26;
break;
}
_value = _step.value;
__value = _slicedToArray$3(_value, 4), name = __value[0], chunk = __value[1];
buff = void 0;
_ctx.t0 = name;
_ctx.next = _ctx.t0 === "tEXt" ? 15 : _ctx.t0 === "IDAT" ? 21 : _ctx.t0 === "IEND" ? 21 : 22;
break;
case 15:
_ctx.next = 17;
return chunk();
case 17:
buff = _ctx.sent;
if (!buff.slice(4, 4 + CUM3.length).equals(CUM3)) {
_ctx.next = 20;
break;
}
return _ctx.abrupt("return", true);
case 20:
return _ctx.abrupt("break", 23);
case 21:
return _ctx.abrupt("return", false);
case 22:
return _ctx.abrupt("break", 23);
case 23:
_iteratorAbruptCompletion = false;
_ctx.next = 6;
break;
case 26:
_ctx.next = 32;
break;
case 28:
_ctx.prev = 28;
_ctx.t1 = _ctx["catch"](4);
_didIteratorError = true;
_iteratorError = _ctx.t1;
case 32:
_ctx.prev = 32;
_ctx.prev = 33;
if (!(_iteratorAbruptCompletion && _iterator.return != null)) {
_ctx.next = 37;
break;
}
_ctx.next = 37;
return _iteratorError.return();
case 37:
_ctx.prev = 37;
if (!_didIteratorError) {
_ctx.next = 40;
break;
}
throw _iteratorError;
case 40:
return _ctx.finish(37);
case 41:
return _ctx.finish(32);
case 42:
_ctx.next = 47;
break;
case 44:
_ctx.prev = 44;
_ctx.t2 = _ctx["catch"](2);
return _ctx.abrupt("return");
case 47:
_ctx.prev = 47;
reader.releaseLock();
return _ctx.finish(47);
case 50:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
2,
44,
47,
50
],
[
4,
28,
32,
42
],
[
33,
,
37,
41
]
]);
}));
return function has_embed(png) {
return _ref.apply(this, arguments);
};
}();
var pngv3 = {
extract: extract$4,
has_embed: has_embed$4,
inject: inject$3,
match: function(fn) {
return !!fn.match(/\.png$/);
}
};
function _classCallCheck$3(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _instanceof$2(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
var BIT32 = 4294967296;
var BIT24 = 16777216;
var fact = function(be, uns) {
var Int64 = /*#__PURE__*/ function() {
function Int64(buf) {
_classCallCheck$3(this, Int64);
var fromPositiveBE = function fromPositiveBE(buffer, offset, value) {
var pos = offset + 8;
while(pos > offset){
buffer[--pos] = value & 255;
value /= 256;
}
};
var fromNegativeBE = function fromNegativeBE(buffer, offset, value) {
var pos = offset + 8;
value++;
while(pos > offset){
buffer[--pos] = -value & 255 ^ 255;
value /= 256;
}
};
var fromPositiveLE = function fromPositiveLE(buffer, offset, value) {
var end = offset + 8;
while(offset < end){
buffer[offset++] = value & 255;
value /= 256;
}
};
var fromNegativeLE = function fromNegativeLE(buffer, offset, value) {
var end = offset + 8;
value++;
while(offset < end){
buffer[offset++] = -value & 255 ^ 255;
value /= 256;
}
};
this.buffer = Buffer.alloc(8);
this.offset = 0;
this.posH = 0;
this.posL = 0;
this.pos0 = 0;
this.pos1 = 0;
this.pos2 = 0;
this.pos3 = 0;
this.storage = null;
this.posH = be ? 0 : 4;
this.posL = be ? 4 : 0;
this.pos0 = be ? 0 : 3;
this.pos1 = be ? 1 : 2;
this.pos2 = be ? 2 : 1;
this.pos3 = be ? 3 : 0;
var fromPositive = be ? fromPositiveBE : fromPositiveLE;
var fromNegative = be ? fromNegativeBE : fromNegativeLE;
if (Buffer.isBuffer(buf)) buf.copy(this.buffer, 0, 0, 8);
else if (buf > 0) {
fromPositive(this.buffer, 0, buf); // positive
} else if (buf < 0) {
fromNegative(this.buffer, 0, buf);
}
}
var _proto = Int64.prototype;
_proto.readInt32 = function readInt32(buffer, offset) {
return buffer[offset + this.pos0] * BIT24 + (buffer[offset + this.pos1] << 16) + (buffer[offset + this.pos2] << 8) + buffer[offset + this.pos3];
};
_proto.toNumber = function toNumber() {
var buffer = this.buffer;
var offset = this.offset;
var high = this.readInt32(buffer, offset + this.posH);
var low = this.readInt32(buffer, offset + this.posL);
if (!uns) high |= 0; // a trick to get signed
return high ? high * BIT32 + low : low;
};
_proto.fromArray = function fromArray(destbuf, destoff, srcbuf, srcoff) {
destoff |= 0;
srcoff |= 0;
for(var i = 0; i < 8; i++){
destbuf[destoff++] = srcbuf[srcoff++] & 255;
}
};
_proto.toArrayBuffer = function toArrayBuffer(raw) {
var buffer = this.buffer;
var offset = this.offset;
var arrbuf = buffer.buffer;
this.storage = Uint8Array;
// arrbuf.slice() ignores buffer.offset until Node v8.0.0
if (raw !== false && !buffer.byteOffset && _instanceof$2(arrbuf, ArrayBuffer)) {
return arrbuf.byteLength === 8 ? arrbuf : arrbuf.slice(offset, offset + 8);
}
var dest = new Uint8Array(8);
this.fromArray(dest, 0, buffer, offset);
return dest.buffer;
};
_proto.toBuffer = function toBuffer(raw) {
var buffer = this.buffer;
var offset = this.offset;
this.storage = Buffer;
if (raw !== false && Buffer.isBuffer(buffer)) {
return buffer.length === 8 ? buffer : buffer.slice(offset, offset + 8);
}
// Buffer.from(arraybuffer) available since Node v4.5.0
// https://nodejs.org/en/blog/release/v4.5.0/
return Buffer.from(this.toArrayBuffer(raw));
};
return Int64;
}();
return Int64;
};
var Int64BE = fact(true, false);
/*jslint node: true, vars: true, nomen: true */
var byEbmlID$2 = {
0x80: {
name: "ChapterDisplay",
level: 4,
type: "m",
multiple: true,
minver: 1,
webm: true,
description: "Contains all possible strings to use for the chapter display."
},
0x83: {
name: "TrackType",
level: 3,
type: "u",
mandatory: true,
minver: 1,
range: "1-254",
description: "A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control)."
},
0x85: {
name: "ChapString",
cppname: "ChapterString",
level: 5,
type: "8",
mandatory: true,
minver: 1,
webm: true,
description: "Contains the string to use as the chapter atom."
},
0x86: {
name: "CodecID",
level: 3,
type: "s",
mandatory: true,
minver: 1,
description: "An ID corresponding to the codec, see the codec page for more info."
},
0x88: {
name: "FlagDefault",
cppname: "TrackFlagDefault",
level: 3,
type: "u",
mandatory: true,
minver: 1,
"default": 1,
range: "0-1",
description: "Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference. (1 bit)"
},
0x89: {
name: "ChapterTrackNumber",
level: 5,
type: "u",
mandatory: true,
multiple: true,
minver: 1,
webm: false,
range: "not 0",
description: "UID of the Track to apply this chapter too. In the absense of a control track, choosing this chapter will select the listed Tracks and deselect unlisted tracks. Absense of this element indicates that the Chapter should be applied to any currently used Tracks."
},
0x91: {
name: "ChapterTimeStart",
level: 4,
type: "u",
mandatory: true,
minver: 1,
webm: true,
description: "Timestamp of the start of Chapter (not scaled)."
},
0x92: {
name: "ChapterTimeEnd",
level: 4,
type: "u",
minver: 1,
webm: false,
description: "Timestamp of the end of Chapter (timestamp excluded, not scaled)."
},
0x96: {
name: "CueRefTime",
level: 5,
type: "u",
mandatory: true,
minver: 2,
webm: false,
description: "Timestamp of the referenced Block."
},
0x97: {
name: "CueRefCluster",
level: 5,
type: "u",
mandatory: true,
webm: false,
description: "The Position of the Cluster containing the referenced Block."
},
0x98: {
name: "ChapterFlagHidden",
level: 4,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
range: "0-1",
description: "If a chapter is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)"
},
0x4254: {
name: "ContentCompAlgo",
level: 6,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
// "br": [ "", "", "", "" ],
// "del": [ "1 - bzlib,", "2 - lzo1x" ],
description: "The compression algorithm used. Algorithms that have been specified so far are: 0 - zlib, 3 - Header Stripping"
},
0x4255: {
name: "ContentCompSettings",
level: 6,
type: "b",
minver: 1,
webm: false,
description: "Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3), the bytes that were removed from the beggining of each frames of the track."
},
0x4282: {
name: "DocType",
level: 1,
type: "s",
mandatory: true,
"default": "matroska",
minver: 1,
description: "A string that describes the type of document that follows this EBML header. 'matroska' in our case or 'webm' for webm files."
},
0x4285: {
name: "DocTypeReadVersion",
level: 1,
type: "u",
mandatory: true,
"default": 1,
minver: 1,
description: "The minimum DocType version an interpreter has to support to read this file."
},
0x4286: {
name: "EBMLVersion",
level: 1,
type: "u",
mandatory: true,
"default": 1,
minver: 1,
description: "The version of EBML parser used to create the file."
},
0x4287: {
name: "DocTypeVersion",
level: 1,
type: "u",
mandatory: true,
"default": 1,
minver: 1,
description: "The version of DocType interpreter used to create the file."
},
0x4444: {
name: "SegmentFamily",
level: 2,
type: "b",
multiple: true,
minver: 1,
webm: false,
bytesize: 16,
description: "A randomly generated unique ID that all segments related to each other must use (128 bits)."
},
0x4461: {
name: "DateUTC",
level: 2,
type: "d",
minver: 1,
description: "Date of the origin of timestamp (value 0), i.e. production date."
},
0x4484: {
name: "TagDefault",
level: 4,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 1,
range: "0-1",
description: "Indication to know if this is the default/original language to use for the given tag. (1 bit)"
},
0x4485: {
name: "TagBinary",
level: 4,
type: "b",
minver: 1,
webm: false,
description: "The values of the Tag if it is binary. Note that this cannot be used in the same SimpleTag as TagString."
},
0x4487: {
name: "TagString",
level: 4,
type: "8",
minver: 1,
webm: false,
description: "The value of the Element."
},
0x4489: {
name: "Duration",
level: 2,
type: "f",
minver: 1,
range: "> 0",
description: "Duration of the segment (based on TimecodeScale)."
},
0x4598: {
name: "ChapterFlagEnabled",
level: 4,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 1,
range: "0-1",
description: "Specify wether the chapter is enabled. It can be enabled/disabled by a Control Track. When disabled, the movie should skip all the content between the TimeStart and TimeEnd of this chapter (see flag notes). (1 bit)"
},
0x4660: {
name: "FileMimeType",
level: 3,
type: "s",
mandatory: true,
minver: 1,
webm: false,
description: "MIME type of the file."
},
0x4661: {
name: "FileUsedStartTime",
level: 3,
type: "u",
divx: true,
description: "DivX font extension"
},
0x4662: {
name: "FileUsedEndTime",
level: 3,
type: "u",
divx: true,
description: "DivX font extension"
},
0x4675: {
name: "FileReferral",
level: 3,
type: "b",
webm: false,
description: "A binary value that a track/codec can refer to when the attachment is needed."
},
0x5031: {
name: "ContentEncodingOrder",
level: 5,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
description: "Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder elements in the segment."
},
0x5032: {
name: "ContentEncodingScope",
level: 5,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 1,
range: "not 0",
// "br": [ "", "", "" ],
description: "A bit field that describes which elements have been modified in this way. Values (big endian) can be OR'ed. Possible values: 1 - all frame contents, 2 - the track's private data, 4 - the next ContentEncoding (next ContentEncodingOrder. Either the data inside ContentCompression and/or ContentEncryption)"
},
0x5033: {
name: "ContentEncodingType",
level: 5,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
// "br": [ "", "" ],
description: "A value describing what kind of transformation has been done. Possible values: 0 - compression, 1 - encryption"
},
0x5034: {
name: "ContentCompression",
level: 5,
type: "m",
minver: 1,
webm: false,
description: "Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking."
},
0x5035: {
name: "ContentEncryption",
level: 5,
type: "m",
minver: 1,
webm: false,
description: "Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise."
},
0x5378: {
name: "CueBlockNumber",
level: 4,
type: "u",
minver: 1,
"default": 1,
range: "not 0",
description: "Number of the Block in the specified Cluster."
},
0x5654: {
name: "ChapterStringUID",
level: 4,
type: "8",
mandatory: false,
minver: 3,
webm: true,
description: "A unique string ID to identify the Chapter. Use for WebVTT cue identifier storage."
},
0x5741: {
name: "WritingApp",
level: 2,
type: "8",
mandatory: true,
minver: 1,
description: "Writing application (\"mkvmerge-0.3.3\")."
},
0x5854: {
name: "SilentTracks",
cppname: "ClusterSilentTracks",
level: 2,
type: "m",
minver: 1,
webm: false,
description: "The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use."
},
0x6240: {
name: "ContentEncoding",
level: 4,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: false,
description: "Settings for one content encoding like compression or encryption."
},
0x6264: {
name: "BitDepth",
cppname: "AudioBitDepth",
level: 4,
type: "u",
minver: 1,
range: "not 0",
description: "Bits per sample, mostly used for PCM."
},
0x6532: {
name: "SignedElement",
level: 3,
type: "b",
multiple: true,
webm: false,
description: "An element ID whose data will be used to compute the signature."
},
0x6624: {
name: "TrackTranslate",
level: 3,
type: "m",
multiple: true,
minver: 1,
webm: false,
description: "The track identification for the given Chapter Codec."
},
0x6911: {
name: "ChapProcessCommand",
cppname: "ChapterProcessCommand",
level: 5,
type: "m",
multiple: true,
minver: 1,
webm: false,
description: "Contains all the commands associated to the Atom."
},
0x6922: {
name: "ChapProcessTime",
cppname: "ChapterProcessTime",
level: 6,
type: "u",
mandatory: true,
minver: 1,
webm: false,
description: "Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter)."
},
0x6924: {
name: "ChapterTranslate",
level: 2,
type: "m",
multiple: true,
minver: 1,
webm: false,
description: "A tuple of corresponding ID used by chapter codecs to represent this segment."
},
0x6933: {
name: "ChapProcessData",
cppname: "ChapterProcessData",
level: 6,
type: "b",
mandatory: true,
minver: 1,
webm: false,
description: "Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands."
},
0x6944: {
name: "ChapProcess",
cppname: "ChapterProcess",
level: 4,
type: "m",
multiple: true,
minver: 1,
webm: false,
description: "Contains all the commands associated to the Atom."
},
0x6955: {
name: "ChapProcessCodecID",
cppname: "ChapterProcessCodecID",
level: 5,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
description: "Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined), a value of 1 means the DVD command set is used. More codec IDs can be added later."
},
0x7373: {
name: "Tag",
level: 2,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: false,
description: "Element containing elements specific to Tracks/Chapters."
},
0x7384: {
name: "SegmentFilename",
level: 2,
type: "8",
minver: 1,
webm: false,
description: "A filename corresponding to this segment."
},
0x7446: {
name: "AttachmentLink",
cppname: "TrackAttachmentLink",
level: 3,
type: "u",
minver: 1,
webm: false,
range: "not 0",
description: "The UID of an attachment that is used by this codec."
},
0x258688: {
name: "CodecName",
level: 3,
type: "8",
minver: 1,
description: "A human-readable string specifying the codec."
},
0x18538067: {
name: "Segment",
level: "0",
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "This element contains all other top-level (level 1) elements. Typically a Matroska file is composed of 1 segment."
},
0x447a: {
name: "TagLanguage",
level: 4,
type: "s",
mandatory: true,
minver: 1,
webm: false,
"default": "und",
description: "Specifies the language of the tag specified, in the Matroska languages form."
},
0x45a3: {
name: "TagName",
level: 4,
type: "8",
mandatory: true,
minver: 1,
webm: false,
description: "The name of the Tag that is going to be stored."
},
0x67c8: {
name: "SimpleTag",
cppname: "TagSimple",
level: 3,
"recursive": "1",
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: false,
description: "Contains general information about the target."
},
0x63c6: {
name: "TagAttachmentUID",
level: 4,
type: "u",
multiple: true,
minver: 1,
webm: false,
"default": 0,
description: "A unique ID to identify the Attachment(s) the tags belong to. If the value is 0 at this level, the tags apply to all the attachments in the Segment."
},
0x63c4: {
name: "TagChapterUID",
level: 4,
type: "u",
multiple: true,
minver: 1,
webm: false,
"default": 0,
description: "A unique ID to identify the Chapter(s) the tags belong to. If the value is 0 at this level, the tags apply to all chapters in the Segment."
},
0x63c9: {
name: "TagEditionUID",
level: 4,
type: "u",
multiple: true,
minver: 1,
webm: false,
"default": 0,
description: "A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment."
},
0x63c5: {
name: "TagTrackUID",
level: 4,
type: "u",
multiple: true,
minver: 1,
webm: false,
"default": 0,
description: "A unique ID to identify the Track(s) the tags belong to. If the value is 0 at this level, the tags apply to all tracks in the Segment."
},
0x63ca: {
name: "TargetType",
cppname: "TagTargetType",
level: 4,
type: "s",
minver: 1,
webm: false,
"strong": "informational",
description: "An string that can be used to display the logical level of the target like \"ALBUM\", \"TRACK\", \"MOVIE\", \"CHAPTER\", etc (see TargetType)."
},
0x68ca: {
name: "TargetTypeValue",
cppname: "TagTargetTypeValue",
level: 4,
type: "u",
minver: 1,
webm: false,
"default": 50,
description: "A number to indicate the logical level of the target (see TargetType)."
},
0x63c0: {
name: "Targets",
cppname: "TagTargets",
level: 3,
type: "m",
mandatory: true,
minver: 1,
webm: false,
description: "Contain all UIDs where the specified meta data apply. It is empty to describe everything in the segment."
},
0x1254c367: {
name: "Tags",
level: 1,
type: "m",
multiple: true,
minver: 1,
webm: false,
description: "Element containing elements specific to Tracks/Chapters. A list of valid tags can be found here."
},
0x450d: {
name: "ChapProcessPrivate",
cppname: "ChapterProcessPrivate",
level: 5,
type: "b",
minver: 1,
webm: false,
description: "Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the \"DVD level\" equivalent."
},
0x437e: {
name: "ChapCountry",
cppname: "ChapterCountry",
level: 5,
type: "s",
multiple: true,
minver: 1,
webm: false,
description: "The countries corresponding to the string, same 2 octets as in Internet domains."
},
0x437c: {
name: "ChapLanguage",
cppname: "ChapterLanguage",
level: 5,
type: "s",
mandatory: true,
multiple: true,
minver: 1,
webm: true,
"default": "eng",
description: "The languages corresponding to the string, in the bibliographic ISO-639-2 form."
},
0x8f: {
name: "ChapterTrack",
level: 4,
type: "m",
minver: 1,
webm: false,
description: "List of tracks on which the chapter applies. If this element is not present, all tracks apply"
},
0x63c3: {
name: "ChapterPhysicalEquiv",
level: 4,
type: "u",
minver: 1,
webm: false,
description: "Specify the physical equivalent of this ChapterAtom like \"DVD\" (60) or \"SIDE\" (50), see complete list of values."
},
0x6ebc: {
name: "ChapterSegmentEditionUID",
level: 4,
type: "u",
minver: 1,
webm: false,
range: "not 0",
description: "The EditionUID to play from the segment linked in ChapterSegmentUID."
},
0x6e67: {
name: "ChapterSegmentUID",
level: 4,
type: "b",
minver: 1,
webm: false,
range: ">0",
bytesize: 16,
description: "A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used."
},
0x73c4: {
name: "ChapterUID",
level: 4,
type: "u",
mandatory: true,
minver: 1,
webm: true,
range: "not 0",
description: "A unique ID to identify the Chapter."
},
0xb6: {
name: "ChapterAtom",
level: 3,
"recursive": "1",
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: true,
description: "Contains the atom information to use as the chapter atom (apply to all tracks)."
},
0x45dd: {
name: "EditionFlagOrdered",
level: 3,
type: "u",
minver: 1,
webm: false,
"default": 0,
range: "0-1",
description: "Specify if the chapters can be defined multiple times and the order to play them is enforced. (1 bit)"
},
0x45db: {
name: "EditionFlagDefault",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
range: "0-1",
description: "If a flag is set (1) the edition should be used as the default one. (1 bit)"
},
0x45bd: {
name: "EditionFlagHidden",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
range: "0-1",
description: "If an edition is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)"
},
0x45bc: {
name: "EditionUID",
level: 3,
type: "u",
minver: 1,
webm: false,
range: "not 0",
description: "A unique ID to identify the edition. It's useful for tagging an edition."
},
0x45b9: {
name: "EditionEntry",
level: 2,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: true,
description: "Contains all information about a segment edition."
},
0x1043a770: {
name: "Chapters",
level: 1,
type: "m",
minver: 1,
webm: true,
description: "A system to define basic menus and partition data. For more detailed information, look at the Chapters Explanation."
},
0x46ae: {
name: "FileUID",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
range: "not 0",
description: "Unique ID representing the file, as random as possible."
},
0x465c: {
name: "FileData",
level: 3,
type: "b",
mandatory: true,
minver: 1,
webm: false,
description: "The data of the file."
},
0x466e: {
name: "FileName",
level: 3,
type: "8",
mandatory: true,
minver: 1,
webm: false,
description: "Filename of the attached file."
},
0x467e: {
name: "FileDescription",
level: 3,
type: "8",
minver: 1,
webm: false,
description: "A human-friendly name for the attached file."
},
0x61a7: {
name: "AttachedFile",
level: 2,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: false,
description: "An attached file."
},
0x1941a469: {
name: "Attachments",
level: 1,
type: "m",
minver: 1,
webm: false,
description: "Contain attached files."
},
0xeb: {
name: "CueRefCodecState",
level: 5,
type: "u",
webm: false,
"default": 0,
description: "The position of the Codec State corresponding to this referenced element. 0 means that the data is taken from the initial Track Entry."
},
0x535f: {
name: "CueRefNumber",
level: 5,
type: "u",
webm: false,
"default": 1,
range: "not 0",
description: "Number of the referenced Block of Track X in the specified Cluster."
},
0xdb: {
name: "CueReference",
level: 4,
type: "m",
multiple: true,
minver: 2,
webm: false,
description: "The Clusters containing the required referenced Blocks."
},
0xea: {
name: "CueCodecState",
level: 4,
type: "u",
minver: 2,
webm: false,
"default": 0,
description: "The position of the Codec State corresponding to this Cue element. 0 means that the data is taken from the initial Track Entry."
},
0xb2: {
name: "CueDuration",
level: 4,
type: "u",
mandatory: false,
minver: 4,
webm: false,
description: "The duration of the block according to the segment time base. If missing the track's DefaultDuration does not apply and no duration information is available in terms of the cues."
},
0xf0: {
name: "CueRelativePosition",
level: 4,
type: "u",
mandatory: false,
minver: 4,
webm: false,
description: "The relative position of the referenced block inside the cluster with 0 being the first possible position for an element inside that cluster.",
position: "clusterRelative"
},
0xf1: {
name: "CueClusterPosition",
level: 4,
type: "u",
mandatory: true,
minver: 1,
description: "The position of the Cluster containing the required Block.",
position: "segment",
},
0xf7: {
name: "CueTrack",
level: 4,
type: "u",
mandatory: true,
minver: 1,
range: "not 0",
description: "The track for which a position is given."
},
0xb7: {
name: "CueTrackPositions",
level: 3,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "Contain positions for different tracks corresponding to the timestamp."
},
0xb3: {
name: "CueTime",
level: 3,
type: "u",
mandatory: true,
minver: 1,
description: "Absolute timestamp according to the segment time base."
},
0xbb: {
name: "CuePoint",
level: 2,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "Contains all information relative to a seek point in the segment."
},
0x1c53bb6b: {
name: "Cues",
level: 1,
type: "m",
minver: 1,
description: "A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non \"live\" streams."
},
0x47e6: {
name: "ContentSigHashAlgo",
level: 6,
type: "u",
minver: 1,
webm: false,
"default": 0,
// "br": [ "", "" ],
description: "The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - SHA1-160 2 - MD5"
},
0x47e5: {
name: "ContentSigAlgo",
level: 6,
type: "u",
minver: 1,
webm: false,
"default": 0,
// "br": "",
description: "The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - RSA"
},
0x47e4: {
name: "ContentSigKeyID",
level: 6,
type: "b",
minver: 1,
webm: false,
description: "This is the ID of the private key the data was signed with."
},
0x47e3: {
name: "ContentSignature",
level: 6,
type: "b",
minver: 1,
webm: false,
description: "A cryptographic signature of the contents."
},
0x47e2: {
name: "ContentEncKeyID",
level: 6,
type: "b",
minver: 1,
webm: false,
description: "For public key algorithms this is the ID of the public key the the data was encrypted with."
},
0x47e1: {
name: "ContentEncAlgo",
level: 6,
type: "u",
minver: 1,
webm: false,
"default": 0,
// "br": "",
description: "The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values: 1 - DES, 2 - 3DES, 3 - Twofish, 4 - Blowfish, 5 - AES"
},
0x6d80: {
name: "ContentEncodings",
level: 3,
type: "m",
minver: 1,
webm: false,
description: "Settings for several content encoding mechanisms like compression or encryption."
},
0xc4: {
name: "TrickMasterTrackSegmentUID",
level: 3,
type: "b",
divx: true,
bytesize: 16,
description: "DivX trick track extenstions"
},
0xc7: {
name: "TrickMasterTrackUID",
level: 3,
type: "u",
divx: true,
description: "DivX trick track extenstions"
},
0xc6: {
name: "TrickTrackFlag",
level: 3,
type: "u",
divx: true,
"default": 0,
description: "DivX trick track extenstions"
},
0xc1: {
name: "TrickTrackSegmentUID",
level: 3,
type: "b",
divx: true,
bytesize: 16,
description: "DivX trick track extenstions"
},
0xc0: {
name: "TrickTrackUID",
level: 3,
type: "u",
divx: true,
description: "DivX trick track extenstions"
},
0xed: {
name: "TrackJoinUID",
level: 5,
type: "u",
mandatory: true,
multiple: true,
minver: 3,
webm: false,
range: "not 0",
description: "The trackUID number of a track whose blocks are used to create this virtual track."
},
0xe9: {
name: "TrackJoinBlocks",
level: 4,
type: "m",
minver: 3,
webm: false,
description: "Contains the list of all tracks whose Blocks need to be combined to create this virtual track"
},
0xe6: {
name: "TrackPlaneType",
level: 6,
type: "u",
mandatory: true,
minver: 3,
webm: false,
description: "The kind of plane this track corresponds to (0: left eye, 1: right eye, 2: background)."
},
0xe5: {
name: "TrackPlaneUID",
level: 6,
type: "u",
mandatory: true,
minver: 3,
webm: false,
range: "not 0",
description: "The trackUID number of the track representing the plane."
},
0xe4: {
name: "TrackPlane",
level: 5,
type: "m",
mandatory: true,
multiple: true,
minver: 3,
webm: false,
description: "Contains a video plane track that need to be combined to create this 3D track"
},
0xe3: {
name: "TrackCombinePlanes",
level: 4,
type: "m",
minver: 3,
webm: false,
description: "Contains the list of all video plane tracks that need to be combined to create this 3D track"
},
0xe2: {
name: "TrackOperation",
level: 3,
type: "m",
minver: 3,
webm: false,
description: "Operation that needs to be applied on tracks to create this virtual track. For more details look at the Specification Notes on the subject."
},
0x7d7b: {
name: "ChannelPositions",
cppname: "AudioPosition",
level: 4,
type: "b",
webm: false,
description: "Table of horizontal angles for each successive channel, see appendix."
},
0x9f: {
name: "Channels",
cppname: "AudioChannels",
level: 4,
type: "u",
mandatory: true,
minver: 1,
"default": 1,
range: "not 0",
description: "Numbers of channels in the track."
},
0x78b5: {
name: "OutputSamplingFrequency",
cppname: "AudioOutputSamplingFreq",
level: 4,
type: "f",
minver: 1,
"default": "Sampling Frequency",
range: "> 0",
description: "Real output sampling frequency in Hz (used for SBR techniques)."
},
0xb5: {
name: "SamplingFrequency",
cppname: "AudioSamplingFreq",
level: 4,
type: "f",
mandatory: true,
minver: 1,
"default": 8000.0,
range: "> 0",
description: "Sampling frequency in Hz."
},
0xe1: {
name: "Audio",
cppname: "TrackAudio",
level: 3,
type: "m",
minver: 1,
description: "Audio settings."
},
0x2383e3: {
name: "FrameRate",
cppname: "VideoFrameRate",
level: 4,
type: "f",
range: "> 0",
"strong": "Informational",
description: "Number of frames per second. only."
},
0x2fb523: {
name: "GammaValue",
cppname: "VideoGamma",
level: 4,
type: "f",
webm: false,
range: "> 0",
description: "Gamma Value."
},
0x2eb524: {
name: "ColourSpace",
cppname: "VideoColourSpace",
level: 4,
type: "b",
minver: 1,
webm: false,
bytesize: 4,
description: "Same value as in AVI (32 bits)."
},
0x54b3: {
name: "AspectRatioType",
cppname: "VideoAspectRatio",
level: 4,
type: "u",
minver: 1,
"default": 0,
description: "Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed)."
},
0x54b2: {
name: "DisplayUnit",
cppname: "VideoDisplayUnit",
level: 4,
type: "u",
minver: 1,
"default": 0,
description: "How DisplayWidth & DisplayHeight should be interpreted (0: pixels, 1: centimeters, 2: inches, 3: Display Aspect Ratio)."
},
0x54ba: {
name: "DisplayHeight",
cppname: "VideoDisplayHeight",
level: 4,
type: "u",
minver: 1,
"default": "PixelHeight",
range: "not 0",
description: "Height of the video frames to display. The default value is only valid when DisplayUnit is 0."
},
0x54b0: {
name: "DisplayWidth",
cppname: "VideoDisplayWidth",
level: 4,
type: "u",
minver: 1,
"default": "PixelWidth",
range: "not 0",
description: "Width of the video frames to display. The default value is only valid when DisplayUnit is 0."
},
0x54dd: {
name: "PixelCropRight",
cppname: "VideoPixelCropRight",
level: 4,
type: "u",
minver: 1,
"default": 0,
description: "The number of video pixels to remove on the right of the image."
},
0x54cc: {
name: "PixelCropLeft",
cppname: "VideoPixelCropLeft",
level: 4,
type: "u",
minver: 1,
"default": 0,
description: "The number of video pixels to remove on the left of the image."
},
0x54bb: {
name: "PixelCropTop",
cppname: "VideoPixelCropTop",
level: 4,
type: "u",
minver: 1,
"default": 0,
description: "The number of video pixels to remove at the top of the image."
},
0x54aa: {
name: "PixelCropBottom",
cppname: "VideoPixelCropBottom",
level: 4,
type: "u",
minver: 1,
"default": 0,
description: "The number of video pixels to remove at the bottom of the image (for HDTV content)."
},
0xba: {
name: "PixelHeight",
cppname: "VideoPixelHeight",
level: 4,
type: "u",
mandatory: true,
minver: 1,
range: "not 0",
description: "Height of the encoded video frames in pixels."
},
0xb0: {
name: "PixelWidth",
cppname: "VideoPixelWidth",
level: 4,
type: "u",
mandatory: true,
minver: 1,
range: "not 0",
description: "Width of the encoded video frames in pixels."
},
0x53b9: {
name: "OldStereoMode",
level: 4,
type: "u",
"maxver": "0",
webm: false,
divx: false,
description: "DEPRECATED, DO NOT USE. Bogus StereoMode value used in old versions of libmatroska. (0: mono, 1: right eye, 2: left eye, 3: both eyes)."
},
0x53c0: {
name: "AlphaMode",
cppname: "VideoAlphaMode",
level: 4,
type: "u",
minver: 3,
webm: true,
"default": 0,
description: "Alpha Video Mode. Presence of this element indicates that the BlockAdditional element could contain Alpha data."
},
0x53b8: {
name: "StereoMode",
cppname: "VideoStereoMode",
level: 4,
type: "u",
minver: 3,
webm: true,
"default": 0,
description: "Stereo-3D video mode (0: mono, 1: side by side (left eye is first), 2: top-bottom (right eye is first), 3: top-bottom (left eye is first), 4: checkboard (right is first), 5: checkboard (left is first), 6: row interleaved (right is first), 7: row interleaved (left is first), 8: column interleaved (right is first), 9: column interleaved (left is first), 10: anaglyph (cyan/red), 11: side by side (right eye is first), 12: anaglyph (green/magenta), 13 both eyes laced in one Block (left eye is first), 14 both eyes laced in one Block (right eye is first)) . There are some more details on 3D support in the Specification Notes."
},
0x9a: {
name: "FlagInterlaced",
cppname: "VideoFlagInterlaced",
level: 4,
type: "u",
mandatory: true,
minver: 2,
webm: true,
"default": 0,
range: "0-1",
description: "Set if the video is interlaced. (1 bit)"
},
0xe0: {
name: "Video",
cppname: "TrackVideo",
level: 3,
type: "m",
minver: 1,
description: "Video settings."
},
0x66a5: {
name: "TrackTranslateTrackID",
level: 4,
type: "b",
mandatory: true,
minver: 1,
webm: false,
description: "The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used."
},
0x66bf: {
name: "TrackTranslateCodec",
level: 4,
type: "u",
mandatory: true,
minver: 1,
webm: false,
description: "The chapter codec using this ID (0: Matroska Script, 1: DVD-menu)."
},
0x66fc: {
name: "TrackTranslateEditionUID",
level: 4,
type: "u",
multiple: true,
minver: 1,
webm: false,
description: "Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment."
},
0x56bb: {
name: "SeekPreRoll",
level: 3,
type: "u",
mandatory: true,
multiple: false,
"default": 0,
minver: 4,
webm: true,
description: "After a discontinuity, SeekPreRoll is the duration in nanoseconds of the data the decoder must decode before the decoded data is valid."
},
0x56aa: {
name: "CodecDelay",
level: 3,
type: "u",
multiple: false,
"default": 0,
minver: 4,
webm: true,
description: "CodecDelay is The codec-built-in delay in nanoseconds. This value must be subtracted from each block timestamp in order to get the actual timestamp. The value should be small so the muxing of tracks with the same actual timestamp are in the same Cluster."
},
0x6fab: {
name: "TrackOverlay",
level: 3,
type: "u",
multiple: true,
minver: 1,
webm: false,
description: "Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc."
},
0xaa: {
name: "CodecDecodeAll",
level: 3,
type: "u",
mandatory: true,
minver: 2,
webm: false,
"default": 1,
range: "0-1",
description: "The codec can decode potentially damaged data (1 bit)."
},
0x26b240: {
name: "CodecDownloadURL",
level: 3,
type: "s",
multiple: true,
webm: false,
description: "A URL to download about the codec used."
},
0x3b4040: {
name: "CodecInfoURL",
level: 3,
type: "s",
multiple: true,
webm: false,
description: "A URL to find information about the codec used."
},
0x3a9697: {
name: "CodecSettings",
level: 3,
type: "8",
webm: false,
description: "A string describing the encoding setting used."
},
0x63a2: {
name: "CodecPrivate",
level: 3,
type: "b",
minver: 1,
description: "Private data only known to the codec."
},
0x22b59c: {
name: "Language",
cppname: "TrackLanguage",
level: 3,
type: "s",
minver: 1,
"default": "eng",
description: "Specifies the language of the track in the Matroska languages form."
},
0x536e: {
name: "Name",
cppname: "TrackName",
level: 3,
type: "8",
minver: 1,
description: "A human-readable track name."
},
0x55ee: {
name: "MaxBlockAdditionID",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
description: "The maximum value of BlockAdditions for this track."
},
0x537f: {
name: "TrackOffset",
level: 3,
type: "i",
webm: false,
"default": 0,
description: "A value to add to the Block's Timestamp. This can be used to adjust the playback offset of a track."
},
0x23314f: {
name: "TrackTimecodeScale",
level: 3,
type: "f",
mandatory: true,
minver: 1,
"maxver": "3",
webm: false,
"default": 1.0,
range: "> 0",
description: "DEPRECATED, DO NOT USE. The scale to apply on this track to work at normal speed in relation with other tracks (mostly used to adjust video speed when the audio length differs)."
},
0x234e7a: {
name: "DefaultDecodedFieldDuration",
cppname: "TrackDefaultDecodedFieldDuration",
level: 3,
type: "u",
minver: 4,
range: "not 0",
description: "The period in nanoseconds (not scaled by TimcodeScale)\nbetween two successive fields at the output of the decoding process (see the notes)"
},
0x23e383: {
name: "DefaultDuration",
cppname: "TrackDefaultDuration",
level: 3,
type: "u",
minver: 1,
range: "not 0",
description: "Number of nanoseconds (not scaled via TimecodeScale) per frame ('frame' in the Matroska sense -- one element put into a (Simple)Block)."
},
0x6df8: {
name: "MaxCache",
cppname: "TrackMaxCache",
level: 3,
type: "u",
minver: 1,
webm: false,
description: "The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed."
},
0x6de7: {
name: "MinCache",
cppname: "TrackMinCache",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
description: "The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used."
},
0x9c: {
name: "FlagLacing",
cppname: "TrackFlagLacing",
level: 3,
type: "u",
mandatory: true,
minver: 1,
"default": 1,
range: "0-1",
description: "Set if the track may contain blocks using lacing. (1 bit)"
},
0x55aa: {
name: "FlagForced",
cppname: "TrackFlagForced",
level: 3,
type: "u",
mandatory: true,
minver: 1,
"default": 0,
range: "0-1",
description: "Set if that track MUST be active during playback. There can be many forced track for a kind (audio, video or subs), the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind. (1 bit)"
},
0xb9: {
name: "FlagEnabled",
cppname: "TrackFlagEnabled",
level: 3,
type: "u",
mandatory: true,
minver: 2,
webm: true,
"default": 1,
range: "0-1",
description: "Set if the track is usable. (1 bit)"
},
0x73c5: {
name: "TrackUID",
level: 3,
type: "u",
mandatory: true,
minver: 1,
range: "not 0",
description: "A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file."
},
0xd7: {
name: "TrackNumber",
level: 3,
type: "u",
mandatory: true,
minver: 1,
range: "not 0",
description: "The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number)."
},
0xae: {
name: "TrackEntry",
level: 2,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "Describes a track with all elements."
},
0x1654ae6b: {
name: "Tracks",
level: 1,
type: "m",
multiple: true,
minver: 1,
description: "A top-level block of information with many tracks described."
},
0xaf: {
name: "EncryptedBlock",
level: 2,
type: "b",
multiple: true,
webm: false,
description: "Similar to EncryptedBlock Structure)"
},
0xca: {
name: "ReferenceTimeCode",
level: 4,
type: "u",
multiple: false,
mandatory: true,
minver: 0,
webm: false,
divx: true,
description: "DivX trick track extenstions"
},
0xc9: {
name: "ReferenceOffset",
level: 4,
type: "u",
multiple: false,
mandatory: true,
minver: 0,
webm: false,
divx: true,
description: "DivX trick track extenstions"
},
0xc8: {
name: "ReferenceFrame",
level: 3,
type: "m",
multiple: false,
minver: 0,
webm: false,
divx: true,
description: "DivX trick track extenstions"
},
0xcf: {
name: "SliceDuration",
level: 5,
type: "u",
"default": 0,
description: "The (scaled) duration to apply to the element."
},
0xce: {
name: "Delay",
cppname: "SliceDelay",
level: 5,
type: "u",
"default": 0,
description: "The (scaled) delay to apply to the element."
},
0xcb: {
name: "BlockAdditionID",
cppname: "SliceBlockAddID",
level: 5,
type: "u",
"default": 0,
description: "The ID of the BlockAdditional element (0 is the main Block)."
},
0xcd: {
name: "FrameNumber",
cppname: "SliceFrameNumber",
level: 5,
type: "u",
"default": 0,
description: "The number of the frame to generate from this lace with this delay (allow you to generate many frames from the same Block/Frame)."
},
0xcc: {
name: "LaceNumber",
cppname: "SliceLaceNumber",
level: 5,
type: "u",
minver: 1,
"default": 0,
divx: false,
description: "The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback."
},
0xe8: {
name: "TimeSlice",
level: 4,
type: "m",
multiple: true,
minver: 1,
divx: false,
description: "Contains extra time information about the data contained in the Block. While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback."
},
0x8e: {
name: "Slices",
level: 3,
type: "m",
minver: 1,
divx: false,
description: "Contains slices description."
},
0x75a2: {
name: "DiscardPadding",
level: 3,
type: "i",
minver: 4,
webm: true,
description: "Duration in nanoseconds of the silent data added to the Block (padding at the end of the Block for positive value, at the beginning of the Block for negative value). The duration of DiscardPadding is not calculated in the duration of the TrackEntry and should be discarded during playback."
},
0xa4: {
name: "CodecState",
level: 3,
type: "b",
minver: 2,
webm: false,
description: "The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry."
},
0xfd: {
name: "ReferenceVirtual",
level: 3,
type: "i",
webm: false,
description: "Relative position of the data that should be in position of the virtual block."
},
0xfb: {
name: "ReferenceBlock",
level: 3,
type: "i",
multiple: true,
minver: 1,
description: "Timestamp of another frame used as a reference (ie: B or P frame). The timestamp is relative to the block it's attached to."
},
0xfa: {
name: "ReferencePriority",
cppname: "FlagReferenced",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 0,
description: "This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced."
},
0x9b: {
name: "BlockDuration",
level: 3,
type: "u",
minver: 1,
"default": "TrackDuration",
description: "The duration of the Block (based on TimecodeScale). This element is mandatory when DefaultDuration is set for the track (but can be omitted as other default values). When not written and with no DefaultDuration, the value is assumed to be the difference between the timestamp of this Block and the timestamp of the next Block in \"display\" order (not coding order). This element can be useful at the end of a Track (as there is not other Block available), or when there is a break in a track like for subtitle tracks. When set to 0 that means the frame is not a keyframe."
},
0xa5: {
name: "BlockAdditional",
level: 5,
type: "b",
mandatory: true,
minver: 1,
webm: false,
description: "Interpreted by the codec as it wishes (using the BlockAddID)."
},
0xee: {
name: "BlockAddID",
level: 5,
type: "u",
mandatory: true,
minver: 1,
webm: false,
"default": 1,
range: "not 0",
description: "An ID to identify the BlockAdditional level."
},
0xa6: {
name: "BlockMore",
level: 4,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
webm: false,
description: "Contain the BlockAdditional and some parameters."
},
0x75a1: {
name: "BlockAdditions",
level: 3,
type: "m",
minver: 1,
webm: false,
description: "Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data."
},
0xa2: {
name: "BlockVirtual",
level: 3,
type: "b",
webm: false,
description: "A Block with no data. It must be stored in the stream at the place the real Block should be in display order. (see Block Virtual)"
},
0xa1: {
name: "Block",
level: 3,
type: "b",
mandatory: true,
minver: 1,
description: "Block containing the actual data to be rendered and a timestamp relative to the Cluster Timecode. (see Block Structure)"
},
0xa0: {
name: "BlockGroup",
level: 2,
type: "m",
multiple: true,
minver: 1,
description: "Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock."
},
0xa3: {
name: "SimpleBlock",
level: 2,
type: "b",
multiple: true,
minver: 2,
webm: true,
divx: true,
description: "Similar to SimpleBlock Structure"
},
0xab: {
name: "PrevSize",
cppname: "ClusterPrevSize",
level: 2,
type: "u",
minver: 1,
description: "Size of the previous Cluster, in octets. Can be useful for backward playing.",
position: "prevCluster"
},
0xa7: {
name: "Position",
cppname: "ClusterPosition",
level: 2,
type: "u",
minver: 1,
webm: false,
description: "The Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams.",
position: "segment"
},
0x58d7: {
name: "SilentTrackNumber",
cppname: "ClusterSilentTrackNumber",
level: 3,
type: "u",
multiple: true,
minver: 1,
webm: false,
description: "One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster."
},
0xe7: {
name: "Timecode",
cppname: "ClusterTimecode",
level: 2,
type: "u",
mandatory: true,
minver: 1,
description: "Absolute timestamp of the cluster (based on TimecodeScale)."
},
0x1f43b675: {
name: "Cluster",
level: 1,
type: "m",
multiple: true,
minver: 1,
description: "The lower level element containing the (monolithic) Block structure."
},
0x4d80: {
name: "MuxingApp",
level: 2,
type: "8",
mandatory: true,
minver: 1,
description: "Muxing application or library (\"libmatroska-0.4.3\")."
},
0x7ba9: {
name: "Title",
level: 2,
type: "8",
minver: 1,
webm: false,
description: "General name of the segment."
},
0x2ad7b2: {
name: "TimecodeScaleDenominator",
level: 2,
type: "u",
mandatory: true,
minver: 4,
"default": "1000000000",
description: "Timestamp scale numerator, see TimecodeScale."
},
0x2ad7b1: {
name: "TimecodeScale",
level: 2,
type: "u",
mandatory: true,
minver: 1,
"default": "1000000",
description: "Timestamp scale in nanoseconds (1.000.000 means all timestamps in the segment are expressed in milliseconds)."
},
0x69a5: {
name: "ChapterTranslateID",
level: 3,
type: "b",
mandatory: true,
minver: 1,
webm: false,
description: "The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used."
},
0x69bf: {
name: "ChapterTranslateCodec",
level: 3,
type: "u",
mandatory: true,
minver: 1,
webm: false,
description: "The chapter codec using this ID (0: Matroska Script, 1: DVD-menu)."
},
0x69fc: {
name: "ChapterTranslateEditionUID",
level: 3,
type: "u",
multiple: true,
minver: 1,
webm: false,
description: "Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment."
},
0x3e83bb: {
name: "NextFilename",
level: 2,
type: "8",
minver: 1,
webm: false,
description: "An escaped filename corresponding to the next segment."
},
0x3eb923: {
name: "NextUID",
level: 2,
type: "b",
minver: 1,
webm: false,
bytesize: 16,
description: "A unique ID to identify the next chained segment (128 bits)."
},
0x3c83ab: {
name: "PrevFilename",
level: 2,
type: "8",
minver: 1,
webm: false,
description: "An escaped filename corresponding to the previous segment."
},
0x3cb923: {
name: "PrevUID",
level: 2,
type: "b",
minver: 1,
webm: false,
bytesize: 16,
description: "A unique ID to identify the previous chained segment (128 bits)."
},
0x73a4: {
name: "SegmentUID",
level: 2,
type: "b",
minver: 1,
webm: false,
range: "not 0",
bytesize: 16,
description: "A randomly generated unique ID to identify the current segment between many others (128 bits)."
},
0x1549a966: {
name: "Info",
level: 1,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "Contains miscellaneous general information and statistics on the file."
},
0x53ac: {
name: "SeekPosition",
level: 3,
type: "u",
mandatory: true,
minver: 1,
description: "The position of the element in the segment in octets (0 = first level 1 element).",
position: "segment"
},
0x53ab: {
name: "SeekID",
level: 3,
type: "b",
mandatory: true,
minver: 1,
description: "The binary ID corresponding to the element name.",
type2: "ebmlID"
},
0x4dbb: {
name: "Seek",
cppname: "SeekPoint",
level: 2,
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "Contains a single seek entry to an EBML element."
},
0x114d9b74: {
name: "SeekHead",
cppname: "SeekHeader",
level: 1,
type: "m",
multiple: true,
minver: 1,
description: "Contains the position of other level 1 elements."
},
0x7e7b: {
name: "SignatureElementList",
level: 2,
type: "m",
multiple: true,
webm: false,
i: "Cluster|Block|BlockAdditional",
description: "A list consists of a number of consecutive elements that represent one case where data is used in signature. Ex: means that the BlockAdditional of all Blocks in all Clusters is used for encryption."
},
0x7e5b: {
name: "SignatureElements",
level: 1,
type: "m",
webm: false,
description: "Contains elements that will be used to compute the signature."
},
0x7eb5: {
name: "Signature",
level: 1,
type: "b",
webm: false,
description: "The signature of the data (until a new."
},
0x7ea5: {
name: "SignaturePublicKey",
level: 1,
type: "b",
webm: false,
description: "The public key to use with the algorithm (in the case of a PKI-based signature)."
},
0x7e9a: {
name: "SignatureHash",
level: 1,
type: "u",
webm: false,
description: "Hash algorithm used (1=SHA1-160, 2=MD5)."
},
0x7e8a: {
name: "SignatureAlgo",
level: 1,
type: "u",
webm: false,
description: "Signature algorithm used (1=RSA, 2=elliptic)."
},
0x1b538667: {
name: "SignatureSlot",
level: -1,
type: "m",
multiple: true,
webm: false,
description: "Contain signature of some (coming) elements in the stream."
},
0xbf: {
name: "CRC-32",
level: -1,
type: "b",
minver: 1,
webm: false,
description: "The CRC is computed on all the data of the Master element it's in. The CRC element should be the first in it's parent master for easier reading. All level 1 elements should include a CRC-32. The CRC in use is the IEEE CRC32 Little Endian",
crc: true
},
0xec: {
name: "Void",
level: -1,
type: "b",
minver: 1,
description: "Used to void damaged data, to avoid unexpected behaviors when using damaged data. The content is discarded. Also used to reserve space in a sub-element for later use."
},
0x42f3: {
name: "EBMLMaxSizeLength",
level: 1,
type: "u",
mandatory: true,
"default": 8,
minver: 1,
description: "The maximum length of the sizes you'll find in this file (8 or less in Matroska). This does not override the element size indicated at the beginning of an element. Elements that have an indicated size which is larger than what is allowed by EBMLMaxSizeLength shall be considered invalid."
},
0x42f2: {
name: "EBMLMaxIDLength",
level: 1,
type: "u",
mandatory: true,
"default": 4,
minver: 1,
description: "The maximum length of the IDs you'll find in this file (4 or less in Matroska)."
},
0x42f7: {
name: "EBMLReadVersion",
level: 1,
type: "u",
mandatory: true,
"default": 1,
minver: 1,
description: "The minimum EBML version a parser has to support to read this file."
},
0x1a45dfa3: {
name: "EBML",
level: "0",
type: "m",
mandatory: true,
multiple: true,
minver: 1,
description: "Set the EBML characteristics of the data to follow. Each EBML document has to start with this."
}
};
var byName = {};
var schema = {
byEbmlID: byEbmlID$2,
byName: byName
};
for ( var ebmlID in byEbmlID$2) {
var desc = byEbmlID$2[ebmlID];
byName[desc.name.replace('-', '_')] = parseInt(ebmlID, 10);
}
var schema_1 = schema;
function _classCallCheck$2(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var byEbmlID$1 = schema_1.byEbmlID;
var EBMLEncoder = /*#__PURE__*/ function() {
function EBMLEncoder() {
_classCallCheck$2(this, EBMLEncoder);
this._schema = byEbmlID$1;
this._buffers = [];
this._stack = [];
}
var _proto = EBMLEncoder.prototype;
_proto.encode = function encode(elms) {
var _this = this;
return concat(elms.reduce(function(lst, elm) {
return lst.concat(_this.encodeChunk(elm));
}, [])).buffer;
};
_proto.encodeChunk = function encodeChunk(elm) {
if (elm.type === "m") {
if (!elm.isEnd) {
this.startTag(elm);
} else {
this.endTag(elm);
}
} else {
// ensure that we are working with an internal `Buffer` instance
elm.data = Buffer.from(elm.data);
this.writeTag(elm);
}
return this.flush();
};
_proto.flush = function flush() {
var ret = this._buffers;
this._buffers = [];
return ret;
};
_proto.getSchemaInfo = function getSchemaInfo(tagName) {
var tagNums = Object.keys(this._schema).map(Number);
for(var i = 0; i < tagNums.length; i++){
var tagNum = tagNums[i];
if (this._schema[tagNum].name === tagName) {
return new Buffer(tagNum.toString(16), "hex");
}
}
return null;
};
_proto.writeTag = function writeTag(elm) {
var tagName = elm.name;
var tagId = this.getSchemaInfo(tagName);
var tagData = elm.data;
if (tagId == null) {
throw new Error("No schema entry found for " + tagName);
}
var data = encodeTag(tagId, tagData);
/**
* 親要素が閉じタグあり(isEnd)なら閉じタグが来るまで待つ(children queに入る)
*/ if (this._stack.length > 0) {
var last = this._stack[this._stack.length - 1];
last.children.push({
tagId: tagId,
elm: elm,
children: [],
data: data
});
return;
}
this._buffers = this._buffers.concat(data);
return;
};
_proto.startTag = function startTag(elm) {
var tagName = elm.name;
var tagId = this.getSchemaInfo(tagName);
if (tagId == null) {
throw new Error("No schema entry found for " + tagName);
}
/**
* 閉じタグ不定長の場合はスタックに積まずに即時バッファに書き込む
*/ if (elm.unknownSize) {
var data = encodeTag(tagId, new Buffer(0), elm.unknownSize);
this._buffers = this._buffers.concat(data);
return;
}
var tag = {
tagId: tagId,
elm: elm,
children: [],
data: null
};
if (this._stack.length > 0) {
this._stack[this._stack.length - 1].children.push(tag);
}
this._stack.push(tag);
};
_proto.endTag = function endTag(elm) {
elm.name;
var tag = this._stack.pop();
if (tag == null) {
throw new Error("EBML structure is broken");
}
if (tag.elm.name !== elm.name) {
throw new Error("EBML structure is broken");
}
var childTagDataBuffers = tag.children.reduce(function(lst, child) {
if (child.data === null) {
throw new Error("EBML structure is broken");
}
return lst.concat(child.data);
}, []);
var childTagDataBuffer = concat(childTagDataBuffers);
if (tag.elm.type === "m") {
tag.data = encodeTag(tag.tagId, childTagDataBuffer, tag.elm.unknownSize);
} else {
tag.data = encodeTag(tag.tagId, childTagDataBuffer);
}
if (this._stack.length < 1) {
this._buffers = this._buffers.concat(tag.data);
}
};
return EBMLEncoder;
}();
// https://github.com/themasch/node-ebml/blob/master/lib/ebml/tools.js
var vint$1 = function (buffer, start, signed) {
start = start || 0;
for (var length = 1; length <= 8; length++) {
if (buffer[start] >= Math.pow(2, 8 - length)) {
break
}
}
if (length > 8) {
throw new Error('Unrepresentable length: ' + length + ' ' +
buffer.toString('hex', start, start + length))
}
if (start + length > buffer.length) {
return null
}
var i;
var value = buffer[start] & (1 << (8 - length)) - 1;
for (i = 1; i < length; i++) {
if (i === 7) {
if (value >= Math.pow(2, 53 - 8) && buffer[start + 7] > 0) {
return {
length: length,
value: -1
}
}
}
value *= Math.pow(2, 8);
value += buffer[start + i];
}
if (signed) {
value -= Math.pow(2, length * 7 - 1) - 1;
}
return {
length: length,
value: value
}
};
var vint = vint$1;
function BufferReader (buffer) {
this.buffer = buffer;
this.offset = 0;
}
// a super limited subset of the node buffer API
BufferReader.prototype.nextInt16BE = function () {
var value = this.buffer.readInt16BE(this.offset);
this.offset += 2;
return value
};
BufferReader.prototype.nextUInt8 = function () {
var value = this.buffer.readUInt8(this.offset);
this.offset += 1;
return value
};
// EBML variable sized integers
BufferReader.prototype.nextUIntV = function () {
var v = vint(this.buffer, this.offset);
this.offset += v.length;
return v.value
};
BufferReader.prototype.nextIntV = function () {
var v = vint(this.buffer, this.offset, true);
this.offset += v.length;
return v.value
};
// buffer slice
BufferReader.prototype.nextBuffer = function (length) {
var buffer = length
? this.buffer.slice(this.offset, this.offset + length)
: this.buffer.slice(this.offset);
this.offset += length || this.length;
return buffer
};
// remaining bytes to read
Object.defineProperty(BufferReader.prototype, 'length', {
get: function () { return this.buffer.length - this.offset }
});
function _instanceof$1(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
var _tools = {
readVint: function readVint(buffer, start) {
start = start || 0;
for(var _$length = 1; _$length <= 8; _$length++){
if (buffer[start] >= Math.pow(2, 8 - _$length)) {
break;
}
}
if (length > 8) {
throw new Error("Unrepresentable length: " + length + " " + buffer.toString("hex", start, start + length));
}
if (start + length > buffer.length) {
return null;
}
var value = buffer[start] & (1 << 8 - length) - 1;
for(var i = 1; i < length; i++){
if (i === 7) {
if (value >= Math.pow(2, 53 - 8) && buffer[start + 7] > 0) {
return {
length: length,
value: -1
};
}
}
value *= Math.pow(2, 8);
value += buffer[start + i];
}
return {
length: length,
value: value
};
},
writeVint: function writeVint(value) {
if (value < 0 || value > Math.pow(2, 53)) {
throw new Error("Unrepresentable value: " + value);
}
var buffer = Buffer.alloc(length);
for(var i = 1; i <= length; i++){
var b = value & 0xFF;
buffer[length - i] = b;
value -= b;
value /= Math.pow(2, 8);
}
buffer[0] = buffer[0] | 1 << 8 - length;
return buffer;
}
};
var readVint = _tools.readVint;
var writeVint = _tools.writeVint;
/**
* @param end - if end === false then length is unknown
*/ function encodeTag(tagId, tagData) {
var unknownSize = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
return concat([
tagId,
unknownSize ? Buffer.from("01ffffffffffffff", "hex") : writeVint(tagData.length),
tagData
]);
}
function concat(list) {
return Buffer.concat(list);
}
function convertEBMLDateToJSDate(int64str) {
if (_instanceof$1(int64str, Date)) {
return int64str;
}
return new Date(new Date("2001-01-01T00:00:00.000Z").getTime() + Number(int64str) / 1000 / 1000);
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var byEbmlID = schema_1.byEbmlID;
var // https://www.matroska.org/technical/specs/index.html
State$1;
(function(State) {
State[State["STATE_TAG"] = 1] = "STATE_TAG";
State[State["STATE_SIZE"] = 2] = "STATE_SIZE";
State[State["STATE_CONTENT"] = 3] = "STATE_CONTENT";
})(State$1 || (State$1 = {}));
var EBMLDecoder = /*#__PURE__*/ function() {
function EBMLDecoder() {
_classCallCheck$1(this, EBMLDecoder);
this._buffer = new Buffer(0);
this._tag_stack = [];
this._state = State$1.STATE_TAG;
this._cursor = 0;
this._total = 0;
this._schema = byEbmlID;
this._result = [];
}
var _proto = EBMLDecoder.prototype;
_proto.decode = function decode(chunk) {
this.readChunk(chunk);
var diff = this._result;
this._result = [];
return diff;
};
_proto.readChunk = function readChunk(chunk) {
// 読みかけの(読めなかった) this._buffer と 新しい chunk を合わせて読み直す
this._buffer = concat([
this._buffer,
new Buffer(chunk)
]);
while(this._cursor < this._buffer.length){
// console.log(this._cursor, this._total, this._tag_stack);
if (this._state === State$1.STATE_TAG && !this.readTag()) {
break;
}
if (this._state === State$1.STATE_SIZE && !this.readSize()) {
break;
}
if (this._state === State$1.STATE_CONTENT && !this.readContent()) {
break;
}
}
};
_proto.getSchemaInfo = function getSchemaInfo(tagNum) {
return this._schema[tagNum] || {
name: "unknown",
level: -1,
type: "unknown",
description: "unknown"
};
};
/**
* vint された parsing tag
* @return - return false when waiting for more data
*/ _proto.readTag = function readTag() {
// tag.length が buffer の外にある
if (this._cursor >= this._buffer.length) {
return false;
}
// read ebml id vint without first byte
var tag = readVint(this._buffer, this._cursor);
// tag が読めなかった
if (tag == null) {
return false;
}
// >>>>>>>>>
// tag 識別子
//const tagStr = this._buffer.toString("hex", this._cursor, this._cursor + tag.length);
//const tagNum = parseInt(tagStr, 16);
// 上と等価
var buf = this._buffer.slice(this._cursor, this._cursor + tag.length);
var tagNum = buf.reduce(function(o, v, i, arr) {
return o + v * Math.pow(16, 2 * (arr.length - 1 - i));
}, 0);
var _$schema = this.getSchemaInfo(tagNum);
var tagObj = {
EBML_ID: tagNum.toString(16),
schema: _$schema,
type: _$schema.type,
name: _$schema.name,
level: _$schema.level,
tagStart: this._total,
tagEnd: this._total + tag.length,
sizeStart: this._total + tag.length,
sizeEnd: null,
dataStart: null,
dataEnd: null,
dataSize: null,
data: null
};
// | tag: vint | size: vint | data: Buffer(size) |
this._tag_stack.push(tagObj);
// <<<<<<<<
// ポインタを進める
this._cursor += tag.length;
this._total += tag.length;
// 読み込み状態変更
this._state = State$1.STATE_SIZE;
return true;
};
/**
* vint された現在のタグの内容の大きさを読み込む
* @return - return false when waiting for more data
*/ _proto.readSize = function readSize() {
// tag.length が buffer の外にある
if (this._cursor >= this._buffer.length) {
return false;
}
// read ebml datasize vint without first byte
var size = readVint(this._buffer, this._cursor);
// まだ読めない
if (size == null) {
return false;
}
// >>>>>>>>>
// current tag の data size 決定
var tagObj = this._tag_stack[this._tag_stack.length - 1];
tagObj.sizeEnd = tagObj.sizeStart + size.length;
tagObj.dataStart = tagObj.sizeEnd;
tagObj.dataSize = size.value;
if (size.value === -1) {
// unknown size
tagObj.dataEnd = -1;
if (tagObj.type === "m") {
tagObj.unknownSize = true;
}
} else {
tagObj.dataEnd = tagObj.sizeEnd + size.value;
}
// <<<<<<<<
// ポインタを進める
this._cursor += size.length;
this._total += size.length;
this._state = State$1.STATE_CONTENT;
return true;
};
/**
* データ読み込み
*/ _proto.readContent = function readContent() {
var tagObj = this._tag_stack[this._tag_stack.length - 1];
// master element は子要素を持つので生データはない
if (tagObj.type === "m") {
// console.log('content should be tags');
tagObj.isEnd = false;
this._result.push(tagObj);
this._state = State$1.STATE_TAG;
// この Mastert Element は空要素か
if (tagObj.dataSize === 0) {
// 即座に終了タグを追加
var elm = Object.assign({}, tagObj, {
isEnd: true
});
this._result.push(elm);
this._tag_stack.pop(); // スタックからこのタグを捨てる
}
return true;
}
// waiting for more data
if (this._buffer.length < this._cursor + tagObj.dataSize) {
return false;
}
// タグの中身の生データ
var data = this._buffer.slice(this._cursor, this._cursor + tagObj.dataSize);
// 読み終わったバッファを捨てて読み込んでいる部分のバッファのみ残す
this._buffer = this._buffer.slice(this._cursor + tagObj.dataSize);
tagObj.data = data;
// >>>>>>>>>
switch(tagObj.type){
//case "m": break;
// Master-Element - contains other EBML sub-elements of the next lower level
case "u":
tagObj.value = data.readUIntBE(0, data.length);
break;
// Unsigned Integer - Big-endian, any size from 1 to 8 octets
case "i":
tagObj.value = data.readIntBE(0, data.length);
break;
// Signed Integer - Big-endian, any size from 1 to 8 octets
case "f":
tagObj.value = tagObj.dataSize === 4 ? data.readFloatBE(0) : tagObj.dataSize === 8 ? data.readDoubleBE(0) : (console.warn("cannot read ".concat(tagObj.dataSize, " octets float. failback to 0")), 0);
break;
// Float - Big-endian, defined for 4 and 8 octets (32, 64 bits)
case "s":
tagObj.value = data.toString("ascii");
break; // ascii
// Printable ASCII (0x20 to 0x7E), zero-padded when needed
case "8":
tagObj.value = data.toString("utf8");
break;
// Unicode string, zero padded when needed (RFC 2279)
case "b":
tagObj.value = data;
break;
// Binary - not interpreted by the parser
case "d":
tagObj.value = convertEBMLDateToJSDate(new Int64BE(data).toNumber());
break;
}
if (tagObj.value === null) {
throw new Error("unknown tag type:" + tagObj.type);
}
this._result.push(tagObj);
// <<<<<<<<
// ポインタを進める
this._total += tagObj.dataSize;
// タグ待ちモードに変更
this._state = State$1.STATE_TAG;
this._cursor = 0;
this._tag_stack.pop(); // remove the object from the stack
while(this._tag_stack.length > 0){
var topEle = this._tag_stack[this._tag_stack.length - 1];
// 親が不定長サイズなので閉じタグは期待できない
if (topEle.dataEnd < 0) {
this._tag_stack.pop(); // 親タグを捨てる
return true;
}
// 閉じタグの来るべき場所まで来たかどうか
if (this._total < topEle.dataEnd) {
break;
}
// 閉じタグを挿入すべきタイミングが来た
if (topEle.type !== "m") {
throw new Error("parent element is not master element");
}
var elm1 = Object.assign({}, topEle, {
isEnd: true
});
this._result.push(elm1);
this._tag_stack.pop();
}
return true;
};
return EBMLDecoder;
}();
function _arrayLikeToArray$4(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithoutHoles$2(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$4(arr);
}
function asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$6(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArray$2(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread$2() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray$2(arr) {
return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _unsupportedIterableToArray$4(arr) || _nonIterableSpread$2();
}
function _unsupportedIterableToArray$4(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$4(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen);
}
// unused, but will in case 4chan does file sig checks
Buffer$1.from("NOA");
var findEnclosingTag = function(ch, name) {
var first = ch.findIndex(function(e) {
return e.type == "m" && e.name == name;
});
if (first < 0) return;
var second = ch.slice(first).findIndex(function(e) {
return e.type == "m" && e.name == name;
});
if (second < 0) return;
return [
first,
first + second
];
};
var embed = function(webm, data) {
var _chunks1;
var dec = new EBMLDecoder();
var chunks = dec.decode(webm);
var enc = new EBMLEncoder();
var embed1 = chunks.findIndex(function(e) {
return e.name == "Tracks" && e.type == "m" && e.isEnd;
});
var findOrInsert = function(n) {
var tags = findEnclosingTag(chunks, n);
var stack = [];
if (!tags) {
var _chunks;
stack.push({
type: "m",
isEnd: false,
name: n,
data: Buffer$1.from("")
});
stack.push({
type: "m",
isEnd: true,
name: n,
data: Buffer$1.from("")
});
(_chunks = chunks).splice.apply(_chunks, [
embed1 + 1,
0
].concat(_toConsumableArray$2(stack)));
tags = findEnclosingTag(chunks, n);
}
embed1 = tags[1];
};
findOrInsert("Tags");
findOrInsert("Tag");
findOrInsert("Targets");
embed1++;
(_chunks1 = chunks).splice.apply(_chunks1, [
embed1 + 1,
0,
{
type: "m",
isEnd: false,
name: "SimpleTag",
data: Buffer$1.from("")
},
{
type: "8",
isEnd: false,
name: "TagName",
data: Buffer$1.from("DOOM")
},
{
type: "8",
isEnd: false,
name: "TagBinary",
data: data
},
{
type: "m",
isEnd: true,
name: "SimpleTag",
data: Buffer$1.from("")
}
]);
return Buffer$1.from(enc.encode(chunks.filter(function(e) {
return e.name != "unknown";
})));
};
var extract$3 = function(webm) {
var dec = new EBMLDecoder();
var chunks = dec.decode(webm);
var embed2 = chunks.findIndex(function(e) {
return e.name == "TagName" && e.type == "8" && e.value == "DOOM";
});
var cl = chunks.find(function(e) {
return e.name == "Cluster";
});
if (cl && embed2 == -1) return;
if (embed2 == -1) return;
var chk = chunks[embed2 + 1];
if (chk.type == "b" && chk.name == "TagBinary") return decodeCoom3Payload(chk.data);
};
var inject$2 = function() {
var _ref = _asyncToGenerator$6(regeneratorRuntime$1.mark(function _callee(container, links) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.t0 = embed;
_ctx.t1 = Buffer$1;
_ctx.next = 4;
return container.arrayBuffer();
case 4:
_ctx.t2 = _ctx.sent;
_ctx.t3 = _ctx.t1.from.call(_ctx.t1, _ctx.t2);
_ctx.t4 = Buffer$1.from(links.join(" "));
return _ctx.abrupt("return", (0, _ctx.t0)(_ctx.t3, _ctx.t4));
case 8:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function inject(container, links) {
return _ref.apply(this, arguments);
};
}();
var has_embed$3 = function(webm) {
var dec = new EBMLDecoder();
var chunks = dec.decode(webm);
var embed3 = chunks.findIndex(function(e) {
return e.name == "TagName" && e.type == "8" && e.value == "DOOM";
});
var cl = chunks.find(function(e) {
return e.name == "Cluster";
});
if (cl && embed3 == -1) return false; // Tags appear before Cluster, so if we have a Cluster and no coomtag, then it's a definite no
if (embed3 == -1) return;
return true;
};
var webm = {
extract: extract$3,
has_embed: has_embed$3,
inject: inject$2,
match: function(fn) {
return !!fn.match(/\.webm$/);
}
};
function _arrayLikeToArray$3(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles$2(arr) {
if (Array.isArray(arr)) return arr;
}
function asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$5(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArrayLimit$2(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$2() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray$2(arr, i) {
return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _unsupportedIterableToArray$3(arr, i) || _nonIterableRest$2();
}
function _unsupportedIterableToArray$3(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$3(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen);
}
var netscape = Buffer$1.from("!\xff\vNETSCAPE2.0", "ascii");
var magic = Buffer$1.from("!\xff\v" + "DOOMTECH1.1", "ascii");
var read_section = function(gif, pos) {
var begin = pos;
pos += 3 + gif[pos + 2];
var buf = Buffer$1.alloc(0);
while(pos < gif.byteLength){
var v = gif[pos++];
buf = Buffer$1.concat([
buf,
gif.slice(pos, pos + v)
]);
if (v == 0) break;
pos += v;
}
var appname = gif.slice(begin + 3, begin + 11).toString("ascii");
return {
appname: appname,
data: buf,
end: pos
};
};
var extractBuff = function(gif) {
var field = gif.readUInt8(10);
var gcte = !!(field & 1 << 7);
var end = 13;
if (gcte) {
end += 3 * (1 << (field & 7) + 1);
}
// skip beeg blocks
while(gif[end] == "!".charCodeAt(0)){
var sec = read_section(gif, end); // this section contains the size to more easily preallocate a buffer size, but you don't need to care care
if (sec.appname == "DOOMTECH") {
var ret = Buffer$1.alloc(sec.data.readInt32LE(0));
var ptr = 0;
do {
sec = read_section(gif, sec.end);
sec.data.copy(ret, ptr);
ptr += sec.data.byteLength;
end = sec.end;
}while (sec.appname == "DOOMTECH" && gif[end] == "!".charCodeAt(0));
return decodeCoom3Payload(ret);
}
end = sec.end;
}
throw new Error("Shouldn't happen");
// metadata ended, nothing...
};
var extract$2 = extractBuff;
var write_data = function() {
var _ref = _asyncToGenerator$5(regeneratorRuntime$1.mark(function _callee(writer, inj) {
var byte, size, ws, offset;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return writer.write(magic);
case 2:
byte = Buffer$1.from([
0
]);
size = inj.byteLength;
offset = 0;
case 6:
if (!(size != 0)) {
_ctx.next = 17;
break;
}
ws = size >= 255 ? 255 : size;
byte.writeUInt8(ws, 0);
_ctx.next = 11;
return writer.write(byte);
case 11:
_ctx.next = 13;
return writer.write(inj.slice(offset, offset + ws));
case 13:
size -= ws;
offset += ws;
_ctx.next = 6;
break;
case 17:
byte.writeUInt8(0, 0);
_ctx.next = 20;
return writer.write(byte);
case 20:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function write_data(writer, inj) {
return _ref.apply(this, arguments);
};
}();
var write_embedding = function() {
var _ref = _asyncToGenerator$5(regeneratorRuntime$1.mark(function _callee(writer, inj) {
var b, size, offset, ws;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
b = Buffer$1.alloc(4);
b.writeInt32LE(inj.byteLength, 0);
_ctx.next = 4;
return write_data(writer, b);
case 4:
size = inj.byteLength;
offset = 0;
case 6:
if (!(size != 0)) {
_ctx.next = 14;
break;
}
ws = size >= 3 << 13 ? 3 << 13 : size;
_ctx.next = 10;
return write_data(writer, inj.slice(offset, offset + ws));
case 10:
offset += ws;
size -= ws;
_ctx.next = 6;
break;
case 14:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function write_embedding(writer, inj) {
return _ref.apply(this, arguments);
};
}();
var inject$1 = function() {
var _ref = _asyncToGenerator$5(regeneratorRuntime$1.mark(function _callee(container, links) {
var ref, writestream, extract1, writer, inj, contbuff, field, gcte, endo;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
ref = _slicedToArray$2(BufferWriteStream$1(), 2), writestream = ref[0], extract1 = ref[1];
writer = writestream.getWriter();
inj = Buffer$1.from(links.join(" "));
_ctx.t0 = Buffer$1;
_ctx.next = 6;
return container.arrayBuffer();
case 6:
_ctx.t1 = _ctx.sent;
contbuff = _ctx.t0.from.call(_ctx.t0, _ctx.t1);
field = contbuff.readUInt8(10);
gcte = !!(field & 1 << 0x7);
endo = 13;
if (gcte) endo += 3 * (1 << (field & 7) + 1);
if (netscape.compare(contbuff, endo, endo + netscape.byteLength) == 0) endo += 19;
_ctx.next = 15;
return writer.write(contbuff.slice(0, endo));
case 15:
_ctx.next = 17;
return write_embedding(writer, Buffer$1.from(inj));
case 17:
_ctx.next = 19;
return writer.write(contbuff.slice(endo));
case 19:
return _ctx.abrupt("return", extract1());
case 20:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function inject(container, links) {
return _ref.apply(this, arguments);
};
}();
var has_embed$2 = function(gif) {
var field = gif.readUInt8(10);
var gcte = !!(field & 1 << 7);
var end = 13;
if (gcte) {
end += 3 * (1 << (field & 7) + 1);
}
// skip beeg blocks
while(end < gif.byteLength && gif.readUInt8(end) == "!".charCodeAt(0)){
if (magic.compare(gif, end, end + magic.byteLength) != 0) {
end += 3 + gif.readUInt8(end + 2);
// eslint-disable-next-line no-constant-condition
while(true){
var v = gif.readUInt8(end++);
if (!v) break;
end += v;
}
} else {
return true;
}
}
if (end >= gif.byteLength) return; // Don't know yet, need more to decide.
return false; // no more extension blocks, so definite no
};
var gif = {
extract: extract$2,
has_embed: has_embed$2,
inject: inject$1,
match: function(fn) {
return !!fn.match(/\.gif$/);
}
};
function asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$4(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var convertToPng = function() {
var _ref = _asyncToGenerator$4(regeneratorRuntime$1.mark(function _callee(f) {
var can, url, dims, source, imgElem, vidElem, ctx, blob;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
can = document.createElement("canvas");
url = URL.createObjectURL(f);
_ctx.prev = 2;
if (!f.type.startsWith("image")) {
_ctx.next = 14;
break;
}
imgElem = document.createElement("img");
imgElem.src = url;
_ctx.next = 10;
return new Promise(function(_) {
return imgElem.onload = _;
});
case 10:
dims = [
imgElem.naturalWidth,
imgElem.naturalHeight
];
source = imgElem;
_ctx.next = 33;
break;
case 14:
if (!f.type.startsWith("video")) {
_ctx.next = 32;
break;
}
vidElem = document.createElement("video");
vidElem.src = url;
_ctx.next = 19;
return new Promise(function(_) {
return vidElem.onloadedmetadata = _;
});
case 19:
vidElem.currentTime = 0;
_ctx.next = 22;
return new Promise(function(_) {
return vidElem.onloadeddata = _;
});
case 22:
_ctx.next = 24;
return new Promise(requestAnimationFrame);
case 24:
_ctx.next = 26;
return new Promise(requestAnimationFrame);
case 26:
_ctx.next = 28;
return new Promise(requestAnimationFrame);
case 28:
dims = [
vidElem.videoWidth,
vidElem.videoHeight
];
source = vidElem;
_ctx.next = 33;
break;
case 32:
return _ctx.abrupt("return");
case 33:
can.width = dims[0];
can.height = dims[1];
ctx = can.getContext("2d");
if (ctx) {
_ctx.next = 38;
break;
}
return _ctx.abrupt("return");
case 38:
ctx.drawImage(source, 0, 0, dims[0], dims[1]);
_ctx.next = 41;
return new Promise(function(_) {
return can.toBlob(_, "image/png");
});
case 41:
blob = _ctx.sent;
if (blob) {
_ctx.next = 44;
break;
}
return _ctx.abrupt("return");
case 44:
return _ctx.abrupt("return", blob);
case 45:
_ctx.prev = 45;
URL.revokeObjectURL(url);
return _ctx.finish(45);
case 48:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
2,
,
45,
48
]
]);
}));
return function convertToPng(f) {
return _ref.apply(this, arguments);
};
}();
var inject = function() {
var _ref = _asyncToGenerator$4(regeneratorRuntime$1.mark(function _callee(b, links) {
var pngfile;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return convertToPng(b);
case 2:
pngfile = _ctx.sent;
if (!(!pngfile || pngfile.size > 3000 * 1024)) {
_ctx.next = 5;
break;
}
throw new Error("Couldn't convert file to PNG: resulting filesize too big.");
case 5:
return _ctx.abrupt("return", pngv3.inject(new File([
pngfile
], b.name), links));
case 6:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function inject(b, links) {
return _ref.apply(this, arguments);
};
}();
var jpg = {
skip: true,
match: function(fn) {
return !!fn.match(/\.jpe?g$/);
},
has_embed: function() {
return false;
},
extract: function() {
return [];
},
inject: inject
};
function JPEGEncoder(quality) {
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
var std_ac_luminance_values = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
var std_ac_chrominance_values = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
function initQuantTables(sf){
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j]*sf+50)/100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++)
{
for (var col = 0; col < 8; col++)
{
fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table){
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
function initHuffmanTbl()
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
function initCategoryNumber()
{
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr<nrupper; nr++) {
category[32767+nr] = cat;
bitcode[32767+nr] = [];
bitcode[32767+nr][1] = cat;
bitcode[32767+nr][0] = nr;
}
//Negative numbers
for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) {
category[32767+nrneg] = cat;
bitcode[32767+nrneg] = [];
bitcode[32767+nrneg][1] = cat;
bitcode[32767+nrneg][0] = nrupper-1+nrneg;
}
nrlower <<= 1;
nrupper <<= 1;
}
}
function initRGBYUVTable() {
for(var i = 0; i < 256;i++) {
RGB_YUV_TABLE[i] = 19595 * i;
RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i;
RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs)
{
var value = bs[0];
var posval = bs[1]-1;
while ( posval >= 0 ) {
if (value & (1 << posval) ) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
function writeByte(value)
{
//byteout.push(clt[value]); // write char directly instead of converting later
byteout.push(value);
}
function writeWord(value)
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl)
{
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff=0;
var i;
var I8 = 8;
var I64 = 64;
for (i=0; i<I8; ++i)
{
d0 = data[dataOff];
d1 = data[dataOff+1];
d2 = data[dataOff+2];
d3 = data[dataOff+3];
d4 = data[dataOff+4];
d5 = data[dataOff+5];
d6 = data[dataOff+6];
d7 = data[dataOff+7];
var tmp0 = d0 + d7;
var tmp7 = d0 - d7;
var tmp1 = d1 + d6;
var tmp6 = d1 - d6;
var tmp2 = d2 + d5;
var tmp5 = d2 - d5;
var tmp3 = d3 + d4;
var tmp4 = d3 - d4;
/* Even part */
var tmp10 = tmp0 + tmp3; /* phase 2 */
var tmp13 = tmp0 - tmp3;
var tmp11 = tmp1 + tmp2;
var tmp12 = tmp1 - tmp2;
data[dataOff] = tmp10 + tmp11; /* phase 3 */
data[dataOff+4] = tmp10 - tmp11;
var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
data[dataOff+2] = tmp13 + z1; /* phase 5 */
data[dataOff+6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
var z3 = tmp11 * 0.707106781; /* c4 */
var z11 = tmp7 + z3; /* phase 5 */
var z13 = tmp7 - z3;
data[dataOff+5] = z13 + z2; /* phase 6 */
data[dataOff+3] = z13 - z2;
data[dataOff+1] = z11 + z4;
data[dataOff+7] = z11 - z4;
dataOff += 8; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataOff = 0;
for (i=0; i<I8; ++i)
{
d0 = data[dataOff];
d1 = data[dataOff + 8];
d2 = data[dataOff + 16];
d3 = data[dataOff + 24];
d4 = data[dataOff + 32];
d5 = data[dataOff + 40];
d6 = data[dataOff + 48];
d7 = data[dataOff + 56];
var tmp0p2 = d0 + d7;
var tmp7p2 = d0 - d7;
var tmp1p2 = d1 + d6;
var tmp6p2 = d1 - d6;
var tmp2p2 = d2 + d5;
var tmp5p2 = d2 - d5;
var tmp3p2 = d3 + d4;
var tmp4p2 = d3 - d4;
/* Even part */
var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
var tmp13p2 = tmp0p2 - tmp3p2;
var tmp11p2 = tmp1p2 + tmp2p2;
var tmp12p2 = tmp1p2 - tmp2p2;
data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
data[dataOff+32] = tmp10p2 - tmp11p2;
var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */
data[dataOff+48] = tmp13p2 - z1p2;
/* Odd part */
tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
tmp11p2 = tmp5p2 + tmp6p2;
tmp12p2 = tmp6p2 + tmp7p2;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
var z3p2 = tmp11p2 * 0.707106781; /* c4 */
var z11p2 = tmp7p2 + z3p2; /* phase 5 */
var z13p2 = tmp7p2 - z3p2;
data[dataOff+40] = z13p2 + z2p2; /* phase 6 */
data[dataOff+24] = z13p2 - z2p2;
data[dataOff+ 8] = z11p2 + z4p2;
data[dataOff+56] = z11p2 - z4p2;
dataOff++; /* advance pointer to next column */
}
// Quantize/descale the coefficients
var fDCTQuant;
for (i=0; i<I64; ++i)
{
// Apply the quantization and scaling factor & Round to nearest integer
fDCTQuant = data[i]*fdtbl[i];
outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0()
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeAPP1(exifBuffer) {
if (!exifBuffer) return;
writeWord(0xFFE1); // APP1 marker
if (exifBuffer[0] === 0x45 &&
exifBuffer[1] === 0x78 &&
exifBuffer[2] === 0x69 &&
exifBuffer[3] === 0x66) {
// Buffer already starts with EXIF, just use it directly
writeWord(exifBuffer.length + 2); // length is buffer + length itself!
} else {
// Buffer doesn't start with EXIF, write it for them
writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself!
writeByte(0x45); // E
writeByte(0x78); // X
writeByte(0x69); // I
writeByte(0x66); // F
writeByte(0); // = "EXIF",'\0'
}
for (var i = 0; i < exifBuffer.length; i++) {
writeByte(exifBuffer[i]);
}
}
function writeSOF0(width, height)
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT()
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j=0; j<64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT()
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (var j=0; j<=11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k=0; k<16; k++) {
writeByte(std_ac_luminance_nrcodes[k+1]);
}
for (var l=0; l<=161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m=0; m<16; m++) {
writeByte(std_dc_chrominance_nrcodes[m+1]);
}
for (var n=0; n<=11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o=0; o<16; o++) {
writeByte(std_ac_chrominance_nrcodes[o+1]);
}
for (var p=0; p<=161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeSOS()
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC){
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j=0;j<I64;++j) {
DU[ZigZag[j]]=DU_DCT[j];
}
var Diff = DU[0] - DC; DC = DU[0];
//Encode DC
if (Diff==0) {
writeBits(HTDC[0]); // Diff might be 0
} else {
pos = 32767+Diff;
writeBits(HTDC[category[pos]]);
writeBits(bitcode[pos]);
}
//Encode ACs
var end0pos = 63; // was const... which is crazy
for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {} //end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while ( i <= end0pos ) {
var startpos = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes&0xF;
}
pos = 32767+DU[i];
writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable(){
var sfcc = String.fromCharCode;
for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function(image,quality) // image data object
{
new Date().getTime();
if(quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeAPP1(image.exifBuffer);
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY=0;
var DCU=0;
var DCV=0;
bytenew=0;
bytepos=7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width*4;
var x, y = 0;
var r, g, b;
var start,p, col,row,pos;
while(y < height){
x = 0;
while(x < quadWidth){
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for(pos=0; pos < 64; pos++){
row = pos >> 3;// /8
col = ( pos & 7 ) * 4; // %8
p = start + ( row * quadWidth ) + col;
if(y+row >= height){ // padding bottom
p-= (quadWidth*(y+1+row-height));
}
if(x+col >= quadWidth){ // padding right
p-= ((x+col) - quadWidth +4);
}
r = imageData[ p++ ];
g = imageData[ p++ ];
b = imageData[ p++ ];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x+=32;
}
y+=8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits = [];
fillbits[1] = bytepos+1;
fillbits[0] = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
if (typeof module === 'undefined') return new Uint8Array(byteout);
return Buffer$1.from(byteout);
};
function setQuality(quality){
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if(currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality*2);
}
initQuantTables(sf);
currentQuality = quality;
//console.log('Quality set to: '+quality +'%');
}
function init(){
var time_start = new Date().getTime();
if(!quality) quality = 50;
// Create tables
initCharLookupTable();
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
new Date().getTime() - time_start;
//console.log('Initialization '+ duration + 'ms');
}
init();
}
if (typeof module !== 'undefined') {
module.exports = encode$1;
} else if (typeof window !== 'undefined') {
window['jpeg-js'] = window['jpeg-js'] || {};
window['jpeg-js'].encode = encode$1;
}
function encode$1(imgData, qu) {
if (typeof qu === 'undefined') qu = 50;
var encoder = new JPEGEncoder(qu);
var data = encoder.encode(imgData, qu);
return {
data: data,
width: imgData.width,
height: imgData.height
};
}
var encoder = /*#__PURE__*/Object.freeze({
__proto__: null
});
var require$$0 = /*@__PURE__*/getAugmentedNamespace(encoder);
/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
Copyright 2011 notmasteryet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// - The JPEG specification can be found in the ITU CCITT Recommendation T.81
// (www.w3.org/Graphics/JPEG/itu-t81.pdf)
// - The JFIF specification can be found in the JPEG File Interchange Format
// (www.w3.org/Graphics/JPEG/jfif3.pdf)
// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
// in PostScript Level 2, Technical Note #5116
// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)
var JpegImage = (function jpegImage() {
var dctZigZag = new Int32Array([
0,
1, 8,
16, 9, 2,
3, 10, 17, 24,
32, 25, 18, 11, 4,
5, 12, 19, 26, 33, 40,
48, 41, 34, 27, 20, 13, 6,
7, 14, 21, 28, 35, 42, 49, 56,
57, 50, 43, 36, 29, 22, 15,
23, 30, 37, 44, 51, 58,
59, 52, 45, 38, 31,
39, 46, 53, 60,
61, 54, 47,
55, 62,
63
]);
var dctCos1 = 4017; // cos(pi/16)
var dctSin1 = 799; // sin(pi/16)
var dctCos3 = 3406; // cos(3*pi/16)
var dctSin3 = 2276; // sin(3*pi/16)
var dctCos6 = 1567; // cos(6*pi/16)
var dctSin6 = 3784; // sin(6*pi/16)
var dctSqrt2 = 5793; // sqrt(2)
var dctSqrt1d2 = 2896; // sqrt(2) / 2
function constructor() {
}
function buildHuffmanTable(codeLengths, values) {
var k = 0, code = [], i, j, length = 16;
while (length > 0 && !codeLengths[length - 1])
length--;
code.push({children: [], index: 0});
var p = code[0], q;
for (i = 0; i < length; i++) {
for (j = 0; j < codeLengths[i]; j++) {
p = code.pop();
p.children[p.index] = values[k];
while (p.index > 0) {
if (code.length === 0)
throw new Error('Could not recreate Huffman Table');
p = code.pop();
}
p.index++;
code.push(p);
while (code.length <= i) {
code.push(q = {children: [], index: 0});
p.children[p.index] = q.children;
p = q;
}
k++;
}
if (i + 1 < length) {
// p here points to last code
code.push(q = {children: [], index: 0});
p.children[p.index] = q.children;
p = q;
}
}
return code[0].children;
}
function decodeScan(data, offset,
frame, components, resetInterval,
spectralStart, spectralEnd,
successivePrev, successive, opts) {
frame.precision;
frame.samplesPerLine;
frame.scanLines;
var mcusPerLine = frame.mcusPerLine;
var progressive = frame.progressive;
frame.maxH; frame.maxV;
var startOffset = offset, bitsData = 0, bitsCount = 0;
function readBit() {
if (bitsCount > 0) {
bitsCount--;
return (bitsData >> bitsCount) & 1;
}
bitsData = data[offset++];
if (bitsData == 0xFF) {
var nextByte = data[offset++];
if (nextByte) {
throw new Error("unexpected marker: " + ((bitsData << 8) | nextByte).toString(16));
}
// unstuff 0
}
bitsCount = 7;
return bitsData >>> 7;
}
function decodeHuffman(tree) {
var node = tree, bit;
while ((bit = readBit()) !== null) {
node = node[bit];
if (typeof node === 'number')
return node;
if (typeof node !== 'object')
throw new Error("invalid huffman sequence");
}
return null;
}
function receive(length) {
var n = 0;
while (length > 0) {
var bit = readBit();
if (bit === null) return;
n = (n << 1) | bit;
length--;
}
return n;
}
function receiveAndExtend(length) {
var n = receive(length);
if (n >= 1 << (length - 1))
return n;
return n + (-1 << length) + 1;
}
function decodeBaseline(component, zz) {
var t = decodeHuffman(component.huffmanTableDC);
var diff = t === 0 ? 0 : receiveAndExtend(t);
zz[0]= (component.pred += diff);
var k = 1;
while (k < 64) {
var rs = decodeHuffman(component.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15)
break;
k += 16;
continue;
}
k += r;
var z = dctZigZag[k];
zz[z] = receiveAndExtend(s);
k++;
}
}
function decodeDCFirst(component, zz) {
var t = decodeHuffman(component.huffmanTableDC);
var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
zz[0] = (component.pred += diff);
}
function decodeDCSuccessive(component, zz) {
zz[0] |= readBit() << successive;
}
var eobrun = 0;
function decodeACFirst(component, zz) {
if (eobrun > 0) {
eobrun--;
return;
}
var k = spectralStart, e = spectralEnd;
while (k <= e) {
var rs = decodeHuffman(component.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15) {
eobrun = receive(r) + (1 << r) - 1;
break;
}
k += 16;
continue;
}
k += r;
var z = dctZigZag[k];
zz[z] = receiveAndExtend(s) * (1 << successive);
k++;
}
}
var successiveACState = 0, successiveACNextValue;
function decodeACSuccessive(component, zz) {
var k = spectralStart, e = spectralEnd, r = 0;
while (k <= e) {
var z = dctZigZag[k];
var direction = zz[z] < 0 ? -1 : 1;
switch (successiveACState) {
case 0: // initial state
var rs = decodeHuffman(component.huffmanTableAC);
var s = rs & 15, r = rs >> 4;
if (s === 0) {
if (r < 15) {
eobrun = receive(r) + (1 << r);
successiveACState = 4;
} else {
r = 16;
successiveACState = 1;
}
} else {
if (s !== 1)
throw new Error("invalid ACn encoding");
successiveACNextValue = receiveAndExtend(s);
successiveACState = r ? 2 : 3;
}
continue;
case 1: // skipping r zero items
case 2:
if (zz[z])
zz[z] += (readBit() << successive) * direction;
else {
r--;
if (r === 0)
successiveACState = successiveACState == 2 ? 3 : 0;
}
break;
case 3: // set value for a zero item
if (zz[z])
zz[z] += (readBit() << successive) * direction;
else {
zz[z] = successiveACNextValue << successive;
successiveACState = 0;
}
break;
case 4: // eob
if (zz[z])
zz[z] += (readBit() << successive) * direction;
break;
}
k++;
}
if (successiveACState === 4) {
eobrun--;
if (eobrun === 0)
successiveACState = 0;
}
}
function decodeMcu(component, decode, mcu, row, col) {
var mcuRow = (mcu / mcusPerLine) | 0;
var mcuCol = mcu % mcusPerLine;
var blockRow = mcuRow * component.v + row;
var blockCol = mcuCol * component.h + col;
// If the block is missing and we're in tolerant mode, just skip it.
if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)
return;
decode(component, component.blocks[blockRow][blockCol]);
}
function decodeBlock(component, decode, mcu) {
var blockRow = (mcu / component.blocksPerLine) | 0;
var blockCol = mcu % component.blocksPerLine;
// If the block is missing and we're in tolerant mode, just skip it.
if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)
return;
decode(component, component.blocks[blockRow][blockCol]);
}
var componentsLength = components.length;
var component, i, j, k, n;
var decodeFn;
if (progressive) {
if (spectralStart === 0)
decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
else
decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
} else {
decodeFn = decodeBaseline;
}
var mcu = 0, marker;
var mcuExpected;
if (componentsLength == 1) {
mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
} else {
mcuExpected = mcusPerLine * frame.mcusPerColumn;
}
if (!resetInterval) resetInterval = mcuExpected;
var h, v;
while (mcu < mcuExpected) {
// reset interval stuff
for (i = 0; i < componentsLength; i++)
components[i].pred = 0;
eobrun = 0;
if (componentsLength == 1) {
component = components[0];
for (n = 0; n < resetInterval; n++) {
decodeBlock(component, decodeFn, mcu);
mcu++;
}
} else {
for (n = 0; n < resetInterval; n++) {
for (i = 0; i < componentsLength; i++) {
component = components[i];
h = component.h;
v = component.v;
for (j = 0; j < v; j++) {
for (k = 0; k < h; k++) {
decodeMcu(component, decodeFn, mcu, j, k);
}
}
}
mcu++;
// If we've reached our expected MCU's, stop decoding
if (mcu === mcuExpected) break;
}
}
if (mcu === mcuExpected) {
// Skip trailing bytes at the end of the scan - until we reach the next marker
do {
if (data[offset] === 0xFF) {
if (data[offset + 1] !== 0x00) {
break;
}
}
offset += 1;
} while (offset < data.length - 2);
}
// find marker
bitsCount = 0;
marker = (data[offset] << 8) | data[offset + 1];
if (marker < 0xFF00) {
throw new Error("marker was not found");
}
if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
offset += 2;
}
else
break;
}
return offset - startOffset;
}
function buildComponentData(frame, component) {
var lines = [];
var blocksPerLine = component.blocksPerLine;
var blocksPerColumn = component.blocksPerColumn;
var samplesPerLine = blocksPerLine << 3;
// Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.
var R = new Int32Array(64), r = new Uint8Array(64);
// A port of poppler's IDCT method which in turn is taken from:
// Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
// "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
// IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
// 988-991.
function quantizeAndInverse(zz, dataOut, dataIn) {
var qt = component.quantizationTable;
var v0, v1, v2, v3, v4, v5, v6, v7, t;
var p = dataIn;
var i;
// dequant
for (i = 0; i < 64; i++)
p[i] = zz[i] * qt[i];
// inverse DCT on rows
for (i = 0; i < 8; ++i) {
var row = 8 * i;
// check for all-zero AC coefficients
if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&
p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&
p[7 + row] == 0) {
t = (dctSqrt2 * p[0 + row] + 512) >> 10;
p[0 + row] = t;
p[1 + row] = t;
p[2 + row] = t;
p[3 + row] = t;
p[4 + row] = t;
p[5 + row] = t;
p[6 + row] = t;
p[7 + row] = t;
continue;
}
// stage 4
v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;
v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;
v2 = p[2 + row];
v3 = p[6 + row];
v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;
v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;
v5 = p[3 + row] << 4;
v6 = p[5 + row] << 4;
// stage 3
t = (v0 - v1+ 1) >> 1;
v0 = (v0 + v1 + 1) >> 1;
v1 = t;
t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
v3 = t;
t = (v4 - v6 + 1) >> 1;
v4 = (v4 + v6 + 1) >> 1;
v6 = t;
t = (v7 + v5 + 1) >> 1;
v5 = (v7 - v5 + 1) >> 1;
v7 = t;
// stage 2
t = (v0 - v3 + 1) >> 1;
v0 = (v0 + v3 + 1) >> 1;
v3 = t;
t = (v1 - v2 + 1) >> 1;
v1 = (v1 + v2 + 1) >> 1;
v2 = t;
t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
v7 = t;
t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
v6 = t;
// stage 1
p[0 + row] = v0 + v7;
p[7 + row] = v0 - v7;
p[1 + row] = v1 + v6;
p[6 + row] = v1 - v6;
p[2 + row] = v2 + v5;
p[5 + row] = v2 - v5;
p[3 + row] = v3 + v4;
p[4 + row] = v3 - v4;
}
// inverse DCT on columns
for (i = 0; i < 8; ++i) {
var col = i;
// check for all-zero AC coefficients
if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&
p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&
p[7*8 + col] == 0) {
t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;
p[0*8 + col] = t;
p[1*8 + col] = t;
p[2*8 + col] = t;
p[3*8 + col] = t;
p[4*8 + col] = t;
p[5*8 + col] = t;
p[6*8 + col] = t;
p[7*8 + col] = t;
continue;
}
// stage 4
v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;
v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;
v2 = p[2*8 + col];
v3 = p[6*8 + col];
v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;
v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;
v5 = p[3*8 + col];
v6 = p[5*8 + col];
// stage 3
t = (v0 - v1 + 1) >> 1;
v0 = (v0 + v1 + 1) >> 1;
v1 = t;
t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
v3 = t;
t = (v4 - v6 + 1) >> 1;
v4 = (v4 + v6 + 1) >> 1;
v6 = t;
t = (v7 + v5 + 1) >> 1;
v5 = (v7 - v5 + 1) >> 1;
v7 = t;
// stage 2
t = (v0 - v3 + 1) >> 1;
v0 = (v0 + v3 + 1) >> 1;
v3 = t;
t = (v1 - v2 + 1) >> 1;
v1 = (v1 + v2 + 1) >> 1;
v2 = t;
t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
v7 = t;
t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
v6 = t;
// stage 1
p[0*8 + col] = v0 + v7;
p[7*8 + col] = v0 - v7;
p[1*8 + col] = v1 + v6;
p[6*8 + col] = v1 - v6;
p[2*8 + col] = v2 + v5;
p[5*8 + col] = v2 - v5;
p[3*8 + col] = v3 + v4;
p[4*8 + col] = v3 - v4;
}
// convert to 8-bit integers
for (i = 0; i < 64; ++i) {
var sample = 128 + ((p[i] + 8) >> 4);
dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
}
}
requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
var i, j;
for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
var scanLine = blockRow << 3;
for (i = 0; i < 8; i++)
lines.push(new Uint8Array(samplesPerLine));
for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
var offset = 0, sample = blockCol << 3;
for (j = 0; j < 8; j++) {
var line = lines[scanLine + j];
for (i = 0; i < 8; i++)
line[sample + i] = r[offset++];
}
}
}
return lines;
}
function clampTo8bit(a) {
return a < 0 ? 0 : a > 255 ? 255 : a;
}
constructor.prototype = {
load: function load(path) {
var xhr = new XMLHttpRequest();
xhr.open("GET", path, true);
xhr.responseType = "arraybuffer";
xhr.onload = (function() {
// TODO catch parse error
var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
this.parse(data);
if (this.onload)
this.onload();
}).bind(this);
xhr.send(null);
},
parse: function parse(data) {
var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;
var offset = 0; data.length;
function readUint16() {
var value = (data[offset] << 8) | data[offset + 1];
offset += 2;
return value;
}
function readDataBlock() {
var length = readUint16();
var array = data.subarray(offset, offset + length - 2);
offset += array.length;
return array;
}
function prepareComponents(frame) {
var maxH = 0, maxV = 0;
var component, componentId;
for (componentId in frame.components) {
if (frame.components.hasOwnProperty(componentId)) {
component = frame.components[componentId];
if (maxH < component.h) maxH = component.h;
if (maxV < component.v) maxV = component.v;
}
}
var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
for (componentId in frame.components) {
if (frame.components.hasOwnProperty(componentId)) {
component = frame.components[componentId];
var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
var blocksPerLineForMcu = mcusPerLine * component.h;
var blocksPerColumnForMcu = mcusPerColumn * component.v;
var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
var blocks = [];
// Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)
requestMemoryAllocation(blocksToAllocate * 256);
for (var i = 0; i < blocksPerColumnForMcu; i++) {
var row = [];
for (var j = 0; j < blocksPerLineForMcu; j++)
row.push(new Int32Array(64));
blocks.push(row);
}
component.blocksPerLine = blocksPerLine;
component.blocksPerColumn = blocksPerColumn;
component.blocks = blocks;
}
}
frame.maxH = maxH;
frame.maxV = maxV;
frame.mcusPerLine = mcusPerLine;
frame.mcusPerColumn = mcusPerColumn;
}
var jfif = null;
var adobe = null;
var frame, resetInterval;
var quantizationTables = [], frames = [];
var huffmanTablesAC = [], huffmanTablesDC = [];
var fileMarker = readUint16();
var malformedDataOffset = -1;
this.comments = [];
if (fileMarker != 0xFFD8) { // SOI (Start of Image)
throw new Error("SOI not found");
}
fileMarker = readUint16();
while (fileMarker != 0xFFD9) { // EOI (End of image)
var i, j;
switch(fileMarker) {
case 0xFF00: break;
case 0xFFE0: // APP0 (Application Specific)
case 0xFFE1: // APP1
case 0xFFE2: // APP2
case 0xFFE3: // APP3
case 0xFFE4: // APP4
case 0xFFE5: // APP5
case 0xFFE6: // APP6
case 0xFFE7: // APP7
case 0xFFE8: // APP8
case 0xFFE9: // APP9
case 0xFFEA: // APP10
case 0xFFEB: // APP11
case 0xFFEC: // APP12
case 0xFFED: // APP13
case 0xFFEE: // APP14
case 0xFFEF: // APP15
case 0xFFFE: // COM (Comment)
var appData = readDataBlock();
if (fileMarker === 0xFFFE) {
var comment = String.fromCharCode.apply(null, appData);
this.comments.push(comment);
}
if (fileMarker === 0xFFE0) {
if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
jfif = {
version: { major: appData[5], minor: appData[6] },
densityUnits: appData[7],
xDensity: (appData[8] << 8) | appData[9],
yDensity: (appData[10] << 8) | appData[11],
thumbWidth: appData[12],
thumbHeight: appData[13],
thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
};
}
}
// TODO APP1 - Exif
if (fileMarker === 0xFFE1) {
if (appData[0] === 0x45 &&
appData[1] === 0x78 &&
appData[2] === 0x69 &&
appData[3] === 0x66 &&
appData[4] === 0) { // 'EXIF\x00'
this.exifBuffer = appData.subarray(5, appData.length);
}
}
if (fileMarker === 0xFFEE) {
if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
adobe = {
version: appData[6],
flags0: (appData[7] << 8) | appData[8],
flags1: (appData[9] << 8) | appData[10],
transformCode: appData[11]
};
}
}
break;
case 0xFFDB: // DQT (Define Quantization Tables)
var quantizationTablesLength = readUint16();
var quantizationTablesEnd = quantizationTablesLength + offset - 2;
while (offset < quantizationTablesEnd) {
var quantizationTableSpec = data[offset++];
requestMemoryAllocation(64 * 4);
var tableData = new Int32Array(64);
if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
for (j = 0; j < 64; j++) {
var z = dctZigZag[j];
tableData[z] = data[offset++];
}
} else if ((quantizationTableSpec >> 4) === 1) { //16 bit
for (j = 0; j < 64; j++) {
var z = dctZigZag[j];
tableData[z] = readUint16();
}
} else
throw new Error("DQT: invalid table spec");
quantizationTables[quantizationTableSpec & 15] = tableData;
}
break;
case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
readUint16(); // skip data length
frame = {};
frame.extended = (fileMarker === 0xFFC1);
frame.progressive = (fileMarker === 0xFFC2);
frame.precision = data[offset++];
frame.scanLines = readUint16();
frame.samplesPerLine = readUint16();
frame.components = {};
frame.componentsOrder = [];
var pixelsInFrame = frame.scanLines * frame.samplesPerLine;
if (pixelsInFrame > maxResolutionInPixels) {
var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
}
var componentsCount = data[offset++], componentId;
for (i = 0; i < componentsCount; i++) {
componentId = data[offset];
var h = data[offset + 1] >> 4;
var v = data[offset + 1] & 15;
var qId = data[offset + 2];
frame.componentsOrder.push(componentId);
frame.components[componentId] = {
h: h,
v: v,
quantizationIdx: qId
};
offset += 3;
}
prepareComponents(frame);
frames.push(frame);
break;
case 0xFFC4: // DHT (Define Huffman Tables)
var huffmanLength = readUint16();
for (i = 2; i < huffmanLength;) {
var huffmanTableSpec = data[offset++];
var codeLengths = new Uint8Array(16);
var codeLengthSum = 0;
for (j = 0; j < 16; j++, offset++) {
codeLengthSum += (codeLengths[j] = data[offset]);
}
requestMemoryAllocation(16 + codeLengthSum);
var huffmanValues = new Uint8Array(codeLengthSum);
for (j = 0; j < codeLengthSum; j++, offset++)
huffmanValues[j] = data[offset];
i += 17 + codeLengthSum;
((huffmanTableSpec >> 4) === 0 ?
huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
buildHuffmanTable(codeLengths, huffmanValues);
}
break;
case 0xFFDD: // DRI (Define Restart Interval)
readUint16(); // skip data length
resetInterval = readUint16();
break;
case 0xFFDC: // Number of Lines marker
readUint16(); // skip data length
readUint16(); // Ignore this data since it represents the image height
break;
case 0xFFDA: // SOS (Start of Scan)
readUint16();
var selectorsCount = data[offset++];
var components = [], component;
for (i = 0; i < selectorsCount; i++) {
component = frame.components[data[offset++]];
var tableSpec = data[offset++];
component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
components.push(component);
}
var spectralStart = data[offset++];
var spectralEnd = data[offset++];
var successiveApproximation = data[offset++];
var processed = decodeScan(data, offset,
frame, components, resetInterval,
spectralStart, spectralEnd,
successiveApproximation >> 4, successiveApproximation & 15, this.opts);
offset += processed;
break;
case 0xFFFF: // Fill bytes
if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
offset--;
}
break;
default:
if (data[offset - 3] == 0xFF &&
data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
// could be incorrect encoding -- last 0xFF byte of the previous
// block was eaten by the encoder
offset -= 3;
break;
}
else if (fileMarker === 0xE0 || fileMarker == 0xE1) {
// Recover from malformed APP1 markers popular in some phone models.
// See https://github.com/eugeneware/jpeg-js/issues/82
if (malformedDataOffset !== -1) {
throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
}
malformedDataOffset = offset - 1;
const nextOffset = readUint16();
if (data[offset + nextOffset - 2] === 0xFF) {
offset += nextOffset - 2;
break;
}
}
throw new Error("unknown JPEG marker " + fileMarker.toString(16));
}
fileMarker = readUint16();
}
if (frames.length != 1)
throw new Error("only single frame JPEGs supported");
// set each frame's components quantization table
for (var i = 0; i < frames.length; i++) {
var cp = frames[i].components;
for (var j in cp) {
cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
delete cp[j].quantizationIdx;
}
}
this.width = frame.samplesPerLine;
this.height = frame.scanLines;
this.jfif = jfif;
this.adobe = adobe;
this.components = [];
for (var i = 0; i < frame.componentsOrder.length; i++) {
var component = frame.components[frame.componentsOrder[i]];
this.components.push({
lines: buildComponentData(frame, component),
scaleX: component.h / frame.maxH,
scaleY: component.v / frame.maxV
});
}
},
getData: function getData(width, height) {
var scaleX = this.width / width, scaleY = this.height / height;
var component1, component2, component3, component4;
var component1Line, component2Line, component3Line, component4Line;
var x, y;
var offset = 0;
var Y, Cb, Cr, K, C, M, Ye, R, G, B;
var colorTransform;
var dataLength = width * height * this.components.length;
requestMemoryAllocation(dataLength);
var data = new Uint8Array(dataLength);
switch (this.components.length) {
case 1:
component1 = this.components[0];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
for (x = 0; x < width; x++) {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
data[offset++] = Y;
}
}
break;
case 2:
// PDF might compress two component data in custom colorspace
component1 = this.components[0];
component2 = this.components[1];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
for (x = 0; x < width; x++) {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
data[offset++] = Y;
Y = component2Line[0 | (x * component2.scaleX * scaleX)];
data[offset++] = Y;
}
}
break;
case 3:
// The default transform for three components is true
colorTransform = true;
// The adobe transform marker overrides any previous setting
if (this.adobe && this.adobe.transformCode)
colorTransform = true;
else if (typeof this.opts.colorTransform !== 'undefined')
colorTransform = !!this.opts.colorTransform;
component1 = this.components[0];
component2 = this.components[1];
component3 = this.components[2];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
for (x = 0; x < width; x++) {
if (!colorTransform) {
R = component1Line[0 | (x * component1.scaleX * scaleX)];
G = component2Line[0 | (x * component2.scaleX * scaleX)];
B = component3Line[0 | (x * component3.scaleX * scaleX)];
} else {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
R = clampTo8bit(Y + 1.402 * (Cr - 128));
G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
B = clampTo8bit(Y + 1.772 * (Cb - 128));
}
data[offset++] = R;
data[offset++] = G;
data[offset++] = B;
}
}
break;
case 4:
if (!this.adobe)
throw new Error('Unsupported color mode (4 components)');
// The default transform for four components is false
colorTransform = false;
// The adobe transform marker overrides any previous setting
if (this.adobe && this.adobe.transformCode)
colorTransform = true;
else if (typeof this.opts.colorTransform !== 'undefined')
colorTransform = !!this.opts.colorTransform;
component1 = this.components[0];
component2 = this.components[1];
component3 = this.components[2];
component4 = this.components[3];
for (y = 0; y < height; y++) {
component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];
for (x = 0; x < width; x++) {
if (!colorTransform) {
C = component1Line[0 | (x * component1.scaleX * scaleX)];
M = component2Line[0 | (x * component2.scaleX * scaleX)];
Ye = component3Line[0 | (x * component3.scaleX * scaleX)];
K = component4Line[0 | (x * component4.scaleX * scaleX)];
} else {
Y = component1Line[0 | (x * component1.scaleX * scaleX)];
Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
K = component4Line[0 | (x * component4.scaleX * scaleX)];
C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
}
data[offset++] = 255-C;
data[offset++] = 255-M;
data[offset++] = 255-Ye;
data[offset++] = 255-K;
}
}
break;
default:
throw new Error('Unsupported color mode');
}
return data;
},
copyToImageData: function copyToImageData(imageData, formatAsRGBA) {
var width = imageData.width, height = imageData.height;
var imageDataArray = imageData.data;
var data = this.getData(width, height);
var i = 0, j = 0, x, y;
var Y, K, C, M, R, G, B;
switch (this.components.length) {
case 1:
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
Y = data[i++];
imageDataArray[j++] = Y;
imageDataArray[j++] = Y;
imageDataArray[j++] = Y;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
case 3:
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
R = data[i++];
G = data[i++];
B = data[i++];
imageDataArray[j++] = R;
imageDataArray[j++] = G;
imageDataArray[j++] = B;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
case 4:
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
C = data[i++];
M = data[i++];
Y = data[i++];
K = data[i++];
R = 255 - clampTo8bit(C * (1 - K / 255) + K);
G = 255 - clampTo8bit(M * (1 - K / 255) + K);
B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
imageDataArray[j++] = R;
imageDataArray[j++] = G;
imageDataArray[j++] = B;
if (formatAsRGBA) {
imageDataArray[j++] = 255;
}
}
}
break;
default:
throw new Error('Unsupported color mode');
}
}
};
// We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.
var totalBytesAllocated = 0;
var maxMemoryUsageBytes = 0;
function requestMemoryAllocation(increaseAmount = 0) {
var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);
}
totalBytesAllocated = totalMemoryImpactBytes;
}
constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {
totalBytesAllocated = 0;
maxMemoryUsageBytes = maxMemoryUsageBytes_;
};
constructor.getBytesAllocated = function () {
return totalBytesAllocated;
};
constructor.requestMemoryAllocation = requestMemoryAllocation;
return constructor;
})();
if (typeof module !== 'undefined') {
module.exports = decode$1;
} else if (typeof window !== 'undefined') {
window['jpeg-js'] = window['jpeg-js'] || {};
window['jpeg-js'].decode = decode$1;
}
function decode$1(jpegData, userOpts = {}) {
var defaultOpts = {
// "undefined" means "Choose whether to transform colors based on the image’s color model."
colorTransform: undefined,
useTArray: false,
formatAsRGBA: true,
tolerantDecoding: true,
maxResolutionInMP: 100, // Don't decode more than 100 megapixels
maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB
};
var opts = {...defaultOpts, ...userOpts};
var arr = new Uint8Array(jpegData);
var decoder = new JpegImage();
decoder.opts = opts;
// If this constructor ever supports async decoding this will need to be done differently.
// Until then, treating as singleton limit is fine.
JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);
decoder.parse(arr);
var channels = (opts.formatAsRGBA) ? 4 : 3;
var bytesNeeded = decoder.width * decoder.height * channels;
try {
JpegImage.requestMemoryAllocation(bytesNeeded);
var image = {
width: decoder.width,
height: decoder.height,
exifBuffer: decoder.exifBuffer,
data: opts.useTArray ?
new Uint8Array(bytesNeeded) :
Buffer$1.alloc(bytesNeeded)
};
if(decoder.comments.length > 0) {
image["comments"] = decoder.comments;
}
} catch (err){
if (err instanceof RangeError){
throw new Error("Could not allocate enough memory for the image. " +
"Required: " + bytesNeeded);
} else {
throw err;
}
}
decoder.copyToImageData(image, opts.formatAsRGBA);
return image;
}
var decoder = /*#__PURE__*/Object.freeze({
__proto__: null
});
var require$$1 = /*@__PURE__*/getAugmentedNamespace(decoder);
var encode = require$$0,
decode = require$$1;
var jpegJs = {
encode: encode,
decode: decode
};
var median = function(data) {
var mdarr = data.slice(0);
mdarr.sort(function(a, b) {
return a - b;
});
if (mdarr.length % 2 === 0) return (mdarr[mdarr.length / 2 - 1] + mdarr[mdarr.length / 2]) / 2.0;
return mdarr[Math.floor(mdarr.length / 2)];
};
var translate_blocks_to_bits = function translate_blocks_to_bits(blocks, pixels_per_block) {
var half_block_value = pixels_per_block * 256 * 3 / 2;
var bandsize = blocks.length / 4;
// Compare medians across four horizontal bands
for(var i = 0; i < 4; i++){
var m = median(blocks.slice(i * bandsize, (i + 1) * bandsize));
for(var j = i * bandsize; j < (i + 1) * bandsize; j++){
var v = blocks[j];
blocks[j] = Number(v > m || Math.abs(v - m) < 1 && m > half_block_value);
}
}
};
var bits_to_hexhash = function(bitsArray) {
var hex = [];
for(var i = 0; i < bitsArray.length; i += 4){
var nibble = bitsArray.slice(i, i + 4);
hex.push(parseInt(nibble.join(""), 2).toString(16));
}
return hex.join("");
};
var bmvbhash_even = function(data, bits) {
var blocksize_x = Math.floor(data.width / bits);
var blocksize_y = Math.floor(data.height / bits);
var result = [];
for(var y = 0; y < bits; y++){
for(var x = 0; x < bits; x++){
var total = 0;
for(var iy = 0; iy < blocksize_y; iy++){
for(var ix = 0; ix < blocksize_x; ix++){
var cx = x * blocksize_x + ix;
var cy = y * blocksize_y + iy;
var ii = (cy * data.width + cx) * 4;
var alpha = data.data[ii + 3];
if (alpha === 0) {
total += 765;
} else {
total += data.data[ii] + data.data[ii + 1] + data.data[ii + 2];
}
}
}
result.push(total);
}
}
translate_blocks_to_bits(result, blocksize_x * blocksize_y);
return bits_to_hexhash(result);
};
function _arrayLikeToArray$2(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles$1(arr) {
if (Array.isArray(arr)) return arr;
}
function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$3(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _iterableToArrayLimit$1(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$1() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _objectSpread$1(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_defineProperty$1(target, key, source[key]);
});
}
return target;
}
function _slicedToArray$1(arr, i) {
return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest$1();
}
function _unsupportedIterableToArray$2(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
}
var csettings$1;
settings.subscribe(function(b) {
csettings$1 = b;
});
var gelquirk = function(prefix) {
return function(a) {
var base = a.post || a.data || a;
if (!Array.isArray(base)) return [];
base = base.filter(function(e) {
return e.file_url;
});
return base.map(function(e1) {
return {
full_url: e1.file_url,
preview_url: e1.preview_url || e1.preview_url,
source: e1.source,
ext: e1.file_ext || e1.file_url.substr(e1.file_url.lastIndexOf(".") + 1),
page: "".concat(prefix).concat(e1.id || e1.parent_id),
tags: (e1.tag_string || e1.tags && Array.isArray(e1.tags) && (typeof e1.tags[0] == "string" ? e1.tags.join(" ") : e1.tags.map(function(e) {
return e.name_en;
}).join(" ")) || e1.tags || "").split(" ")
};
}) || [];
};
};
var black = new Set();
var phashEn = false;
var mindist = 5;
settings.subscribe(function(s) {
boorus = s.rsources.map(function(e) {
return _objectSpread$1({}, e, {
quirks: gelquirk(e.view)
});
});
black = new Set(s.blacklist);
mindist = s.mdist || 5;
phashEn = s.phash;
});
var boorus = localLoad("settingsv2", {
rsources: []
}).rsources.map(function(e) {
return _objectSpread$1({}, e, {
quirks: gelquirk(e.view)
});
});
var bufferingTime = 2000;
var expired = undefined;
var reqQueue = [];
var unlockQueue = Promise.resolve();
var queryCache = {};
var processQueries = function() {
var _ref = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee() {
var unlock, md5, res, results;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
unlockQueue = new Promise(function(_) {
return unlock = _;
});
md5 = reqQueue.map(function(e) {
return e[0];
}).filter(function(e) {
return !(e in queryCache);
});
expired = undefined;
if (!(md5.length > 0)) {
_ctx.next = 12;
break;
}
_ctx.next = 7;
return fetch("https://shoujo.coom.tech/api", {
method: "POST",
body: JSON.stringify({
md5: md5
}),
headers: {
"content-type": "application/json"
}
});
case 7:
res = _ctx.sent;
_ctx.next = 10;
return res.json();
case 10:
results = _ctx.sent;
Object.entries(results).forEach(function(e) {
return queryCache[e[0]] = e[1];
});
case 12:
reqQueue.forEach(function(e) {
return e[1](_defineProperty$1({}, e[0], queryCache[e[0]]));
});
reqQueue = [];
unlock();
case 15:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function processQueries() {
return _ref.apply(this, arguments);
};
}();
var queueForProcessing = function() {
var _ref = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee(hex, cb) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
console.log("putting", hex, "in queue");
_ctx.next = 3;
return unlockQueue;
case 3:
console.log("put", hex, "in queue");
reqQueue.push([
hex,
cb
]);
if (!expired) {
expired = setTimeout(processQueries, bufferingTime);
}
case 6:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function queueForProcessing(hex, cb) {
return _ref.apply(this, arguments);
};
}();
var cache = {};
(function() {
var _ref = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee(hex) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
return _ctx.abrupt("return", new Promise(function(res) {
queueForProcessing(hex, res);
}));
case 1:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function shoujoFind(hex) {
return _ref.apply(this, arguments);
};
})();
var findFileFrom = function() {
var _ref = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee(b, hex, abort) {
var res, pres, tran;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.prev = 0;
if (!(b.domain in cache && hex in cache[b.domain])) {
_ctx.next = 3;
break;
}
return _ctx.abrupt("return", cache[b.domain][hex]);
case 3:
_ctx.next = 5;
return ifetch("https://".concat(b.domain).concat(b.endpoint).concat(hex));
case 5:
res = _ctx.sent;
_ctx.next = 8;
return res.json();
case 8:
pres = _ctx.sent;
tran = b.quirks(pres).filter(function(e2) {
return !e2.tags.some(function(e) {
return black.has(e);
});
});
if (!(b.domain in cache)) cache[b.domain] = {};
cache[b.domain][hex] = tran;
return _ctx.abrupt("return", tran);
case 15:
_ctx.prev = 15;
_ctx.t0 = _ctx["catch"](0);
console.error("The following error might be expected");
console.error(_ctx.t0);
return _ctx.abrupt("return", []);
case 20:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
0,
15
]
]);
}));
return function findFileFrom(b, hex, abort) {
return _ref.apply(this, arguments);
};
}();
var extract$1 = function() {
var _ref1 = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee1(b, fn) {
var result, booru, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, e, cachedFile, prev, full;
return regeneratorRuntime$1.wrap(function _callee$(_ctx1) {
while(1)switch(_ctx1.prev = _ctx1.next){
case 0:
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx1.prev = 3;
_iterator = Object.values(boorus)[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_ctx1.next = 18;
break;
}
e = _step.value;
if (!e.disabled) {
_ctx1.next = 9;
break;
}
return _ctx1.abrupt("continue", 15);
case 9:
_ctx1.next = 11;
return findFileFrom(e, fn.substring(0, 32));
case 11:
result = _ctx1.sent;
if (!result.length) {
_ctx1.next = 15;
break;
}
booru = e.name;
return _ctx1.abrupt("break", 18);
case 15:
_iteratorNormalCompletion = true;
_ctx1.next = 5;
break;
case 18:
_ctx1.next = 24;
break;
case 20:
_ctx1.prev = 20;
_ctx1.t0 = _ctx1["catch"](3);
_didIteratorError = true;
_iteratorError = _ctx1.t0;
case 24:
_ctx1.prev = 24;
_ctx1.prev = 25;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 27:
_ctx1.prev = 27;
if (!_didIteratorError) {
_ctx1.next = 30;
break;
}
throw _iteratorError;
case 30:
return _ctx1.finish(27);
case 31:
return _ctx1.finish(24);
case 32:
prev = result[0].preview_url;
full = result[0].full_url;
_ctx1.t1 = result[0].source;
_ctx1.t2 = {
title: booru,
url: result[0].page
};
_ctx1.t3 = fn.substring(0, 33) + result[0].ext;
if (!csettings$1.hotlink) {
_ctx1.next = 42;
break;
}
_ctx1.t4 = prev || full;
_ctx1.next = 49;
break;
case 42:
_ctx1.t5 = Buffer$1;
_ctx1.next = 45;
return ifetch(prev || full);
case 45:
_ctx1.next = 47;
return _ctx1.sent.arrayBuffer();
case 47:
_ctx1.t6 = _ctx1.sent;
_ctx1.t4 = _ctx1.t5.from.call(_ctx1.t5, _ctx1.t6);
case 49:
_ctx1.t7 = _ctx1.t4;
_ctx1.t8 = csettings$1.hotlink ? full || prev : function() {
var _ref = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee(lsn) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (cachedFile) {
_ctx.next = 6;
break;
}
_ctx.next = 3;
return ifetch(full || prev, undefined, lsn);
case 3:
_ctx.next = 5;
return _ctx.sent.arrayBuffer();
case 5:
cachedFile = _ctx.sent;
case 6:
return _ctx.abrupt("return", Buffer$1.from(cachedFile));
case 7:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function(lsn) {
return _ref.apply(this, arguments);
};
}();
_ctx1.t9 = {
source: _ctx1.t1,
page: _ctx1.t2,
filename: _ctx1.t3,
thumbnail: _ctx1.t7,
data: _ctx1.t8
};
return _ctx1.abrupt("return", [
_ctx1.t9
]);
case 53:
case "end":
return _ctx1.stop();
}
}, _callee1, null, [
[
3,
20,
24,
32
],
[
25,
,
27,
31
]
]);
}));
return function extract(b, fn) {
return _ref1.apply(this, arguments);
};
}();
var phash = function(b) {
var res = jpegJs.decode(b);
return bmvbhash_even(res, 8);
};
function bitCount(n) {
n = n - (n >> 1 & 0x55555555);
n = (n & 0x33333333) + (n >> 2 & 0x33333333);
return (n + (n >> 4) & 0xF0F0F0F) * 0x1010101 >> 24;
}
// a & b are hex strings
var hammingDist = function(a, b) {
var acc = 0;
while(a.length > 0){
var an = parseInt(a.slice(0, 8), 16);
var bn = parseInt(b.slice(0, 8), 16);
acc += bitCount(an ^ bn);
a = a.slice(8);
b = b.slice(8);
}
return acc;
};
var has_embed$1 = function() {
var _ref2 = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee2(b, fn, prevlink) {
var result, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, e3, getHash, ref, orighash, tehash, d;
return regeneratorRuntime$1.wrap(function _callee$(_ctx2) {
while(1)switch(_ctx2.prev = _ctx2.next){
case 0:
if (!Buffer$1.from(fn, "hex").equals(b)) {
_ctx2.next = 2;
break;
}
return _ctx2.abrupt("return", false);
case 2:
result = undefined;
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx2.prev = 4;
_iterator = Object.values(boorus)[Symbol.iterator]();
case 6:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_ctx2.next = 19;
break;
}
e3 = _step.value;
if (!e3.disabled) {
_ctx2.next = 10;
break;
}
return _ctx2.abrupt("continue", 16);
case 10:
_ctx2.next = 12;
return findFileFrom(e3, fn.substring(0, 32));
case 12:
result = _ctx2.sent;
result = result.filter(function(e) {
return e.full_url || e.preview_url;
}); // skips possible paywalls
if (!result.length) {
_ctx2.next = 16;
break;
}
return _ctx2.abrupt("break", 19);
case 16:
_iteratorNormalCompletion = true;
_ctx2.next = 6;
break;
case 19:
_ctx2.next = 25;
break;
case 21:
_ctx2.prev = 21;
_ctx2.t0 = _ctx2["catch"](4);
_didIteratorError = true;
_iteratorError = _ctx2.t0;
case 25:
_ctx2.prev = 25;
_ctx2.prev = 26;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 28:
_ctx2.prev = 28;
if (!_didIteratorError) {
_ctx2.next = 31;
break;
}
throw _iteratorError;
case 31:
return _ctx2.finish(28);
case 32:
return _ctx2.finish(25);
case 33:
if (!(result && result.length != 0 && phashEn && prevlink)) {
_ctx2.next = 45;
break;
}
getHash = function() {
var _ref = _asyncToGenerator$3(regeneratorRuntime$1.mark(function _callee(l) {
var ogreq, origPreview;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return ifetch(l);
case 2:
ogreq = _ctx.sent;
_ctx.next = 5;
return ogreq.arrayBuffer();
case 5:
origPreview = _ctx.sent;
return _ctx.abrupt("return", phash(Buffer$1.from(origPreview)));
case 7:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function getHash(l) {
return _ref.apply(this, arguments);
};
}();
_ctx2.t1 = _slicedToArray$1;
_ctx2.next = 38;
return Promise.all([
getHash(prevlink),
getHash(result[0].preview_url)
]);
case 38:
_ctx2.t2 = _ctx2.sent;
ref = (0, _ctx2.t1)(_ctx2.t2, 2);
orighash = ref[0];
tehash = ref[1];
d = hammingDist(orighash, tehash);
console.log(d, prevlink);
return _ctx2.abrupt("return", d > mindist);
case 45:
return _ctx2.abrupt("return", result && result.length != 0);
case 46:
case "end":
return _ctx2.stop();
}
}, _callee2, null, [
[
4,
21,
25,
33
],
[
26,
,
28,
32
]
]);
}));
return function has_embed(b, fn, prevlink) {
return _ref2.apply(this, arguments);
};
}();
var thirdeye = {
skip: true,
extract: extract$1,
has_embed: has_embed$1,
match: function(fn) {
return !!fn.match(/^[0-9a-f]{32}\.....?/);
}
};
function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$2(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var sources = [
{
host: "Catbox",
prefix: "files.catbox.moe/"
},
{
host: "Litter",
prefix: "litter.catbox.moe/"
},
{
host: "Zzzz",
prefix: "z.zz.fo/"
}
];
var csettings;
settings.subscribe(function(b) {
csettings = b;
});
var getExt = function(fn) {
// const isDum = fn!.match(/^[a-z0-9]{6}\./i);
var isB64 = fn.match(/^((?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=))?\.(gif|jpe?g|png|webm)/);
var isExt = fn.match(/\[.*=(.*)\]/);
var ext;
var source;
try {
if (isB64) {
ext = atob(isB64[1]);
} else if (isExt) {
ext = decodeURIComponent(isExt[1]);
if (ext.startsWith("https://")) ext = ext.slice("https://".length);
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = sources[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var cs = _step.value;
if (ext.startsWith(cs.prefix)) {
source = cs.prefix;
ext = ext.slice(cs.prefix.length);
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
} catch (e) {
/**/ }
return {
ext: ext,
source: source
};
};
var extract = function() {
var _ref1 = _asyncToGenerator$2(regeneratorRuntime$1.mark(function _callee1(b, fn) {
var ref, ext, source, rsource, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, cs;
return regeneratorRuntime$1.wrap(function _callee$(_ctx1) {
while(1)switch(_ctx1.prev = _ctx1.next){
case 0:
ref = getExt(fn), ext = ref.ext, source = ref.source;
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx1.prev = 3;
_iterator = sources[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_ctx1.next = 21;
break;
}
cs = _step.value;
if (!(source && cs.prefix != source)) {
_ctx1.next = 9;
break;
}
return _ctx1.abrupt("continue", 18);
case 9:
_ctx1.prev = 9;
_ctx1.next = 12;
return getHeaders("https://" + cs.prefix + ext);
case 12:
rsource = "https://" + cs.prefix + ext;
return _ctx1.abrupt("break", 21);
case 16:
_ctx1.prev = 16;
_ctx1.t0 = _ctx1["catch"](9);
case 18:
_iteratorNormalCompletion = true;
_ctx1.next = 5;
break;
case 21:
_ctx1.next = 27;
break;
case 23:
_ctx1.prev = 23;
_ctx1.t1 = _ctx1["catch"](3);
_didIteratorError = true;
_iteratorError = _ctx1.t1;
case 27:
_ctx1.prev = 27;
_ctx1.prev = 28;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 30:
_ctx1.prev = 30;
if (!_didIteratorError) {
_ctx1.next = 33;
break;
}
throw _iteratorError;
case 33:
return _ctx1.finish(30);
case 34:
return _ctx1.finish(27);
case 35:
return _ctx1.abrupt("return", [
{
filename: ext,
data: csettings.hotlink ? rsource : function() {
var _ref = _asyncToGenerator$2(regeneratorRuntime$1.mark(function _callee(lsn) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.prev = 0;
_ctx.t0 = Buffer$1;
_ctx.next = 4;
return ifetch(rsource, undefined, lsn);
case 4:
_ctx.next = 6;
return _ctx.sent.arrayBuffer();
case 6:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", _ctx.t0.from.call(_ctx.t0, _ctx.t1));
case 10:
_ctx.prev = 10;
_ctx.t2 = _ctx["catch"](0);
case 12:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
0,
10
]
]);
}));
return function(lsn) {
return _ref.apply(this, arguments);
};
}(),
thumbnail: Buffer$1.from(thumbnail)
}
]);
case 36:
case "end":
return _ctx1.stop();
}
}, _callee1, null, [
[
3,
23,
27,
35
],
[
9,
16
],
[
28,
,
30,
34
]
]);
}));
return function extract(b, fn) {
return _ref1.apply(this, arguments);
};
}();
var has_embed = function() {
var _ref = _asyncToGenerator$2(regeneratorRuntime$1.mark(function _callee(b, fn) {
var ref, ext, source, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, cs;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
ref = getExt(fn), ext = ref.ext, source = ref.source;
if (ext) {
_ctx.next = 3;
break;
}
return _ctx.abrupt("return", false);
case 3:
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx.prev = 4;
_iterator = sources[Symbol.iterator]();
case 6:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_ctx.next = 22;
break;
}
cs = _step.value;
if (!(source && cs.prefix != source)) {
_ctx.next = 10;
break;
}
return _ctx.abrupt("continue", 19);
case 10:
_ctx.prev = 10;
_ctx.next = 13;
return getHeaders("https://" + cs.prefix + ext);
case 13:
return _ctx.abrupt("return", true);
case 17:
_ctx.prev = 17;
_ctx.t0 = _ctx["catch"](10);
case 19:
_iteratorNormalCompletion = true;
_ctx.next = 6;
break;
case 22:
_ctx.next = 28;
break;
case 24:
_ctx.prev = 24;
_ctx.t1 = _ctx["catch"](4);
_didIteratorError = true;
_iteratorError = _ctx.t1;
case 28:
_ctx.prev = 28;
_ctx.prev = 29;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 31:
_ctx.prev = 31;
if (!_didIteratorError) {
_ctx.next = 34;
break;
}
throw _iteratorError;
case 34:
return _ctx.finish(31);
case 35:
return _ctx.finish(28);
case 36:
return _ctx.abrupt("return", false);
case 37:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
4,
24,
28,
36
],
[
10,
17
],
[
29,
,
31,
35
]
]);
}));
return function has_embed(b, fn) {
return _ref.apply(this, arguments);
};
}();
var pomf = {
skip: true,
extract: extract,
has_embed: has_embed,
match: function(fn) {
return !!getExt(fn);
}
};
/* src/Components/Dialog.svelte generated by Svelte v3.44.3 */
function create_if_block$8(ctx) {
let div;
let current;
const default_slot_template = /*#slots*/ ctx[5].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[4], null);
return {
c() {
div = element("div");
if (default_slot) default_slot.c();
set_style(div, "top", /*pos*/ ctx[0][1] + "px");
set_style(div, "left", /*pos*/ ctx[0][0] + "px");
attr(div, "class", "dialog svelte-1edrz51");
},
m(target, anchor) {
insert(target, div, anchor);
if (default_slot) {
default_slot.m(div, null);
}
current = true;
},
p(ctx, dirty) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 16)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[4],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[4])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[4], dirty, null),
null
);
}
}
if (!current || dirty & /*pos*/ 1) {
set_style(div, "top", /*pos*/ ctx[0][1] + "px");
}
if (!current || dirty & /*pos*/ 1) {
set_style(div, "left", /*pos*/ ctx[0][0] + "px");
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (default_slot) default_slot.d(detaching);
}
};
}
function create_fragment$f(ctx) {
let if_block_anchor;
let current;
let if_block = /*visible*/ ctx[1] && create_if_block$8(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
if (/*visible*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*visible*/ 2) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$8(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function setPos(p) {
} //pos = p;
function instance$f($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
let { pos = [0, 0] } = $$props;
let visible = false;
function toggle() {
$$invalidate(1, visible = !visible);
}
$$self.$$set = $$props => {
if ('pos' in $$props) $$invalidate(0, pos = $$props.pos);
if ('$$scope' in $$props) $$invalidate(4, $$scope = $$props.$$scope);
};
return [pos, visible, toggle, setPos, $$scope, slots];
}
class Dialog extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$f, create_fragment$f, safe_not_equal, { pos: 0, toggle: 2, setPos: 3 });
}
get pos() {
return this.$$.ctx[0];
}
set pos(pos) {
this.$$set({ pos });
flush();
}
get toggle() {
return this.$$.ctx[2];
}
get setPos() {
return setPos;
}
}
/* src/Components/Tag.svelte generated by Svelte v3.44.3 */
function create_if_block$7(ctx) {
let span;
let mounted;
let dispose;
return {
c() {
span = element("span");
span.textContent = "x";
attr(span, "class", "svelte-gsq99c");
},
m(target, anchor) {
insert(target, span, anchor);
if (!mounted) {
dispose = listen(span, "click", /*click_handler*/ ctx[4]);
mounted = true;
}
},
p: noop$1,
d(detaching) {
if (detaching) detach(span);
mounted = false;
dispose();
}
};
}
function create_fragment$e(ctx) {
let span;
let t0;
let t1;
let mounted;
let dispose;
let if_block = /*toggleable*/ ctx[1] && create_if_block$7(ctx);
return {
c() {
span = element("span");
t0 = text$1(/*tag*/ ctx[0]);
t1 = space();
if (if_block) if_block.c();
attr(span, "class", "tag svelte-gsq99c");
toggle_class(span, "toggle", /*toggleable*/ ctx[1]);
toggle_class(span, "toggled", /*toggleable*/ ctx[1] && /*toggled*/ ctx[2]);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
append(span, t1);
if (if_block) if_block.m(span, null);
if (!mounted) {
dispose = listen(span, "click", /*click_handler_1*/ ctx[5]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*tag*/ 1) set_data(t0, /*tag*/ ctx[0]);
if (/*toggleable*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$7(ctx);
if_block.c();
if_block.m(span, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*toggleable*/ 2) {
toggle_class(span, "toggle", /*toggleable*/ ctx[1]);
}
if (dirty & /*toggleable, toggled*/ 6) {
toggle_class(span, "toggled", /*toggleable*/ ctx[1] && /*toggled*/ ctx[2]);
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (detaching) detach(span);
if (if_block) if_block.d();
mounted = false;
dispose();
}
};
}
function instance$e($$self, $$props, $$invalidate) {
let { tag } = $$props;
let { toggleable = false } = $$props;
let { toggled = false } = $$props;
const dispatch = createEventDispatcher();
const click_handler = e => (e.preventDefault(), dispatch("remove"));
const click_handler_1 = () => dispatch("toggle");
$$self.$$set = $$props => {
if ('tag' in $$props) $$invalidate(0, tag = $$props.tag);
if ('toggleable' in $$props) $$invalidate(1, toggleable = $$props.toggleable);
if ('toggled' in $$props) $$invalidate(2, toggled = $$props.toggled);
};
return [tag, toggleable, toggled, dispatch, click_handler, click_handler_1];
}
class Tag extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$e, create_fragment$e, safe_not_equal, { tag: 0, toggleable: 1, toggled: 2 });
}
get tag() {
return this.$$.ctx[0];
}
set tag(tag) {
this.$$set({ tag });
flush();
}
get toggleable() {
return this.$$.ctx[1];
}
set toggleable(toggleable) {
this.$$set({ toggleable });
flush();
}
get toggled() {
return this.$$.ctx[2];
}
set toggled(toggled) {
this.$$set({ toggled });
flush();
}
}
/* src/Components/Tabs.svelte generated by Svelte v3.44.3 */
function create_fragment$d(ctx) {
let div;
let current;
const default_slot_template = /*#slots*/ ctx[1].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[0], null);
return {
c() {
div = element("div");
if (default_slot) default_slot.c();
attr(div, "class", "tabs svelte-16zoarp");
},
m(target, anchor) {
insert(target, div, anchor);
if (default_slot) {
default_slot.m(div, null);
}
current = true;
},
p(ctx, [dirty]) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 1)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[0],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[0])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[0], dirty, null),
null
);
}
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (default_slot) default_slot.d(detaching);
}
};
}
const TABS = {};
function instance$d($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
const tabs = [];
const panels = [];
const selectedTab = writable(null);
const selectedPanel = writable(null);
setContext(TABS, {
registerTab: tab => {
tabs.push(tab);
selectedTab.update(current => current || tab);
onDestroy(() => {
const i = tabs.indexOf(tab);
tabs.splice(i, 1);
selectedTab.update(current => current === tab
? tabs[i] || tabs[tabs.length - 1]
: current);
});
},
registerPanel: panel => {
panels.push(panel);
selectedPanel.update(current => current || panel);
onDestroy(() => {
const i = panels.indexOf(panel);
panels.splice(i, 1);
selectedPanel.update(current => current === panel
? panels[i] || panels[panels.length - 1]
: current);
});
},
selectTab: tab => {
const i = tabs.indexOf(tab);
selectedTab.set(tab);
selectedPanel.set(panels[i]);
},
selectedTab,
selectedPanel
});
$$self.$$set = $$props => {
if ('$$scope' in $$props) $$invalidate(0, $$scope = $$props.$$scope);
};
return [$$scope, slots];
}
class Tabs extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$d, create_fragment$d, safe_not_equal, {});
}
}
/* src/Components/TabList.svelte generated by Svelte v3.44.3 */
function create_fragment$c(ctx) {
let div;
let current;
const default_slot_template = /*#slots*/ ctx[1].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[0], null);
return {
c() {
div = element("div");
if (default_slot) default_slot.c();
attr(div, "class", "tab-list svelte-1dd6kkg");
},
m(target, anchor) {
insert(target, div, anchor);
if (default_slot) {
default_slot.m(div, null);
}
current = true;
},
p(ctx, [dirty]) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 1)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[0],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[0])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[0], dirty, null),
null
);
}
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (default_slot) default_slot.d(detaching);
}
};
}
function instance$c($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
$$self.$$set = $$props => {
if ('$$scope' in $$props) $$invalidate(0, $$scope = $$props.$$scope);
};
return [$$scope, slots];
}
class TabList extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$c, create_fragment$c, safe_not_equal, {});
}
}
/* src/Components/Tab.svelte generated by Svelte v3.44.3 */
function create_fragment$b(ctx) {
let button;
let current;
let mounted;
let dispose;
const default_slot_template = /*#slots*/ ctx[5].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[4], null);
return {
c() {
button = element("button");
if (default_slot) default_slot.c();
attr(button, "class", "svelte-1i25yaz");
toggle_class(button, "selected", /*$selectedTab*/ ctx[0] === /*tab*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
if (default_slot) {
default_slot.m(button, null);
}
current = true;
if (!mounted) {
dispose = listen(button, "click", /*click_handler*/ ctx[6]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 16)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[4],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[4])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[4], dirty, null),
null
);
}
}
if (dirty & /*$selectedTab, tab*/ 3) {
toggle_class(button, "selected", /*$selectedTab*/ ctx[0] === /*tab*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(button);
if (default_slot) default_slot.d(detaching);
mounted = false;
dispose();
}
};
}
function instance$b($$self, $$props, $$invalidate) {
let $selectedTab;
let { $$slots: slots = {}, $$scope } = $$props;
const tab = {};
const { registerTab, selectTab, selectedTab } = getContext(TABS);
component_subscribe($$self, selectedTab, value => $$invalidate(0, $selectedTab = value));
registerTab(tab);
const click_handler = () => selectTab(tab);
$$self.$$set = $$props => {
if ('$$scope' in $$props) $$invalidate(4, $$scope = $$props.$$scope);
};
return [$selectedTab, tab, selectTab, selectedTab, $$scope, slots, click_handler];
}
class Tab extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$b, create_fragment$b, safe_not_equal, {});
}
}
/* src/Components/TabPanel.svelte generated by Svelte v3.44.3 */
function create_if_block$6(ctx) {
let current;
const default_slot_template = /*#slots*/ ctx[4].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[3], null);
return {
c() {
if (default_slot) default_slot.c();
},
m(target, anchor) {
if (default_slot) {
default_slot.m(target, anchor);
}
current = true;
},
p(ctx, dirty) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 8)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[3],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[3])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[3], dirty, null),
null
);
}
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (default_slot) default_slot.d(detaching);
}
};
}
function create_fragment$a(ctx) {
let if_block_anchor;
let current;
let if_block = /*$selectedPanel*/ ctx[0] === /*panel*/ ctx[1] && create_if_block$6(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
if (/*$selectedPanel*/ ctx[0] === /*panel*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*$selectedPanel*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$6(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function instance$a($$self, $$props, $$invalidate) {
let $selectedPanel;
let { $$slots: slots = {}, $$scope } = $$props;
const panel = {};
const { registerPanel, selectedPanel } = getContext(TABS);
component_subscribe($$self, selectedPanel, value => $$invalidate(0, $selectedPanel = value));
registerPanel(panel);
$$self.$$set = $$props => {
if ('$$scope' in $$props) $$invalidate(3, $$scope = $$props.$$scope);
};
return [$selectedPanel, panel, selectedPanel, $$scope, slots];
}
class TabPanel extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$a, create_fragment$a, safe_not_equal, {});
}
}
/* src/Components/Embedding.svelte generated by Svelte v3.44.3 */
function create_if_block$5(ctx) {
let if_block_anchor;
let if_block = (!/*$settings*/ ctx[19].eye || /*visible*/ ctx[16]) && create_if_block_1$2(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, dirty) {
if (!/*$settings*/ ctx[19].eye || /*visible*/ ctx[16]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block_1$2(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (295:2) {#if !$settings.eye || visible}
function create_if_block_1$2(ctx) {
let div0;
let t0;
let t1;
let t2;
let div1;
let t3;
let t4;
let mounted;
let dispose;
let if_block0 = /*isImage*/ ctx[3] && create_if_block_7$1(ctx);
let if_block1 = /*isAudio*/ ctx[4] && create_if_block_6$1(ctx);
let if_block2 = /*isVideo*/ ctx[2] && create_if_block_5$1(ctx);
let if_block3 = /*unzipping*/ ctx[17] && create_if_block_4$1(ctx);
let if_block4 = /*isImage*/ ctx[3] && create_if_block_3$2(ctx);
let if_block5 = /*isVideo*/ ctx[2] && create_if_block_2$2(ctx);
return {
c() {
div0 = element("div");
if (if_block0) if_block0.c();
t0 = space();
if (if_block1) if_block1.c();
t1 = space();
if (if_block2) if_block2.c();
t2 = space();
div1 = element("div");
if (if_block3) if_block3.c();
t3 = space();
if (if_block4) if_block4.c();
t4 = space();
if (if_block5) if_block5.c();
attr(div0, "class", "place svelte-yvh28x");
toggle_class(div0, "contract", /*contracted*/ ctx[7]);
attr(div1, "class", "hoverer svelte-yvh28x");
toggle_class(div1, "visible", /*hovering*/ ctx[8] && /*contracted*/ ctx[7]);
toggle_class(div1, "unzipping", /*unzipping*/ ctx[17]);
},
m(target, anchor) {
insert(target, div0, anchor);
if (if_block0) if_block0.m(div0, null);
append(div0, t0);
if (if_block1) if_block1.m(div0, null);
append(div0, t1);
if (if_block2) if_block2.m(div0, null);
/*div0_binding*/ ctx[31](div0);
insert(target, t2, anchor);
insert(target, div1, anchor);
if (if_block3) if_block3.m(div1, null);
append(div1, t3);
if (if_block4) if_block4.m(div1, null);
append(div1, t4);
if (if_block5) if_block5.m(div1, null);
/*div1_binding*/ ctx[33](div1);
if (!mounted) {
dispose = [
listen(div0, "click", click_handler),
listen(div0, "auxclick", auxclick_handler),
listen(div0, "mousedown", /*bepis*/ ctx[1]),
listen(div0, "mouseover", /*hoverStart*/ ctx[20]),
listen(div0, "mouseout", /*hoverStop*/ ctx[21]),
listen(div0, "mousemove", /*hoverUpdate*/ ctx[22]),
listen(div0, "wheel", /*adjustAudio*/ ctx[23])
];
mounted = true;
}
},
p(ctx, dirty) {
if (/*isImage*/ ctx[3]) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_7$1(ctx);
if_block0.c();
if_block0.m(div0, t0);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*isAudio*/ ctx[4]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_6$1(ctx);
if_block1.c();
if_block1.m(div0, t1);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
if (/*isVideo*/ ctx[2]) {
if (if_block2) {
if_block2.p(ctx, dirty);
} else {
if_block2 = create_if_block_5$1(ctx);
if_block2.c();
if_block2.m(div0, null);
}
} else if (if_block2) {
if_block2.d(1);
if_block2 = null;
}
if (dirty[0] & /*contracted*/ 128) {
toggle_class(div0, "contract", /*contracted*/ ctx[7]);
}
if (/*unzipping*/ ctx[17]) {
if (if_block3) {
if_block3.p(ctx, dirty);
} else {
if_block3 = create_if_block_4$1(ctx);
if_block3.c();
if_block3.m(div1, t3);
}
} else if (if_block3) {
if_block3.d(1);
if_block3 = null;
}
if (/*isImage*/ ctx[3]) {
if (if_block4) {
if_block4.p(ctx, dirty);
} else {
if_block4 = create_if_block_3$2(ctx);
if_block4.c();
if_block4.m(div1, t4);
}
} else if (if_block4) {
if_block4.d(1);
if_block4 = null;
}
if (/*isVideo*/ ctx[2]) {
if (if_block5) {
if_block5.p(ctx, dirty);
} else {
if_block5 = create_if_block_2$2(ctx);
if_block5.c();
if_block5.m(div1, null);
}
} else if (if_block5) {
if_block5.d(1);
if_block5 = null;
}
if (dirty[0] & /*hovering, contracted*/ 384) {
toggle_class(div1, "visible", /*hovering*/ ctx[8] && /*contracted*/ ctx[7]);
}
if (dirty[0] & /*unzipping*/ 131072) {
toggle_class(div1, "unzipping", /*unzipping*/ ctx[17]);
}
},
d(detaching) {
if (detaching) detach(div0);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
if (if_block2) if_block2.d();
/*div0_binding*/ ctx[31](null);
if (detaching) detach(t2);
if (detaching) detach(div1);
if (if_block3) if_block3.d();
if (if_block4) if_block4.d();
if (if_block5) if_block5.d();
/*div1_binding*/ ctx[33](null);
mounted = false;
run_all(dispose);
}
};
}
// (309:6) {#if isImage}
function create_if_block_7$1(ctx) {
let img;
let img_alt_value;
let img_src_value;
return {
c() {
img = element("img");
attr(img, "referrerpolicy", "no-referrer");
attr(img, "alt", img_alt_value = /*file*/ ctx[0].filename);
if (!src_url_equal(img.src, img_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) attr(img, "src", img_src_value);
attr(img, "class", "svelte-yvh28x");
},
m(target, anchor) {
insert(target, img, anchor);
/*img_binding*/ ctx[29](img);
},
p(ctx, dirty) {
if (dirty[0] & /*file*/ 1 && img_alt_value !== (img_alt_value = /*file*/ ctx[0].filename)) {
attr(img, "alt", img_alt_value);
}
if (dirty[0] & /*furl, url*/ 32832 && !src_url_equal(img.src, img_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) {
attr(img, "src", img_src_value);
}
},
d(detaching) {
if (detaching) detach(img);
/*img_binding*/ ctx[29](null);
}
};
}
// (318:6) {#if isAudio}
function create_if_block_6$1(ctx) {
let audio;
let source;
let source_src_value;
let audio_src_value;
let audio_loop_value;
let audio_alt_value;
return {
c() {
audio = element("audio");
source = element("source");
if (!src_url_equal(source.src, source_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) attr(source, "src", source_src_value);
attr(source, "type", /*ftype*/ ctx[9]);
attr(audio, "referrerpolicy", "no-referrer");
audio.controls = true;
if (!src_url_equal(audio.src, audio_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) attr(audio, "src", audio_src_value);
audio.loop = audio_loop_value = /*$settings*/ ctx[19].loop;
attr(audio, "alt", audio_alt_value = /*file*/ ctx[0].filename);
},
m(target, anchor) {
insert(target, audio, anchor);
append(audio, source);
},
p(ctx, dirty) {
if (dirty[0] & /*furl, url*/ 32832 && !src_url_equal(source.src, source_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) {
attr(source, "src", source_src_value);
}
if (dirty[0] & /*ftype*/ 512) {
attr(source, "type", /*ftype*/ ctx[9]);
}
if (dirty[0] & /*furl, url*/ 32832 && !src_url_equal(audio.src, audio_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) {
attr(audio, "src", audio_src_value);
}
if (dirty[0] & /*$settings*/ 524288 && audio_loop_value !== (audio_loop_value = /*$settings*/ ctx[19].loop)) {
audio.loop = audio_loop_value;
}
if (dirty[0] & /*file*/ 1 && audio_alt_value !== (audio_alt_value = /*file*/ ctx[0].filename)) {
attr(audio, "alt", audio_alt_value);
}
},
d(detaching) {
if (detaching) detach(audio);
}
};
}
// (329:6) {#if isVideo}
function create_if_block_5$1(ctx) {
let video;
let source;
let source_src_value;
let video_loop_value;
return {
c() {
video = element("video");
source = element("source");
attr(source, "referrerpolicy", "no-referrer");
if (!src_url_equal(source.src, source_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) attr(source, "src", source_src_value);
attr(video, "type", /*ftype*/ ctx[9]);
attr(video, "referrerpolicy", "no-referrer");
video.loop = video_loop_value = /*$settings*/ ctx[19].loop;
attr(video, "class", "svelte-yvh28x");
},
m(target, anchor) {
insert(target, video, anchor);
append(video, source);
/*video_binding*/ ctx[30](video);
},
p(ctx, dirty) {
if (dirty[0] & /*furl, url*/ 32832 && !src_url_equal(source.src, source_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) {
attr(source, "src", source_src_value);
}
if (dirty[0] & /*ftype*/ 512) {
attr(video, "type", /*ftype*/ ctx[9]);
}
if (dirty[0] & /*$settings*/ 524288 && video_loop_value !== (video_loop_value = /*$settings*/ ctx[19].loop)) {
video.loop = video_loop_value;
}
},
d(detaching) {
if (detaching) detach(video);
/*video_binding*/ ctx[30](null);
}
};
}
// (349:6) {#if unzipping}
function create_if_block_4$1(ctx) {
let span;
let t0;
let t1_value = /*progress*/ ctx[18][0] + "";
let t1;
let t2;
let t3_value = /*progress*/ ctx[18][1] + "";
let t3;
let t4;
return {
c() {
span = element("span");
t0 = text$1("[");
t1 = text$1(t1_value);
t2 = text$1(" / ");
t3 = text$1(t3_value);
t4 = text$1("]");
attr(span, "class", "progress svelte-yvh28x");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
append(span, t1);
append(span, t2);
append(span, t3);
append(span, t4);
},
p(ctx, dirty) {
if (dirty[0] & /*progress*/ 262144 && t1_value !== (t1_value = /*progress*/ ctx[18][0] + "")) set_data(t1, t1_value);
if (dirty[0] & /*progress*/ 262144 && t3_value !== (t3_value = /*progress*/ ctx[18][1] + "")) set_data(t3, t3_value);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (353:6) {#if isImage}
function create_if_block_3$2(ctx) {
let img;
let img_alt_value;
let img_src_value;
return {
c() {
img = element("img");
attr(img, "alt", img_alt_value = /*file*/ ctx[0].filename);
if (!src_url_equal(img.src, img_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) attr(img, "src", img_src_value);
attr(img, "class", "svelte-yvh28x");
},
m(target, anchor) {
insert(target, img, anchor);
},
p(ctx, dirty) {
if (dirty[0] & /*file*/ 1 && img_alt_value !== (img_alt_value = /*file*/ ctx[0].filename)) {
attr(img, "alt", img_alt_value);
}
if (dirty[0] & /*furl, url*/ 32832 && !src_url_equal(img.src, img_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) {
attr(img, "src", img_src_value);
}
},
d(detaching) {
if (detaching) detach(img);
}
};
}
// (356:6) {#if isVideo}
function create_if_block_2$2(ctx) {
let video;
let source;
let source_src_value;
let video_loop_value;
return {
c() {
video = element("video");
source = element("source");
attr(source, "type", /*ftype*/ ctx[9]);
if (!src_url_equal(source.src, source_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) attr(source, "src", source_src_value);
attr(source, "data-test", "");
video.loop = video_loop_value = /*$settings*/ ctx[19].loop;
attr(video, "class", "svelte-yvh28x");
},
m(target, anchor) {
insert(target, video, anchor);
append(video, source);
/*video_binding_1*/ ctx[32](video);
},
p(ctx, dirty) {
if (dirty[0] & /*ftype*/ 512) {
attr(source, "type", /*ftype*/ ctx[9]);
}
if (dirty[0] & /*furl, url*/ 32832 && !src_url_equal(source.src, source_src_value = /*furl*/ ctx[15] || /*url*/ ctx[6])) {
attr(source, "src", source_src_value);
}
if (dirty[0] & /*$settings*/ 524288 && video_loop_value !== (video_loop_value = /*$settings*/ ctx[19].loop)) {
video.loop = video_loop_value;
}
},
d(detaching) {
if (detaching) detach(video);
/*video_binding_1*/ ctx[32](null);
}
};
}
function create_fragment$9(ctx) {
let if_block_anchor;
let if_block = !/*isText*/ ctx[5] && create_if_block$5(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, dirty) {
if (!/*isText*/ ctx[5]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$5(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function hasAudio(video) {
return video.mozHasAudio || !!video.webkitAudioDecodedByteCount || !!(video.audioTracks && video.audioTracks.length);
}
const click_handler = e => e.preventDefault();
const auxclick_handler = e => e.preventDefault();
function instance$9($$self, $$props, $$invalidate) {
let $settings;
let $appState;
component_subscribe($$self, settings, $$value => $$invalidate(19, $settings = $$value));
component_subscribe($$self, appState, $$value => $$invalidate(38, $appState = $$value));
const dispatch = createEventDispatcher();
let { file } = $$props;
let isVideo = false;
let isImage = false;
let isAudio = false;
let isText = false;
let url = "";
let settled = false;
let contracted = true;
let hovering = false;
let ftype = "";
let place;
let hoverElem;
let imgElem;
let videoElem;
let hoverVideo;
let dims = [0, 0];
let furl = undefined;
let visible = false;
const isNotChrome = !navigator.userAgent.includes("Chrome/");
let { id = "" } = $$props;
document.addEventListener("reveal", e => {
if (e.detail.id == id) $$invalidate(16, visible = !visible);
});
function isContracted() {
return contracted;
}
let content;
beforeUpdate(async () => {
if (settled) return;
settled = true;
const thumb = file.thumbnail || file.data;
let type;
if (typeof thumb != "string") {
let buff = Buffer$1.isBuffer(thumb) ? thumb : await thumb();
type = await fileTypeFromBuffer(buff);
if (!type && file.filename.endsWith(".txt") && file.filename.startsWith("message")) {
type = { ext: "txt", mime: "text/plain" };
}
content = new Blob([buff], { type: type && type.mime });
$$invalidate(6, url = URL.createObjectURL(content));
if (!type) return;
} else {
let head = await getHeaders(thumb);
$$invalidate(6, url = thumb);
type = {
ext: "",
mime: head["content-type"].split(";")[0].trim()
};
}
$$invalidate(9, ftype = type.mime);
$$invalidate(2, isVideo = type.mime.startsWith("video/"));
$$invalidate(4, isAudio = type.mime.startsWith("audio/"));
$$invalidate(3, isImage = type.mime.startsWith("image/"));
$$invalidate(5, isText = type.mime.startsWith("text/plain"));
dispatch("fileinfo", { type });
if (isImage) {
$$invalidate(7, contracted = !$settings.xpi);
}
if (isVideo) {
$$invalidate(7, contracted = !$settings.xpv && !$appState.isCatalog);
}
if ($appState.isCatalog) $$invalidate(7, contracted = true);
if ($settings.pre) {
unzip(); // not awaiting on purpose
}
if ($settings.prev) {
let obs = new IntersectionObserver((entries, obs) => {
for (const item of entries) {
if (!item.isIntersecting) continue;
unzip();
obs.unobserve(place);
}
},
{
root: null,
rootMargin: "0px",
threshold: 0.01
});
obs.observe(place);
}
});
let unzipping = false;
let progress = [0, 0];
async function unzip() {
if (!file.thumbnail) return;
if (unzipping) return;
let type;
if (typeof file.data != "string") {
$$invalidate(17, unzipping = true);
let lisn = new EventTarget();
lisn.addEventListener("progress", e => {
$$invalidate(18, progress = e.detail);
});
let full = Buffer$1.isBuffer(file.data)
? file.data
: await file.data(lisn);
type = await fileTypeFromBuffer(full);
if (!type && file.filename.endsWith(".txt") && file.filename.startsWith("message")) {
type = { ext: "txt", mime: "text/plain" };
}
content = new Blob([full], { type: type && type.mime });
$$invalidate(15, furl = URL.createObjectURL(content));
} else {
$$invalidate(6, url = file.data);
$$invalidate(15, furl = file.data);
let head = await getHeaders(file.data);
type = {
ext: "",
mime: head["content-type"].split(";")[0].trim()
};
}
if (!type) return;
$$invalidate(9, ftype = type.mime);
$$invalidate(2, isVideo = type.mime.startsWith("video/"));
$$invalidate(4, isAudio = type.mime.startsWith("audio/"));
$$invalidate(3, isImage = type.mime.startsWith("image/"));
$$invalidate(5, isText = type.mime.startsWith("text/plain"));
$$invalidate(17, unzipping = false);
dispatch("fileinfo", { type });
if (hovering) {
// reset hovering to recompute proper image coordinates
setTimeout(
async () => {
do {
hoverUpdate();
await new Promise(_ => setTimeout(_, 20));
} while (dims[0] == 0 && dims[1] == 0);
},
20
);
}
}
let { inhibitExpand = false } = $$props;
async function bepis(ev) {
dispatch("click");
if (inhibitExpand) return;
if ($appState.isCatalog) return;
if (ev.button == 0) {
$$invalidate(7, contracted = !contracted);
if (hovering) hoverStop();
if (contracted && isVideo) {
$$invalidate(13, videoElem.controls = false, videoElem);
videoElem.pause();
}
if (!contracted && isVideo) {
$$invalidate(13, videoElem.controls = true, videoElem);
// has to be delayed
setTimeout(
async () => {
$$invalidate(13, videoElem.currentTime = hoverVideo.currentTime || 0, videoElem);
await videoElem.play();
},
10
);
}
if (file.thumbnail && !furl) {
// don't know how you managed to click before hovering but oh well
unzip();
}
ev.preventDefault();
} else if (ev.button == 1) {
// middle click
let src = furl || url;
if (ev.altKey && file.source) {
src = file.source;
}
if (ev.shiftKey && file.page) {
src = file.page.url;
}
ev.preventDefault();
if (isNotChrome) {
window.open(src, "_blank");
} else await Platform.openInTab(src, { active: false, insert: true });
}
}
const getViewport = () => (typeof visualViewport != "undefined"
? () => [visualViewport.width, visualViewport.height]
: () => [document.documentElement.clientWidth, document.documentElement.clientHeight])();
function recompute() {
const [sw, sh] = getViewport();
let [iw, ih] = [0, 0];
if (isImage) {
[iw, ih] = [imgElem.naturalWidth, imgElem.naturalHeight];
} else if (isVideo) {
[iw, ih] = [videoElem.videoWidth, videoElem.videoHeight];
}
let scale = Math.min(1, sw / iw, sh / ih);
dims = [~~(iw * scale), ~~(ih * scale)];
$$invalidate(11, hoverElem.style.width = `${dims[0]}px`, hoverElem);
$$invalidate(11, hoverElem.style.height = `${dims[1]}px`, hoverElem);
}
async function hoverStart(ev) {
if (!(isVideo || isImage)) return;
if ($settings.dh) return;
if (file.thumbnail && !furl) {
unzip();
}
if (!isImage && !isVideo) return;
if (!contracted) return;
recompute();
$$invalidate(8, hovering = true);
if (isVideo) {
try {
await hoverVideo.play();
} catch(e) {
// probably didn't interact with document error, mute the video and try again?
$$invalidate(14, hoverVideo.muted = true, hoverVideo);
$$invalidate(14, hoverVideo.volume = 0, hoverVideo);
await hoverVideo.play();
}
}
}
function hoverStop(ev) {
if ($settings.dh) return;
$$invalidate(8, hovering = false);
if (isVideo) hoverVideo.pause();
}
let lastev;
function hoverUpdate(ev) {
lastev = lastev || ev;
if ($settings.dh) return;
if (!contracted) return;
if (!(isVideo || isImage)) return;
recompute(); // yeah I gave up
const [sw, sh] = [visualViewport.width, visualViewport.height];
// shamelessly stolen from 4chanX
if (dims[0] == 0 && dims[1] == 0) recompute();
let width = dims[0];
let height = dims[1] + 25;
let { clientX, clientY } = ev || lastev;
let top = Math.max(0, clientY * (sh - height) / sh);
let threshold = sw / 2;
let marginX = (clientX <= threshold ? clientX : sw - clientX) + 45;
marginX = Math.min(marginX, sw - width);
marginX = marginX + "px";
let [left, right] = clientX <= threshold ? [marginX, ""] : ["", marginX];
let { style } = hoverElem;
style.top = top + "px";
style.left = left;
style.right = right;
}
function adjustAudio(ev) {
if (!$settings.ca) return;
if (!isVideo) return;
if ($settings.dh && contracted) return;
if (!hasAudio(videoElem)) return;
let vol = videoElem.volume * (ev.deltaY > 0 ? 0.9 : 1.1);
vol = Math.max(0, Math.min(1, vol));
$$invalidate(13, videoElem.volume = vol, videoElem);
$$invalidate(14, hoverVideo.volume = videoElem.volume, hoverVideo);
$$invalidate(14, hoverVideo.muted = vol < 0, hoverVideo);
ev.preventDefault();
}
function img_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
imgElem = $$value;
$$invalidate(12, imgElem);
});
}
function video_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
videoElem = $$value;
$$invalidate(13, videoElem);
});
}
function div0_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
place = $$value;
$$invalidate(10, place);
});
}
function video_binding_1($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
hoverVideo = $$value;
$$invalidate(14, hoverVideo);
});
}
function div1_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
hoverElem = $$value;
$$invalidate(11, hoverElem);
});
}
$$self.$$set = $$props => {
if ('file' in $$props) $$invalidate(0, file = $$props.file);
if ('id' in $$props) $$invalidate(26, id = $$props.id);
if ('inhibitExpand' in $$props) $$invalidate(28, inhibitExpand = $$props.inhibitExpand);
};
return [
file,
bepis,
isVideo,
isImage,
isAudio,
isText,
url,
contracted,
hovering,
ftype,
place,
hoverElem,
imgElem,
videoElem,
hoverVideo,
furl,
visible,
unzipping,
progress,
$settings,
hoverStart,
hoverStop,
hoverUpdate,
adjustAudio,
dispatch,
isNotChrome,
id,
isContracted,
inhibitExpand,
img_binding,
video_binding,
div0_binding,
video_binding_1,
div1_binding
];
}
class Embedding extends SvelteComponent {
constructor(options) {
super();
init$3(
this,
options,
instance$9,
create_fragment$9,
safe_not_equal,
{
dispatch: 24,
file: 0,
isNotChrome: 25,
id: 26,
isContracted: 27,
inhibitExpand: 28,
bepis: 1
},
null,
[-1, -1]
);
}
get dispatch() {
return this.$$.ctx[24];
}
get file() {
return this.$$.ctx[0];
}
set file(file) {
this.$$set({ file });
flush();
}
get isNotChrome() {
return this.$$.ctx[25];
}
get id() {
return this.$$.ctx[26];
}
set id(id) {
this.$$set({ id });
flush();
}
get isContracted() {
return this.$$.ctx[27];
}
get inhibitExpand() {
return this.$$.ctx[28];
}
set inhibitExpand(inhibitExpand) {
this.$$set({ inhibitExpand });
flush();
}
get bepis() {
return this.$$.ctx[1];
}
}
/* src/Components/HydrusSearch.svelte generated by Svelte v3.44.3 */
function get_each_context$6(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i];
return child_ctx;
}
function get_each_context_1$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
return child_ctx;
}
// (53:8) {#each tags as tag}
function create_each_block_1$1(ctx) {
let tag;
let current;
function toggle_handler() {
return /*toggle_handler*/ ctx[6](/*tag*/ ctx[12]);
}
tag = new Tag({ props: { tag: /*tag*/ ctx[12] } });
tag.$on("toggle", toggle_handler);
return {
c() {
create_component(tag.$$.fragment);
},
m(target, anchor) {
mount_component(tag, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const tag_changes = {};
if (dirty & /*tags*/ 1) tag_changes.tag = /*tag*/ ctx[12];
tag.$set(tag_changes);
},
i(local) {
if (current) return;
transition_in(tag.$$.fragment, local);
current = true;
},
o(local) {
transition_out(tag.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(tag, detaching);
}
};
}
// (59:4) {:else}
function create_else_block$1(ctx) {
let div;
let each_blocks = [];
let each_1_lookup = new Map();
let current;
let each_value = /*maps*/ ctx[2];
const get_key = ctx => /*map*/ ctx[9][0];
for (let i = 0; i < each_value.length; i += 1) {
let child_ctx = get_each_context$6(ctx, each_value, i);
let key = get_key(child_ctx);
each_1_lookup.set(key, each_blocks[i] = create_each_block$6(key, child_ctx));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "results svelte-1qi3e99");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
current = true;
},
p(ctx, dirty) {
if (dirty & /*maps, addToEmbeds*/ 4) {
each_value = /*maps*/ ctx[2];
group_outros();
each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value, each_1_lookup, div, outro_and_destroy_block, create_each_block$6, null, get_each_context$6);
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(div);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].d();
}
}
};
}
// (57:4) {#if loading}
function create_if_block$4(ctx) {
let t;
return {
c() {
t = text$1("Loading...");
},
m(target, anchor) {
insert(target, t, anchor);
},
p: noop$1,
i: noop$1,
o: noop$1,
d(detaching) {
if (detaching) detach(t);
}
};
}
// (61:12) {#each maps as map (map[0])}
function create_each_block$6(key_1, ctx) {
let first;
let embedding;
let current;
function click_handler() {
return /*click_handler*/ ctx[7](/*map*/ ctx[9]);
}
embedding = new Embedding({
props: {
inhibitExpand: true,
id: "only",
file: /*map*/ ctx[9][1]
}
});
embedding.$on("click", click_handler);
return {
key: key_1,
first: null,
c() {
first = empty();
create_component(embedding.$$.fragment);
this.first = first;
},
m(target, anchor) {
insert(target, first, anchor);
mount_component(embedding, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const embedding_changes = {};
if (dirty & /*maps*/ 4) embedding_changes.file = /*map*/ ctx[9][1];
embedding.$set(embedding_changes);
},
i(local) {
if (current) return;
transition_in(embedding.$$.fragment, local);
current = true;
},
o(local) {
transition_out(embedding.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(first);
destroy_component(embedding, detaching);
}
};
}
function create_fragment$8(ctx) {
let div1;
let input;
let t0;
let details;
let t5;
let div0;
let t6;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
let each_value_1 = /*tags*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks[i] = create_each_block_1$1(get_each_context_1$1(ctx, each_value_1, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
const if_block_creators = [create_if_block$4, create_else_block$1];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*loading*/ ctx[1]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
div1 = element("div");
input = element("input");
t0 = space();
details = element("details");
details.innerHTML = `<summary class="svelte-1qi3e99">Tips</summary>
Press enter without entering a tag to refresh. <br/>
Files are picked randomly <br/>
Click on a file to embed it <br/>`;
t5 = space();
div0 = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t6 = space();
if_block.c();
attr(input, "type", "text");
attr(input, "placeholder", "Input a tag here, then press enter");
attr(details, "class", "svelte-1qi3e99");
attr(div0, "class", "tagcont svelte-1qi3e99");
attr(div1, "class", "cont svelte-1qi3e99");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, input);
append(div1, t0);
append(div1, details);
append(div1, t5);
append(div1, div0);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div0, null);
}
append(div1, t6);
if_blocks[current_block_type_index].m(div1, null);
current = true;
if (!mounted) {
dispose = listen(input, "keydown", /*keydown_handler*/ ctx[5]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*tags, removeTag*/ 9) {
each_value_1 = /*tags*/ ctx[0];
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1$1(ctx, each_value_1, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block_1$1(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div0, null);
}
}
group_outros();
for (i = each_value_1.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(div1, null);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_1.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block);
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_each(each_blocks, detaching);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$8($$self, $$props, $$invalidate) {
let $appState;
component_subscribe($$self, appState, $$value => $$invalidate(8, $appState = $$value));
let tags = [];
let loading = false;
function removeTag(t) {
$$invalidate(0, tags = tags.filter(e => e != t));
update();
}
let maps = [];
async function update() {
$$invalidate(1, loading = true);
if ($appState.client) {
try {
if (tags.length == 0) {
$$invalidate(2, maps = []);
$$invalidate(1, loading = false);
return;
}
$$invalidate(2, maps = await getFileFromHydrus($appState.client, tags.concat(["system:limit=32"]), { file_sort_type: 4 }));
} catch {
}
}
$$invalidate(1, loading = false);
}
onMount(() => {
return update();
});
const keydown_handler = ev => {
if (ev.key == "Enter") {
if (ev.currentTarget.value) $$invalidate(0, tags = [...tags, ev.currentTarget.value]);
ev.currentTarget.value = "";
update();
}
};
const toggle_handler = tag => removeTag(tag);
const click_handler = map => addToEmbeds(map[1]);
return [
tags,
loading,
maps,
removeTag,
update,
keydown_handler,
toggle_handler,
click_handler
];
}
class HydrusSearch extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$8, create_fragment$8, safe_not_equal, {});
}
}
/* src/Components/App.svelte generated by Svelte v3.44.3 */
function get_each_context$5(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[48] = list[i];
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[51] = list[i];
child_ctx[53] = i;
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[54] = list[i];
child_ctx[53] = i;
return child_ctx;
}
function get_each_context_3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[56] = list[i];
child_ctx[53] = i;
return child_ctx;
}
// (66:8) <Tab>
function create_default_slot_12(ctx) {
let t;
return {
c() {
t = text$1("General");
},
m(target, anchor) {
insert(target, t, anchor);
},
d(detaching) {
if (detaching) detach(t);
}
};
}
// (67:8) <Tab>
function create_default_slot_11(ctx) {
let t;
return {
c() {
t = text$1("External");
},
m(target, anchor) {
insert(target, t, anchor);
},
d(detaching) {
if (detaching) detach(t);
}
};
}
// (68:8) <Tab>
function create_default_slot_10(ctx) {
let t;
return {
c() {
t = text$1("File Host");
},
m(target, anchor) {
insert(target, t, anchor);
},
d(detaching) {
if (detaching) detach(t);
}
};
}
// (69:8) <Tab>
function create_default_slot_9(ctx) {
let t;
return {
c() {
t = text$1("Thread Watcher");
},
m(target, anchor) {
insert(target, t, anchor);
},
d(detaching) {
if (detaching) detach(t);
}
};
}
// (70:8) {#if $appState.akValid}
function create_if_block_8(ctx) {
let tab;
let current;
tab = new Tab({
props: {
$$slots: { default: [create_default_slot_8] },
$$scope: { ctx }
}
});
return {
c() {
create_component(tab.$$.fragment);
},
m(target, anchor) {
mount_component(tab, target, anchor);
current = true;
},
i(local) {
if (current) return;
transition_in(tab.$$.fragment, local);
current = true;
},
o(local) {
transition_out(tab.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(tab, detaching);
}
};
}
// (71:10) <Tab>
function create_default_slot_8(ctx) {
let t;
return {
c() {
t = text$1("Hydrus");
},
m(target, anchor) {
insert(target, t, anchor);
},
d(detaching) {
if (detaching) detach(t);
}
};
}
// (65:6) <TabList>
function create_default_slot_7(ctx) {
let tab0;
let t0;
let tab1;
let t1;
let tab2;
let t2;
let tab3;
let t3;
let if_block_anchor;
let current;
tab0 = new Tab({
props: {
$$slots: { default: [create_default_slot_12] },
$$scope: { ctx }
}
});
tab1 = new Tab({
props: {
$$slots: { default: [create_default_slot_11] },
$$scope: { ctx }
}
});
tab2 = new Tab({
props: {
$$slots: { default: [create_default_slot_10] },
$$scope: { ctx }
}
});
tab3 = new Tab({
props: {
$$slots: { default: [create_default_slot_9] },
$$scope: { ctx }
}
});
let if_block = /*$appState*/ ctx[6].akValid && create_if_block_8(ctx);
return {
c() {
create_component(tab0.$$.fragment);
t0 = space();
create_component(tab1.$$.fragment);
t1 = space();
create_component(tab2.$$.fragment);
t2 = space();
create_component(tab3.$$.fragment);
t3 = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(tab0, target, anchor);
insert(target, t0, anchor);
mount_component(tab1, target, anchor);
insert(target, t1, anchor);
mount_component(tab2, target, anchor);
insert(target, t2, anchor);
mount_component(tab3, target, anchor);
insert(target, t3, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const tab0_changes = {};
if (dirty[1] & /*$$scope*/ 134217728) {
tab0_changes.$$scope = { dirty, ctx };
}
tab0.$set(tab0_changes);
const tab1_changes = {};
if (dirty[1] & /*$$scope*/ 134217728) {
tab1_changes.$$scope = { dirty, ctx };
}
tab1.$set(tab1_changes);
const tab2_changes = {};
if (dirty[1] & /*$$scope*/ 134217728) {
tab2_changes.$$scope = { dirty, ctx };
}
tab2.$set(tab2_changes);
const tab3_changes = {};
if (dirty[1] & /*$$scope*/ 134217728) {
tab3_changes.$$scope = { dirty, ctx };
}
tab3.$set(tab3_changes);
if (/*$appState*/ ctx[6].akValid) {
if (if_block) {
if (dirty[0] & /*$appState*/ 64) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_8(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(tab0.$$.fragment, local);
transition_in(tab1.$$.fragment, local);
transition_in(tab2.$$.fragment, local);
transition_in(tab3.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(tab0.$$.fragment, local);
transition_out(tab1.$$.fragment, local);
transition_out(tab2.$$.fragment, local);
transition_out(tab3.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
destroy_component(tab0, detaching);
if (detaching) detach(t0);
destroy_component(tab1, detaching);
if (detaching) detach(t1);
destroy_component(tab2, detaching);
if (detaching) detach(t2);
destroy_component(tab3, detaching);
if (detaching) detach(t3);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (100:8) {#if $settings.eye}
function create_if_block_7(ctx) {
let label;
let input;
let t;
let mounted;
let dispose;
return {
c() {
label = element("label");
input = element("input");
t = text$1("\n Hide original content when hidden content is visible.");
attr(input, "type", "checkbox");
},
m(target, anchor) {
insert(target, label, anchor);
append(label, input);
input.checked = /*$settings*/ ctx[5].ho;
append(label, t);
if (!mounted) {
dispose = listen(input, "change", /*input_change_handler*/ ctx[19]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32) {
input.checked = /*$settings*/ ctx[5].ho;
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
// (138:8) {#if $settings.hyd}
function create_if_block_4(ctx) {
let t0;
let label;
let t1;
let a;
let t3;
let input;
let t4;
let if_block1_anchor;
let mounted;
let dispose;
let if_block0 = /*$appState*/ ctx[6].herror && create_if_block_6(ctx);
let if_block1 = /*$appState*/ ctx[6].akValid && create_if_block_5(ctx);
return {
c() {
if (if_block0) if_block0.c();
t0 = space();
label = element("label");
t1 = text$1("Hydrus Access Key\n \n ");
a = element("a");
a.textContent = "?";
t3 = space();
input = element("input");
t4 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(a, "title", "Only requires Search Files permission. See Hydrus docs on where to set this up.");
attr(input, "type", "text");
attr(input, "class", "svelte-1epvqgf");
attr(label, "class", "svelte-1epvqgf");
},
m(target, anchor) {
if (if_block0) if_block0.m(target, anchor);
insert(target, t0, anchor);
insert(target, label, anchor);
append(label, t1);
append(label, a);
append(label, t3);
append(label, input);
set_input_value(input, /*$settings*/ ctx[5].ak);
insert(target, t4, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
if (!mounted) {
dispose = listen(input, "input", /*input_input_handler*/ ctx[27]);
mounted = true;
}
},
p(ctx, dirty) {
if (/*$appState*/ ctx[6].herror) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_6(ctx);
if_block0.c();
if_block0.m(t0.parentNode, t0);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (dirty[0] & /*$settings*/ 32 && input.value !== /*$settings*/ ctx[5].ak) {
set_input_value(input, /*$settings*/ ctx[5].ak);
}
if (/*$appState*/ ctx[6].akValid) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_5(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t0);
if (detaching) detach(label);
if (detaching) detach(t4);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
dispose();
}
};
}
// (139:10) {#if $appState.herror}
function create_if_block_6(ctx) {
let span;
let t_value = /*$appState*/ ctx[6].herror + "";
let t;
return {
c() {
span = element("span");
t = text$1(t_value);
attr(span, "class", "error svelte-1epvqgf");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
},
p(ctx, dirty) {
if (dirty[0] & /*$appState*/ 64 && t_value !== (t_value = /*$appState*/ ctx[6].herror + "")) set_data(t, t_value);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (151:10) {#if $appState.akValid}
function create_if_block_5(ctx) {
let label0;
let t0;
let input0;
let t1;
let t2;
let label1;
let input1;
let mounted;
let dispose;
return {
c() {
label0 = element("label");
t0 = text$1("Auto-embed ");
input0 = element("input");
t1 = text$1("\n random files");
t2 = space();
label1 = element("label");
input1 = element("input");
set_style(input0, "width", "5ch");
attr(input0, "type", "number");
attr(input0, "class", "svelte-1epvqgf");
attr(label0, "class", "svelte-1epvqgf");
attr(input1, "placeholder", "Restrict to these tags (space to separate tags, _ to separate words)");
attr(input1, "type", "text");
attr(input1, "class", "svelte-1epvqgf");
attr(label1, "class", "svelte-1epvqgf");
},
m(target, anchor) {
insert(target, label0, anchor);
append(label0, t0);
append(label0, input0);
set_input_value(input0, /*$settings*/ ctx[5].auto_embed);
append(label0, t1);
insert(target, t2, anchor);
insert(target, label1, anchor);
append(label1, input1);
set_input_value(input1, /*$settings*/ ctx[5].auto_tags);
if (!mounted) {
dispose = [
listen(input0, "input", /*input0_input_handler*/ ctx[28]),
listen(input1, "input", /*input1_input_handler*/ ctx[29])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32 && to_number(input0.value) !== /*$settings*/ ctx[5].auto_embed) {
set_input_value(input0, /*$settings*/ ctx[5].auto_embed);
}
if (dirty[0] & /*$settings*/ 32 && input1.value !== /*$settings*/ ctx[5].auto_tags) {
set_input_value(input1, /*$settings*/ ctx[5].auto_tags);
}
},
d(detaching) {
if (detaching) detach(label0);
if (detaching) detach(t2);
if (detaching) detach(label1);
mounted = false;
run_all(dispose);
}
};
}
// (74:6) <TabPanel>
function create_default_slot_6(ctx) {
let label0;
let input0;
let t0;
let t1;
let label1;
let input1;
let t2;
let t3;
let label2;
let input2;
let t4;
let t5;
let label3;
let input3;
let t6;
let t7;
let label4;
let input4;
let t8;
let t9;
let label5;
let input5;
let t10;
let t11;
let t12;
let label6;
let input6;
let t13;
let t14;
let label7;
let input7;
let t15;
let t16;
let label8;
let input8;
let t17;
let t18;
let label9;
let input9;
let t19;
let t20;
let label10;
let input10;
let t21;
let t22;
let label11;
let input11;
let t23;
let a;
let t25;
let label12;
let input12;
let t26;
let t27;
let if_block1_anchor;
let mounted;
let dispose;
let if_block0 = /*$settings*/ ctx[5].eye && create_if_block_7(ctx);
let if_block1 = /*$settings*/ ctx[5].hyd && create_if_block_4(ctx);
return {
c() {
label0 = element("label");
input0 = element("input");
t0 = text$1("\n Check for new versions at startup.");
t1 = space();
label1 = element("label");
input1 = element("input");
t2 = text$1("\n Autoexpand Images on opening.");
t3 = space();
label2 = element("label");
input2 = element("input");
t4 = text$1("\n Autoexpand Videos on opening.");
t5 = space();
label3 = element("label");
input3 = element("input");
t6 = text$1("\n Loop media content.");
t7 = space();
label4 = element("label");
input4 = element("input");
t8 = text$1("\n Disable hover preview.");
t9 = space();
label5 = element("label");
input5 = element("input");
t10 = text$1("\n Hide embedded content behind an eye.");
t11 = space();
if (if_block0) if_block0.c();
t12 = space();
label6 = element("label");
input6 = element("input");
t13 = text$1("\n Preload external files.");
t14 = space();
label7 = element("label");
input7 = element("input");
t15 = text$1("\n Preload external files when they are in view.");
t16 = space();
label8 = element("label");
input8 = element("input");
t17 = text$1("\n Hotlink content.");
t18 = space();
label9 = element("label");
input9 = element("input");
t19 = text$1("\n Control audio on videos with mouse wheel.");
t20 = space();
label10 = element("label");
input10 = element("input");
t21 = text$1("\n Show Minimap");
t22 = space();
label11 = element("label");
input11 = element("input");
t23 = text$1("\n \n Disable embedded file preloading");
a = element("a");
a.textContent = "?";
t25 = space();
label12 = element("label");
input12 = element("input");
t26 = text$1("\n \n Enable Hydrus Integration");
t27 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(input0, "type", "checkbox");
attr(input1, "type", "checkbox");
attr(input2, "type", "checkbox");
attr(input3, "type", "checkbox");
attr(input4, "type", "checkbox");
attr(input5, "type", "checkbox");
attr(input6, "type", "checkbox");
attr(input7, "type", "checkbox");
attr(input8, "type", "checkbox");
attr(input9, "type", "checkbox");
attr(input10, "type", "checkbox");
attr(input11, "type", "checkbox");
attr(a, "title", "You might still want to enable 'preload external files'");
attr(input12, "type", "checkbox");
},
m(target, anchor) {
insert(target, label0, anchor);
append(label0, input0);
input0.checked = /*$settings*/ ctx[5].vercheck;
append(label0, t0);
insert(target, t1, anchor);
insert(target, label1, anchor);
append(label1, input1);
input1.checked = /*$settings*/ ctx[5].xpi;
append(label1, t2);
insert(target, t3, anchor);
insert(target, label2, anchor);
append(label2, input2);
input2.checked = /*$settings*/ ctx[5].xpv;
append(label2, t4);
insert(target, t5, anchor);
insert(target, label3, anchor);
append(label3, input3);
input3.checked = /*$settings*/ ctx[5].loop;
append(label3, t6);
insert(target, t7, anchor);
insert(target, label4, anchor);
append(label4, input4);
input4.checked = /*$settings*/ ctx[5].dh;
append(label4, t8);
insert(target, t9, anchor);
insert(target, label5, anchor);
append(label5, input5);
input5.checked = /*$settings*/ ctx[5].eye;
append(label5, t10);
insert(target, t11, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t12, anchor);
insert(target, label6, anchor);
append(label6, input6);
input6.checked = /*$settings*/ ctx[5].pre;
append(label6, t13);
insert(target, t14, anchor);
insert(target, label7, anchor);
append(label7, input7);
input7.checked = /*$settings*/ ctx[5].prev;
append(label7, t15);
insert(target, t16, anchor);
insert(target, label8, anchor);
append(label8, input8);
input8.checked = /*$settings*/ ctx[5].hotlink;
append(label8, t17);
insert(target, t18, anchor);
insert(target, label9, anchor);
append(label9, input9);
input9.checked = /*$settings*/ ctx[5].ca;
append(label9, t19);
insert(target, t20, anchor);
insert(target, label10, anchor);
append(label10, input10);
input10.checked = /*$settings*/ ctx[5].sh;
append(label10, t21);
insert(target, t22, anchor);
insert(target, label11, anchor);
append(label11, input11);
input11.checked = /*$settings*/ ctx[5].ep;
append(label11, t23);
append(label11, a);
insert(target, t25, anchor);
insert(target, label12, anchor);
append(label12, input12);
input12.checked = /*$settings*/ ctx[5].hyd;
append(label12, t26);
insert(target, t27, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
if (!mounted) {
dispose = [
listen(input0, "change", /*input0_change_handler*/ ctx[13]),
listen(input1, "change", /*input1_change_handler*/ ctx[14]),
listen(input2, "change", /*input2_change_handler*/ ctx[15]),
listen(input3, "change", /*input3_change_handler*/ ctx[16]),
listen(input4, "change", /*input4_change_handler*/ ctx[17]),
listen(input5, "change", /*input5_change_handler*/ ctx[18]),
listen(input6, "change", /*input6_change_handler*/ ctx[20]),
listen(input7, "change", /*input7_change_handler*/ ctx[21]),
listen(input8, "change", /*input8_change_handler*/ ctx[22]),
listen(input9, "change", /*input9_change_handler*/ ctx[23]),
listen(input10, "change", /*input10_change_handler*/ ctx[24]),
listen(input11, "change", /*input11_change_handler*/ ctx[25]),
listen(input12, "change", /*input12_change_handler*/ ctx[26])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32) {
input0.checked = /*$settings*/ ctx[5].vercheck;
}
if (dirty[0] & /*$settings*/ 32) {
input1.checked = /*$settings*/ ctx[5].xpi;
}
if (dirty[0] & /*$settings*/ 32) {
input2.checked = /*$settings*/ ctx[5].xpv;
}
if (dirty[0] & /*$settings*/ 32) {
input3.checked = /*$settings*/ ctx[5].loop;
}
if (dirty[0] & /*$settings*/ 32) {
input4.checked = /*$settings*/ ctx[5].dh;
}
if (dirty[0] & /*$settings*/ 32) {
input5.checked = /*$settings*/ ctx[5].eye;
}
if (/*$settings*/ ctx[5].eye) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_7(ctx);
if_block0.c();
if_block0.m(t12.parentNode, t12);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (dirty[0] & /*$settings*/ 32) {
input6.checked = /*$settings*/ ctx[5].pre;
}
if (dirty[0] & /*$settings*/ 32) {
input7.checked = /*$settings*/ ctx[5].prev;
}
if (dirty[0] & /*$settings*/ 32) {
input8.checked = /*$settings*/ ctx[5].hotlink;
}
if (dirty[0] & /*$settings*/ 32) {
input9.checked = /*$settings*/ ctx[5].ca;
}
if (dirty[0] & /*$settings*/ 32) {
input10.checked = /*$settings*/ ctx[5].sh;
}
if (dirty[0] & /*$settings*/ 32) {
input11.checked = /*$settings*/ ctx[5].ep;
}
if (dirty[0] & /*$settings*/ 32) {
input12.checked = /*$settings*/ ctx[5].hyd;
}
if (/*$settings*/ ctx[5].hyd) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_4(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(label0);
if (detaching) detach(t1);
if (detaching) detach(label1);
if (detaching) detach(t3);
if (detaching) detach(label2);
if (detaching) detach(t5);
if (detaching) detach(label3);
if (detaching) detach(t7);
if (detaching) detach(label4);
if (detaching) detach(t9);
if (detaching) detach(label5);
if (detaching) detach(t11);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t12);
if (detaching) detach(label6);
if (detaching) detach(t14);
if (detaching) detach(label7);
if (detaching) detach(t16);
if (detaching) detach(label8);
if (detaching) detach(t18);
if (detaching) detach(label9);
if (detaching) detach(t20);
if (detaching) detach(label10);
if (detaching) detach(t22);
if (detaching) detach(label11);
if (detaching) detach(t25);
if (detaching) detach(label12);
if (detaching) detach(t27);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (177:8) {#if !$settings.te}
function create_if_block_2$1(ctx) {
let label;
let input0;
let t0;
let t1;
let t2;
let h30;
let t4;
let div0;
let t5;
let button;
let t7;
let dialog;
let t8;
let hr;
let t9;
let h31;
let t11;
let div1;
let t12;
let input1;
let current;
let mounted;
let dispose;
let if_block = /*$settings*/ ctx[5].phash && create_if_block_3$1(ctx);
let each_value_3 = /*$settings*/ ctx[5].rsources;
let each_blocks_1 = [];
for (let i = 0; i < each_value_3.length; i += 1) {
each_blocks_1[i] = create_each_block_3(get_each_context_3(ctx, each_value_3, i));
}
const out = i => transition_out(each_blocks_1[i], 1, 1, () => {
each_blocks_1[i] = null;
});
let dialog_props = {
$$slots: { default: [create_default_slot_5] },
$$scope: { ctx }
};
dialog = new Dialog({ props: dialog_props });
/*dialog_binding*/ ctx[41](dialog);
let each_value_2 = /*$settings*/ ctx[5].blacklist;
let each_blocks = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
}
const out_1 = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
label = element("label");
input0 = element("input");
t0 = text$1("\n Enable perceptual hash-based filtering");
t1 = space();
if (if_block) if_block.c();
t2 = space();
h30 = element("h3");
h30.textContent = "Booru sources";
t4 = space();
div0 = element("div");
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].c();
}
t5 = space();
button = element("button");
button.textContent = "Add a source";
t7 = space();
create_component(dialog.$$.fragment);
t8 = space();
hr = element("hr");
t9 = space();
h31 = element("h3");
h31.textContent = "Blacklisted tags";
t11 = space();
div1 = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t12 = space();
input1 = element("input");
attr(input0, "type", "checkbox");
attr(div0, "class", "tagcont svelte-1epvqgf");
attr(hr, "class", "svelte-1epvqgf");
attr(div1, "class", "tagcont svelte-1epvqgf");
attr(input1, "placeholder", "Press enter after typing your tag");
},
m(target, anchor) {
insert(target, label, anchor);
append(label, input0);
input0.checked = /*$settings*/ ctx[5].phash;
append(label, t0);
insert(target, t1, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, t2, anchor);
insert(target, h30, anchor);
insert(target, t4, anchor);
insert(target, div0, anchor);
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].m(div0, null);
}
insert(target, t5, anchor);
insert(target, button, anchor);
insert(target, t7, anchor);
mount_component(dialog, target, anchor);
insert(target, t8, anchor);
insert(target, hr, anchor);
insert(target, t9, anchor);
insert(target, h31, anchor);
insert(target, t11, anchor);
insert(target, div1, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div1, null);
}
insert(target, t12, anchor);
insert(target, input1, anchor);
current = true;
if (!mounted) {
dispose = [
listen(input0, "change", /*input0_change_handler_1*/ ctx[31]),
listen(button, "click", /*click_handler*/ ctx[36]),
listen(input1, "keydown", /*keydown_handler*/ ctx[43])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32) {
input0.checked = /*$settings*/ ctx[5].phash;
}
if (/*$settings*/ ctx[5].phash) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block_3$1(ctx);
if_block.c();
if_block.m(t2.parentNode, t2);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty[0] & /*$settings, removeBooru, toggleBooru*/ 4640) {
each_value_3 = /*$settings*/ ctx[5].rsources;
let i;
for (i = 0; i < each_value_3.length; i += 1) {
const child_ctx = get_each_context_3(ctx, each_value_3, i);
if (each_blocks_1[i]) {
each_blocks_1[i].p(child_ctx, dirty);
transition_in(each_blocks_1[i], 1);
} else {
each_blocks_1[i] = create_each_block_3(child_ctx);
each_blocks_1[i].c();
transition_in(each_blocks_1[i], 1);
each_blocks_1[i].m(div0, null);
}
}
group_outros();
for (i = each_value_3.length; i < each_blocks_1.length; i += 1) {
out(i);
}
check_outros();
}
const dialog_changes = {};
if (dirty[0] & /*newbooru*/ 1 | dirty[1] & /*$$scope*/ 134217728) {
dialog_changes.$$scope = { dirty, ctx };
}
dialog.$set(dialog_changes);
if (dirty[0] & /*$settings, removeTag*/ 288) {
each_value_2 = /*$settings*/ ctx[5].blacklist;
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx, each_value_2, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block_2(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div1, null);
}
}
group_outros();
for (i = each_value_2.length; i < each_blocks.length; i += 1) {
out_1(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_3.length; i += 1) {
transition_in(each_blocks_1[i]);
}
transition_in(dialog.$$.fragment, local);
for (let i = 0; i < each_value_2.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks_1 = each_blocks_1.filter(Boolean);
for (let i = 0; i < each_blocks_1.length; i += 1) {
transition_out(each_blocks_1[i]);
}
transition_out(dialog.$$.fragment, local);
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(label);
if (detaching) detach(t1);
if (if_block) if_block.d(detaching);
if (detaching) detach(t2);
if (detaching) detach(h30);
if (detaching) detach(t4);
if (detaching) detach(div0);
destroy_each(each_blocks_1, detaching);
if (detaching) detach(t5);
if (detaching) detach(button);
if (detaching) detach(t7);
/*dialog_binding*/ ctx[41](null);
destroy_component(dialog, detaching);
if (detaching) detach(t8);
if (detaching) detach(hr);
if (detaching) detach(t9);
if (detaching) detach(h31);
if (detaching) detach(t11);
if (detaching) detach(div1);
destroy_each(each_blocks, detaching);
if (detaching) detach(t12);
if (detaching) detach(input1);
mounted = false;
run_all(dispose);
}
};
}
// (182:10) {#if $settings.phash}
function create_if_block_3$1(ctx) {
let label;
let input;
let t0;
let a;
let mounted;
let dispose;
return {
c() {
label = element("label");
input = element("input");
t0 = text$1("\n Minimum distance required (5 recommended)\n \n ");
a = element("a");
a.textContent = "?";
attr(input, "type", "number");
attr(input, "class", "svelte-1epvqgf");
attr(a, "title", "Higher will filter more potentially different images, lower will let more identical images through");
attr(label, "class", "svelte-1epvqgf");
},
m(target, anchor) {
insert(target, label, anchor);
append(label, input);
set_input_value(input, /*$settings*/ ctx[5].mdist);
append(label, t0);
append(label, a);
if (!mounted) {
dispose = listen(input, "input", /*input_input_handler_1*/ ctx[32]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32 && to_number(input.value) !== /*$settings*/ ctx[5].mdist) {
set_input_value(input, /*$settings*/ ctx[5].mdist);
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
// (195:12) {#each $settings.rsources as source, i}
function create_each_block_3(ctx) {
let tag;
let current;
function func() {
return /*func*/ ctx[33](/*source*/ ctx[56]);
}
function remove_handler() {
return /*remove_handler*/ ctx[34](/*source*/ ctx[56]);
}
function toggle_handler() {
return /*toggle_handler*/ ctx[35](/*source*/ ctx[56]);
}
tag = new Tag({
props: {
tag: /*source*/ ctx[56].name,
toggleable: true,
toggled: func()
}
});
tag.$on("remove", remove_handler);
tag.$on("toggle", toggle_handler);
return {
c() {
create_component(tag.$$.fragment);
},
m(target, anchor) {
mount_component(tag, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const tag_changes = {};
if (dirty[0] & /*$settings*/ 32) tag_changes.tag = /*source*/ ctx[56].name;
if (dirty[0] & /*$settings*/ 32) tag_changes.toggled = func();
tag.$set(tag_changes);
},
i(local) {
if (current) return;
transition_in(tag.$$.fragment, local);
current = true;
},
o(local) {
transition_out(tag.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(tag, detaching);
}
};
}
// (216:10) <Dialog bind:this={dial}>
function create_default_slot_5(ctx) {
let div;
let label0;
let t0;
let input0;
let t1;
let label1;
let t2;
let input1;
let t3;
let label2;
let t4;
let input2;
let t5;
let label3;
let t6;
let input3;
let t7;
let button;
let mounted;
let dispose;
return {
c() {
div = element("div");
label0 = element("label");
t0 = text$1("Name\n ");
input0 = element("input");
t1 = space();
label1 = element("label");
t2 = text$1("Domain\n ");
input1 = element("input");
t3 = space();
label2 = element("label");
t4 = text$1("API Endpoint\n ");
input2 = element("input");
t5 = space();
label3 = element("label");
t6 = text$1("Post page prefix (for sources)\n ");
input3 = element("input");
t7 = space();
button = element("button");
button.textContent = "Add";
attr(input0, "type", "text");
attr(input0, "placeholder", "Gelbooru");
attr(input0, "class", "svelte-1epvqgf");
attr(label0, "class", "svelte-1epvqgf");
attr(input1, "type", "text");
attr(input1, "placeholder", "gelbooru.com");
attr(input1, "class", "svelte-1epvqgf");
attr(label1, "class", "svelte-1epvqgf");
attr(input2, "type", "text");
attr(input2, "placeholder", "/post.json?tags=md5:");
attr(input2, "class", "svelte-1epvqgf");
attr(label2, "class", "svelte-1epvqgf");
attr(input3, "type", "text");
attr(input3, "placeholder", "https://yande.re/post/show/");
attr(input3, "class", "svelte-1epvqgf");
attr(label3, "class", "svelte-1epvqgf");
attr(div, "class", "form svelte-1epvqgf");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, label0);
append(label0, t0);
append(label0, input0);
set_input_value(input0, /*newbooru*/ ctx[0].name);
append(div, t1);
append(div, label1);
append(label1, t2);
append(label1, input1);
set_input_value(input1, /*newbooru*/ ctx[0].domain);
append(div, t3);
append(div, label2);
append(label2, t4);
append(label2, input2);
set_input_value(input2, /*newbooru*/ ctx[0].endpoint);
append(div, t5);
append(div, label3);
append(label3, t6);
append(label3, input3);
set_input_value(input3, /*newbooru*/ ctx[0].view);
append(div, t7);
append(div, button);
if (!mounted) {
dispose = [
listen(input0, "input", /*input0_input_handler_1*/ ctx[37]),
listen(input1, "input", /*input1_input_handler_1*/ ctx[38]),
listen(input2, "input", /*input2_input_handler*/ ctx[39]),
listen(input3, "input", /*input3_input_handler*/ ctx[40]),
listen(button, "click", /*appendBooru*/ ctx[7])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*newbooru*/ 1 && input0.value !== /*newbooru*/ ctx[0].name) {
set_input_value(input0, /*newbooru*/ ctx[0].name);
}
if (dirty[0] & /*newbooru*/ 1 && input1.value !== /*newbooru*/ ctx[0].domain) {
set_input_value(input1, /*newbooru*/ ctx[0].domain);
}
if (dirty[0] & /*newbooru*/ 1 && input2.value !== /*newbooru*/ ctx[0].endpoint) {
set_input_value(input2, /*newbooru*/ ctx[0].endpoint);
}
if (dirty[0] & /*newbooru*/ 1 && input3.value !== /*newbooru*/ ctx[0].view) {
set_input_value(input3, /*newbooru*/ ctx[0].view);
}
},
d(detaching) {
if (detaching) detach(div);
mounted = false;
run_all(dispose);
}
};
}
// (257:12) {#each $settings.blacklist as tag, i}
function create_each_block_2(ctx) {
let tag;
let current;
function toggle_handler_1() {
return /*toggle_handler_1*/ ctx[42](/*tag*/ ctx[54]);
}
tag = new Tag({ props: { tag: /*tag*/ ctx[54] } });
tag.$on("toggle", toggle_handler_1);
return {
c() {
create_component(tag.$$.fragment);
},
m(target, anchor) {
mount_component(tag, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const tag_changes = {};
if (dirty[0] & /*$settings*/ 32) tag_changes.tag = /*tag*/ ctx[54];
tag.$set(tag_changes);
},
i(local) {
if (current) return;
transition_in(tag.$$.fragment, local);
current = true;
},
o(local) {
transition_out(tag.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(tag, detaching);
}
};
}
// (172:6) <TabPanel>
function create_default_slot_4(ctx) {
let label;
let input;
let t0;
let t1;
let if_block_anchor;
let current;
let mounted;
let dispose;
let if_block = !/*$settings*/ ctx[5].te && create_if_block_2$1(ctx);
return {
c() {
label = element("label");
input = element("input");
t0 = text$1("\n Disable third-eye.");
t1 = space();
if (if_block) if_block.c();
if_block_anchor = empty();
attr(input, "type", "checkbox");
},
m(target, anchor) {
insert(target, label, anchor);
append(label, input);
input.checked = /*$settings*/ ctx[5].te;
append(label, t0);
insert(target, t1, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
if (!mounted) {
dispose = listen(input, "change", /*input_change_handler_1*/ ctx[30]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32) {
input.checked = /*$settings*/ ctx[5].te;
}
if (!/*$settings*/ ctx[5].te) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty[0] & /*$settings*/ 32) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_2$1(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(label);
if (detaching) detach(t1);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
mounted = false;
dispose();
}
};
}
// (278:10) {#each filehosts as fh, i}
function create_each_block_1(ctx) {
let option;
let t_value = /*fh*/ ctx[51].domain + "";
let t;
let option_value_value;
return {
c() {
option = element("option");
t = text$1(t_value);
option.__value = option_value_value = /*i*/ ctx[53];
option.value = option.__value;
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t);
},
p: noop$1,
d(detaching) {
if (detaching) detach(option);
}
};
}
// (275:6) <TabPanel>
function create_default_slot_3(ctx) {
let p;
let t1;
let select;
let t2;
let label;
let t3;
let input;
let mounted;
let dispose;
let each_value_1 = filehosts;
let each_blocks = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
}
return {
c() {
p = element("p");
p.textContent = "Host to use when uploading files (Only permanent hosts)";
t1 = space();
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t2 = space();
label = element("label");
t3 = text$1("Maximum number of embedded links to display\n ");
input = element("input");
if (/*$settings*/ ctx[5].fhost === void 0) add_render_callback(() => /*select_change_handler*/ ctx[44].call(select));
attr(input, "type", "number");
attr(input, "class", "svelte-1epvqgf");
attr(label, "class", "svelte-1epvqgf");
},
m(target, anchor) {
insert(target, p, anchor);
insert(target, t1, anchor);
insert(target, select, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*$settings*/ ctx[5].fhost);
insert(target, t2, anchor);
insert(target, label, anchor);
append(label, t3);
append(label, input);
set_input_value(input, /*$settings*/ ctx[5].maxe);
if (!mounted) {
dispose = [
listen(select, "change", /*select_change_handler*/ ctx[44]),
listen(input, "input", /*input_input_handler_2*/ ctx[45])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*filehosts*/ 0) {
each_value_1 = filehosts;
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx, each_value_1, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block_1(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value_1.length;
}
if (dirty[0] & /*$settings*/ 32) {
select_option(select, /*$settings*/ ctx[5].fhost);
}
if (dirty[0] & /*$settings*/ 32 && to_number(input.value) !== /*$settings*/ ctx[5].maxe) {
set_input_value(input, /*$settings*/ ctx[5].maxe);
}
},
d(detaching) {
if (detaching) detach(p);
if (detaching) detach(t1);
if (detaching) detach(select);
destroy_each(each_blocks, detaching);
if (detaching) detach(t2);
if (detaching) detach(label);
mounted = false;
run_all(dispose);
}
};
}
// (313:8) {:else}
function create_else_block(ctx) {
let p;
return {
c() {
p = element("p");
p.textContent = "Loading...";
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop$1,
d(detaching) {
if (detaching) detach(p);
}
};
}
// (299:8) {#if !updating}
function create_if_block_1$1(ctx) {
let div;
let each_value = /*threads*/ ctx[4];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "bepis svelte-1epvqgf");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, dirty) {
if (dirty[0] & /*threads, boardname*/ 1040) {
each_value = /*threads*/ ctx[4];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$5(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$5(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
}
};
}
// (301:12) {#each threads as thread}
function create_each_block$5(ctx) {
let div;
let a;
let t0;
let t1_value = /*thread*/ ctx[48].id + "";
let t1;
let a_href_value;
let t2;
let t3_value = /*thread*/ ctx[48].cnt + "";
let t3;
let t4;
return {
c() {
div = element("div");
a = element("a");
t0 = text$1(">>");
t1 = text$1(t1_value);
t2 = text$1("\n (");
t3 = text$1(t3_value);
t4 = text$1(" embeds)\n ");
attr(a, "href", a_href_value = "https://boards.4chan.org/" + /*boardname*/ ctx[10] + "/thread/" + /*thread*/ ctx[48].id);
attr(div, "class", "mbepis");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, a);
append(a, t0);
append(a, t1);
append(div, t2);
append(div, t3);
append(div, t4);
},
p(ctx, dirty) {
if (dirty[0] & /*threads*/ 16 && t1_value !== (t1_value = /*thread*/ ctx[48].id + "")) set_data(t1, t1_value);
if (dirty[0] & /*threads*/ 16 && a_href_value !== (a_href_value = "https://boards.4chan.org/" + /*boardname*/ ctx[10] + "/thread/" + /*thread*/ ctx[48].id)) {
attr(a, "href", a_href_value);
}
if (dirty[0] & /*threads*/ 16 && t3_value !== (t3_value = /*thread*/ ctx[48].cnt + "")) set_data(t3, t3_value);
},
d(detaching) {
if (detaching) detach(div);
}
};
}
// (287:6) <TabPanel>
function create_default_slot_2(ctx) {
let label;
let input;
let t0;
let a;
let t2;
let t3;
let button;
let t4;
let t5;
let if_block_anchor;
let mounted;
let dispose;
function select_block_type(ctx, dirty) {
if (!/*updating*/ ctx[3]) return create_if_block_1$1;
return create_else_block;
}
let current_block_type = select_block_type(ctx);
let if_block = current_block_type(ctx);
return {
c() {
label = element("label");
input = element("input");
t0 = text$1("\n \n Contribute to help keep this list up to date. [");
a = element("a");
a.textContent = "?";
t2 = text$1("]");
t3 = space();
button = element("button");
t4 = text$1("Refresh");
t5 = space();
if_block.c();
if_block_anchor = empty();
attr(input, "type", "checkbox");
attr(a, "title", "This will make PEE automatically send the\n post number of posts you find with embedded content");
button.disabled = /*updating*/ ctx[3];
},
m(target, anchor) {
insert(target, label, anchor);
append(label, input);
input.checked = /*$settings*/ ctx[5].tm;
append(label, t0);
append(label, a);
append(label, t2);
insert(target, t3, anchor);
insert(target, button, anchor);
append(button, t4);
insert(target, t5, anchor);
if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
if (!mounted) {
dispose = [
listen(input, "change", /*input_change_handler_2*/ ctx[46]),
listen(button, "click", /*updateThreads*/ ctx[11])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty[0] & /*$settings*/ 32) {
input.checked = /*$settings*/ ctx[5].tm;
}
if (dirty[0] & /*updating*/ 8) {
button.disabled = /*updating*/ ctx[3];
}
if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block) {
if_block.p(ctx, dirty);
} else {
if_block.d(1);
if_block = current_block_type(ctx);
if (if_block) {
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
}
},
d(detaching) {
if (detaching) detach(label);
if (detaching) detach(t3);
if (detaching) detach(button);
if (detaching) detach(t5);
if_block.d(detaching);
if (detaching) detach(if_block_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (317:6) {#if $appState.akValid}
function create_if_block$3(ctx) {
let tabpanel;
let current;
tabpanel = new TabPanel({
props: {
$$slots: { default: [create_default_slot_1] },
$$scope: { ctx }
}
});
return {
c() {
create_component(tabpanel.$$.fragment);
},
m(target, anchor) {
mount_component(tabpanel, target, anchor);
current = true;
},
i(local) {
if (current) return;
transition_in(tabpanel.$$.fragment, local);
current = true;
},
o(local) {
transition_out(tabpanel.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(tabpanel, detaching);
}
};
}
// (318:8) <TabPanel>
function create_default_slot_1(ctx) {
let hydrussearch;
let current;
hydrussearch = new HydrusSearch({});
return {
c() {
create_component(hydrussearch.$$.fragment);
},
m(target, anchor) {
mount_component(hydrussearch, target, anchor);
current = true;
},
i(local) {
if (current) return;
transition_in(hydrussearch.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hydrussearch.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(hydrussearch, detaching);
}
};
}
// (64:4) <Tabs>
function create_default_slot(ctx) {
let tablist;
let t0;
let tabpanel0;
let t1;
let tabpanel1;
let t2;
let tabpanel2;
let t3;
let tabpanel3;
let t4;
let if_block_anchor;
let current;
tablist = new TabList({
props: {
$$slots: { default: [create_default_slot_7] },
$$scope: { ctx }
}
});
tabpanel0 = new TabPanel({
props: {
$$slots: { default: [create_default_slot_6] },
$$scope: { ctx }
}
});
tabpanel1 = new TabPanel({
props: {
$$slots: { default: [create_default_slot_4] },
$$scope: { ctx }
}
});
tabpanel2 = new TabPanel({
props: {
$$slots: { default: [create_default_slot_3] },
$$scope: { ctx }
}
});
tabpanel3 = new TabPanel({
props: {
$$slots: { default: [create_default_slot_2] },
$$scope: { ctx }
}
});
let if_block = /*$appState*/ ctx[6].akValid && create_if_block$3(ctx);
return {
c() {
create_component(tablist.$$.fragment);
t0 = space();
create_component(tabpanel0.$$.fragment);
t1 = space();
create_component(tabpanel1.$$.fragment);
t2 = space();
create_component(tabpanel2.$$.fragment);
t3 = space();
create_component(tabpanel3.$$.fragment);
t4 = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(tablist, target, anchor);
insert(target, t0, anchor);
mount_component(tabpanel0, target, anchor);
insert(target, t1, anchor);
mount_component(tabpanel1, target, anchor);
insert(target, t2, anchor);
mount_component(tabpanel2, target, anchor);
insert(target, t3, anchor);
mount_component(tabpanel3, target, anchor);
insert(target, t4, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const tablist_changes = {};
if (dirty[0] & /*$appState*/ 64 | dirty[1] & /*$$scope*/ 134217728) {
tablist_changes.$$scope = { dirty, ctx };
}
tablist.$set(tablist_changes);
const tabpanel0_changes = {};
if (dirty[0] & /*$settings, $appState*/ 96 | dirty[1] & /*$$scope*/ 134217728) {
tabpanel0_changes.$$scope = { dirty, ctx };
}
tabpanel0.$set(tabpanel0_changes);
const tabpanel1_changes = {};
if (dirty[0] & /*$settings, dial, newbooru*/ 35 | dirty[1] & /*$$scope*/ 134217728) {
tabpanel1_changes.$$scope = { dirty, ctx };
}
tabpanel1.$set(tabpanel1_changes);
const tabpanel2_changes = {};
if (dirty[0] & /*$settings*/ 32 | dirty[1] & /*$$scope*/ 134217728) {
tabpanel2_changes.$$scope = { dirty, ctx };
}
tabpanel2.$set(tabpanel2_changes);
const tabpanel3_changes = {};
if (dirty[0] & /*threads, updating, $settings*/ 56 | dirty[1] & /*$$scope*/ 134217728) {
tabpanel3_changes.$$scope = { dirty, ctx };
}
tabpanel3.$set(tabpanel3_changes);
if (/*$appState*/ ctx[6].akValid) {
if (if_block) {
if (dirty[0] & /*$appState*/ 64) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$3(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(tablist.$$.fragment, local);
transition_in(tabpanel0.$$.fragment, local);
transition_in(tabpanel1.$$.fragment, local);
transition_in(tabpanel2.$$.fragment, local);
transition_in(tabpanel3.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(tablist.$$.fragment, local);
transition_out(tabpanel0.$$.fragment, local);
transition_out(tabpanel1.$$.fragment, local);
transition_out(tabpanel2.$$.fragment, local);
transition_out(tabpanel3.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
destroy_component(tablist, detaching);
if (detaching) detach(t0);
destroy_component(tabpanel0, detaching);
if (detaching) detach(t1);
destroy_component(tabpanel1, detaching);
if (detaching) detach(t2);
destroy_component(tabpanel2, detaching);
if (detaching) detach(t3);
destroy_component(tabpanel3, detaching);
if (detaching) detach(t4);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function create_fragment$7(ctx) {
let div1;
let div0;
let h1;
let t1;
let hr;
let t2;
let tabs;
let current;
tabs = new Tabs({
props: {
$$slots: { default: [create_default_slot] },
$$scope: { ctx }
}
});
return {
c() {
div1 = element("div");
div0 = element("div");
h1 = element("h1");
h1.textContent = "PEE Settings";
t1 = space();
hr = element("hr");
t2 = space();
create_component(tabs.$$.fragment);
attr(h1, "class", "svelte-1epvqgf");
attr(hr, "class", "svelte-1epvqgf");
attr(div0, "class", "content svelte-1epvqgf");
attr(div1, "class", "backpanel svelte-1epvqgf");
toggle_class(div1, "enabled", /*visible*/ ctx[2]);
toggle_class(div1, "disabled", !/*visible*/ ctx[2]);
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
append(div0, h1);
append(div0, t1);
append(div0, hr);
append(div0, t2);
mount_component(tabs, div0, null);
current = true;
},
p(ctx, dirty) {
const tabs_changes = {};
if (dirty[0] & /*$appState, threads, updating, $settings, dial, newbooru*/ 123 | dirty[1] & /*$$scope*/ 134217728) {
tabs_changes.$$scope = { dirty, ctx };
}
tabs.$set(tabs_changes);
if (dirty[0] & /*visible*/ 4) {
toggle_class(div1, "enabled", /*visible*/ ctx[2]);
}
if (dirty[0] & /*visible*/ 4) {
toggle_class(div1, "disabled", !/*visible*/ ctx[2]);
}
},
i(local) {
if (current) return;
transition_in(tabs.$$.fragment, local);
current = true;
},
o(local) {
transition_out(tabs.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(tabs);
}
};
}
function instance$7($$self, $$props, $$invalidate) {
let $settings;
let $appState;
component_subscribe($$self, settings, $$value => $$invalidate(5, $settings = $$value));
component_subscribe($$self, appState, $$value => $$invalidate(6, $appState = $$value));
let newbooru = {};
let dial;
function appendBooru() {
set_store_value(settings, $settings.rsources = [...$settings.rsources, newbooru], $settings);
dial.toggle();
$$invalidate(0, newbooru = {});
}
let visible = false;
let penisEvent = () => {
$$invalidate(2, visible = !visible);
};
document.addEventListener("penis", penisEvent);
console.log("app loaded");
function removeTag(t) {
set_store_value(settings, $settings.blacklist = $settings.blacklist.filter(e => e != t), $settings);
}
function removeBooru(t) {
const idx = $settings.rsources.findIndex(e => e.domain == t);
const rep = prompt("You DO know what you're doing, right? (type 'y')");
if (!rep || rep != "y") return;
if (idx >= 0) $settings.rsources.splice(idx, 1);
settings.set($settings);
}
const boardname = location.pathname.match(/\/([^/]*)\//)[1];
let updating = false;
let threads = [];
async function updateThreads() {
$$invalidate(3, updating = true);
let params = "";
if ($settings.phash) {
params = "?mdist=" + $settings.mdist;
}
let res = await fetch("https://shoujo.coom.tech/listing/" + boardname + params);
$$invalidate(4, threads = await res.json());
$$invalidate(3, updating = false);
}
function toggleBooru(t) {
const elem = $settings.rsources.find(e => e.domain == t);
if (elem) elem.disabled = !elem.disabled;
settings.set($settings);
}
onDestroy(() => {
document.removeEventListener("penis", penisEvent);
});
function input0_change_handler() {
$settings.vercheck = this.checked;
settings.set($settings);
}
function input1_change_handler() {
$settings.xpi = this.checked;
settings.set($settings);
}
function input2_change_handler() {
$settings.xpv = this.checked;
settings.set($settings);
}
function input3_change_handler() {
$settings.loop = this.checked;
settings.set($settings);
}
function input4_change_handler() {
$settings.dh = this.checked;
settings.set($settings);
}
function input5_change_handler() {
$settings.eye = this.checked;
settings.set($settings);
}
function input_change_handler() {
$settings.ho = this.checked;
settings.set($settings);
}
function input6_change_handler() {
$settings.pre = this.checked;
settings.set($settings);
}
function input7_change_handler() {
$settings.prev = this.checked;
settings.set($settings);
}
function input8_change_handler() {
$settings.hotlink = this.checked;
settings.set($settings);
}
function input9_change_handler() {
$settings.ca = this.checked;
settings.set($settings);
}
function input10_change_handler() {
$settings.sh = this.checked;
settings.set($settings);
}
function input11_change_handler() {
$settings.ep = this.checked;
settings.set($settings);
}
function input12_change_handler() {
$settings.hyd = this.checked;
settings.set($settings);
}
function input_input_handler() {
$settings.ak = this.value;
settings.set($settings);
}
function input0_input_handler() {
$settings.auto_embed = to_number(this.value);
settings.set($settings);
}
function input1_input_handler() {
$settings.auto_tags = this.value;
settings.set($settings);
}
function input_change_handler_1() {
$settings.te = this.checked;
settings.set($settings);
}
function input0_change_handler_1() {
$settings.phash = this.checked;
settings.set($settings);
}
function input_input_handler_1() {
$settings.mdist = to_number(this.value);
settings.set($settings);
}
const func = source => {
const e = $settings.rsources.find(e => e.domain == source.domain);
return !(e && e.disabled);
};
const remove_handler = source => removeBooru(source.domain);
const toggle_handler = source => toggleBooru(source.domain);
const click_handler = ev => {
dial.setPos([ev.clientX, ev.clientY]);
dial.toggle();
};
function input0_input_handler_1() {
newbooru.name = this.value;
$$invalidate(0, newbooru);
}
function input1_input_handler_1() {
newbooru.domain = this.value;
$$invalidate(0, newbooru);
}
function input2_input_handler() {
newbooru.endpoint = this.value;
$$invalidate(0, newbooru);
}
function input3_input_handler() {
newbooru.view = this.value;
$$invalidate(0, newbooru);
}
function dialog_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
dial = $$value;
$$invalidate(1, dial);
});
}
const toggle_handler_1 = tag => removeTag(tag);
const keydown_handler = ev => {
if (ev.key == "Enter") {
set_store_value(settings, $settings.blacklist = [...$settings.blacklist, ev.currentTarget.value], $settings);
ev.currentTarget.value = "";
}
};
function select_change_handler() {
$settings.fhost = select_value(this);
settings.set($settings);
}
function input_input_handler_2() {
$settings.maxe = to_number(this.value);
settings.set($settings);
}
function input_change_handler_2() {
$settings.tm = this.checked;
settings.set($settings);
}
return [
newbooru,
dial,
visible,
updating,
threads,
$settings,
$appState,
appendBooru,
removeTag,
removeBooru,
boardname,
updateThreads,
toggleBooru,
input0_change_handler,
input1_change_handler,
input2_change_handler,
input3_change_handler,
input4_change_handler,
input5_change_handler,
input_change_handler,
input6_change_handler,
input7_change_handler,
input8_change_handler,
input9_change_handler,
input10_change_handler,
input11_change_handler,
input12_change_handler,
input_input_handler,
input0_input_handler,
input1_input_handler,
input_change_handler_1,
input0_change_handler_1,
input_input_handler_1,
func,
remove_handler,
toggle_handler,
click_handler,
input0_input_handler_1,
input1_input_handler_1,
input2_input_handler,
input3_input_handler,
dialog_binding,
toggle_handler_1,
keydown_handler,
select_change_handler,
input_input_handler_2,
input_change_handler_2
];
}
class App extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$7, create_fragment$7, safe_not_equal, {}, null, [-1, -1]);
}
}
/* src/Components/ScrollHighlighter.svelte generated by Svelte v3.44.3 */
function get_each_context$4(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[14] = list[i];
child_ctx[16] = i;
return child_ctx;
}
// (70:0) {#if $settings.sh}
function create_if_block$2(ctx) {
let div;
let t;
let span;
let each_value = /*$appState*/ ctx[2].foundPosts;
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
span = element("span");
attr(span, "class", "hint svelte-ausv8u");
attr(div, "class", "scroll-container svelte-ausv8u");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
append(div, t);
append(div, span);
/*span_binding*/ ctx[5](span);
},
p(ctx, dirty) {
if (dirty & /*positions, window, $appState*/ 5) {
each_value = /*$appState*/ ctx[2].foundPosts;
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$4(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$4(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, t);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
/*span_binding*/ ctx[5](null);
}
};
}
// (72:4) {#each $appState.foundPosts as post, i}
function create_each_block$4(ctx) {
let span;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[4](/*i*/ ctx[16]);
}
return {
c() {
span = element("span");
set_style(span, "top", /*positions*/ ctx[0][/*i*/ ctx[16]][0] + "px");
set_style(span, "height", /*positions*/ ctx[0][/*i*/ ctx[16]][1] + "px");
set_style(span, "background-color", /*positions*/ ctx[0][/*i*/ ctx[16]][3]);
attr(span, "class", "marker svelte-ausv8u");
},
m(target, anchor) {
insert(target, span, anchor);
if (!mounted) {
dispose = listen(span, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*positions*/ 1) {
set_style(span, "top", /*positions*/ ctx[0][/*i*/ ctx[16]][0] + "px");
}
if (dirty & /*positions*/ 1) {
set_style(span, "height", /*positions*/ ctx[0][/*i*/ ctx[16]][1] + "px");
}
if (dirty & /*positions*/ 1) {
set_style(span, "background-color", /*positions*/ ctx[0][/*i*/ ctx[16]][3]);
}
},
d(detaching) {
if (detaching) detach(span);
mounted = false;
dispose();
}
};
}
function create_fragment$6(ctx) {
let if_block_anchor;
let if_block = /*$settings*/ ctx[3].sh && create_if_block$2(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*$settings*/ ctx[3].sh) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$2(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function getOffset(el) {
var _x = 0;
var _y = 0;
while (el && el instanceof HTMLElement) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function instance$6($$self, $$props, $$invalidate) {
let $appState;
let $settings;
component_subscribe($$self, appState, $$value => $$invalidate(2, $appState = $$value));
component_subscribe($$self, settings, $$value => $$invalidate(3, $settings = $$value));
let positions = [];
const getViewport = () => (typeof visualViewport != "undefined"
? () => [visualViewport.width, visualViewport.height]
: () => [document.documentElement.clientWidth, document.documentElement.clientHeight])();
const getDistFromTop = () => (typeof visualViewport != "undefined"
? () => visualViewport.pageTop
: () => document.documentElement.scrollTop)();
let viewhint;
const updatePositions = v => {
const [sw, sh] = getViewport();
const containerScrollHeight = document.documentElement.scrollHeight;
$$invalidate(0, positions = v.foundPosts.map(v => {
const coords = getOffset(v);
const top = sh * (coords.top / containerScrollHeight);
const bot = sh * ((coords.top + v.offsetHeight) / containerScrollHeight);
const hei = bot - top;
return [top, hei, coords.top, getComputedStyle(v)['borderRightColor']];
}));
};
const updateViewhint = () => {
if (!$settings.sh) return;
const [sw, sh] = getViewport();
const fromtop = getDistFromTop();
const containerScrollHeight = document.documentElement.scrollHeight;
const top = sh * (fromtop / containerScrollHeight);
const bot = sh * ((fromtop + sh) / containerScrollHeight);
const hei = bot - top;
$$invalidate(1, viewhint.style.top = top + 'px', viewhint);
$$invalidate(1, viewhint.style.height = hei + 'px', viewhint);
};
appState.subscribe(v => updatePositions(v));
const handleResize = () => {
updatePositions($appState);
};
let locked = false;
const handleScroll = async () => {
if (locked) return;
locked = true;
updateViewhint();
await new Promise(_ => requestAnimationFrame(_));
locked = false;
};
const docRszObserver = new ResizeObserver(e => {
updatePositions($appState);
updateViewhint();
});
onMount(() => {
window.addEventListener('resize', handleResize);
document.addEventListener('scroll', handleScroll);
updateViewhint();
docRszObserver.observe(document.documentElement);
});
onDestroy(() => {
window.removeEventListener('resize', handleResize);
document.addEventListener('scroll', handleScroll);
docRszObserver.unobserve(document.documentElement);
});
const click_handler = i => window.scrollTo(0, positions[i][2]);
function span_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
viewhint = $$value;
$$invalidate(1, viewhint);
});
}
return [positions, viewhint, $appState, $settings, click_handler, span_binding];
}
class ScrollHighlighter extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$6, create_fragment$6, safe_not_equal, {});
}
}
/* src/Components/PostOptions.svelte generated by Svelte v3.44.3 */
function create_if_block$1(ctx) {
let a;
let i;
let t_value = (/*$appState*/ ctx[1].is4chanX ? "" : "❌") + "";
let t;
let a_title_value;
let mounted;
let dispose;
return {
c() {
a = element("a");
i = element("i");
t = text$1(t_value);
attr(i, "class", "fa fa-times svelte-bgqqj3");
attr(a, "title", a_title_value = "Discard ALL " + /*links*/ ctx[0].length + " files");
attr(a, "class", "svelte-bgqqj3");
},
m(target, anchor) {
insert(target, a, anchor);
append(a, i);
append(i, t);
if (!mounted) {
dispose = listen(a, "click", /*click_handler*/ ctx[7]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*$appState*/ 2 && t_value !== (t_value = (/*$appState*/ ctx[1].is4chanX ? "" : "❌") + "")) set_data(t, t_value);
if (dirty & /*links*/ 1 && a_title_value !== (a_title_value = "Discard ALL " + /*links*/ ctx[0].length + " files")) {
attr(a, "title", a_title_value);
}
},
d(detaching) {
if (detaching) detach(a);
mounted = false;
dispose();
}
};
}
function create_fragment$5(ctx) {
let div1;
let a0;
let i0;
let t0_value = (/*$appState*/ ctx[1].is4chanX ? "" : "🧲") + "";
let t0;
let t1;
let div0;
let a1;
let i1;
let t2_value = (/*$appState*/ ctx[1].is4chanX ? "" : "🖉") + "";
let t2;
let t3;
let mounted;
let dispose;
let if_block = /*links*/ ctx[0].length && create_if_block$1(ctx);
return {
c() {
div1 = element("div");
a0 = element("a");
i0 = element("i");
t0 = text$1(t0_value);
t1 = space();
div0 = element("div");
a1 = element("a");
i1 = element("i");
t2 = text$1(t2_value);
t3 = space();
if (if_block) if_block.c();
attr(i0, "class", "fa fa-magnet svelte-bgqqj3");
attr(a0, "title", "Add a file");
attr(a0, "class", "svelte-bgqqj3");
attr(i1, "class", "fa fa-pencil svelte-bgqqj3");
attr(a1, "title", "Add a message (this uses the content of the comment text box)");
attr(a1, "class", "svelte-bgqqj3");
attr(div0, "class", "additionnal svelte-bgqqj3");
attr(div1, "class", "root svelte-bgqqj3");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, a0);
append(a0, i0);
append(i0, t0);
append(div1, t1);
append(div1, div0);
append(div0, a1);
append(a1, i1);
append(i1, t2);
append(div0, t3);
if (if_block) if_block.m(div0, null);
if (!mounted) {
dispose = [
listen(a0, "click", /*embedFile*/ ctx[4]),
listen(a1, "click", /*embedText*/ ctx[3])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*$appState*/ 2 && t0_value !== (t0_value = (/*$appState*/ ctx[1].is4chanX ? "" : "🧲") + "")) set_data(t0, t0_value);
if (dirty & /*$appState*/ 2 && t2_value !== (t2_value = (/*$appState*/ ctx[1].is4chanX ? "" : "🖉") + "")) set_data(t2, t2_value);
if (/*links*/ ctx[0].length) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$1(ctx);
if_block.c();
if_block.m(div0, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (detaching) detach(div1);
if (if_block) if_block.d();
mounted = false;
run_all(dispose);
}
};
}
function instance$5($$self, $$props, $$invalidate) {
let $appState;
component_subscribe($$self, settings, $$value => $$invalidate(10, $$value));
component_subscribe($$self, appState, $$value => $$invalidate(1, $appState = $$value));
let { processors = [] } = $$props;
let { textinput } = $$props;
let { links = [] } = $$props;
const addContent = async (...newfiles) => {
$$invalidate(0, links = [...links, ...await uploadFiles(newfiles)]);
return embedContent();
};
let original;
function restore() {
document.dispatchEvent(new CustomEvent("QRSetFile", { detail: { file: original } }));
}
// This is an event to signal a change in the container file
document.addEventListener("PEEFile", async e => {
e.detail;
});
document.addEventListener("QRPostSuccessful", () => {
});
document.addEventListener("AddPEE", e => {
let link = e.detail;
$$invalidate(0, links = links.concat(link));
embedContent(e);
});
const embedText = async e => {
if (textinput.value == "") return;
if (textinput.value.length > 2000) {
fireNotification("error", "Message attachments are limited to 2000 characters");
return;
}
await addContent(new File([new Blob([textinput.value], { type: "text/plain" })], `message${links.length}.txt`));
$$invalidate(5, textinput.value = "", textinput);
};
const embedContent = async e => {
return;
};
const embedFile = async e => {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.multiple = true;
input.onchange = async ev => {
if (input.files) {
addContent(...input.files);
}
};
input.click();
};
const click_handler = () => ($$invalidate(0, links = []), restore());
$$self.$$set = $$props => {
if ('processors' in $$props) $$invalidate(6, processors = $$props.processors);
if ('textinput' in $$props) $$invalidate(5, textinput = $$props.textinput);
if ('links' in $$props) $$invalidate(0, links = $$props.links);
};
return [
links,
$appState,
restore,
embedText,
embedFile,
textinput,
processors,
click_handler
];
}
class PostOptions extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$5, create_fragment$5, safe_not_equal, { processors: 6, textinput: 5, links: 0 });
}
get processors() {
return this.$$.ctx[6];
}
set processors(processors) {
this.$$set({ processors });
flush();
}
get textinput() {
return this.$$.ctx[5];
}
set textinput(textinput) {
this.$$set({ textinput });
flush();
}
get links() {
return this.$$.ctx[0];
}
set links(links) {
this.$$set({ links });
flush();
}
}
/* src/Components/SettingsButton.svelte generated by Svelte v3.44.3 */
function create_fragment$4(ctx) {
let span;
let mounted;
let dispose;
return {
c() {
span = element("span");
span.textContent = "[PEE Settings]";
attr(span, "class", "clickable svelte-55kf6x");
toggle_class(span, "glow", /*visible*/ ctx[0]);
},
m(target, anchor) {
insert(target, span, anchor);
if (!mounted) {
dispose = listen(span, "click", /*click_handler*/ ctx[2]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*visible*/ 1) {
toggle_class(span, "glow", /*visible*/ ctx[0]);
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (detaching) detach(span);
mounted = false;
dispose();
}
};
}
function instance$4($$self, $$props, $$invalidate) {
let visible = false;
function opensettings() {
$$invalidate(0, visible = !visible);
document.dispatchEvent(new CustomEvent("penis"));
}
const click_handler = () => opensettings();
return [visible, opensettings, click_handler];
}
class SettingsButton extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$4, create_fragment$4, safe_not_equal, {});
}
}
/* src/Components/Embeddings.svelte generated by Svelte v3.44.3 */
function get_each_context$3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
child_ctx[8] = list;
child_ctx[9] = i;
return child_ctx;
}
// (13:0) {#each files as file, i}
function create_each_block$3(ctx) {
let embedding;
let i = /*i*/ ctx[9];
let current;
const assign_embedding = () => /*embedding_binding*/ ctx[5](embedding, i);
const unassign_embedding = () => /*embedding_binding*/ ctx[5](null, i);
let embedding_props = { id: /*id*/ ctx[1], file: /*file*/ ctx[7] };
embedding = new Embedding({ props: embedding_props });
assign_embedding();
embedding.$on("fileinfo", /*fileinfo_handler*/ ctx[6]);
return {
c() {
create_component(embedding.$$.fragment);
},
m(target, anchor) {
mount_component(embedding, target, anchor);
current = true;
},
p(ctx, dirty) {
if (i !== /*i*/ ctx[9]) {
unassign_embedding();
i = /*i*/ ctx[9];
assign_embedding();
}
const embedding_changes = {};
if (dirty & /*id*/ 2) embedding_changes.id = /*id*/ ctx[1];
if (dirty & /*files*/ 1) embedding_changes.file = /*file*/ ctx[7];
embedding.$set(embedding_changes);
},
i(local) {
if (current) return;
transition_in(embedding.$$.fragment, local);
current = true;
},
o(local) {
transition_out(embedding.$$.fragment, local);
current = false;
},
d(detaching) {
unassign_embedding();
destroy_component(embedding, detaching);
}
};
}
function create_fragment$3(ctx) {
let each_1_anchor;
let current;
let each_value = /*files*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*id, files, children*/ 7) {
each_value = /*files*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$3(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$3(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$3($$self, $$props, $$invalidate) {
const dispatch = createEventDispatcher();
let { files } = $$props;
let { id = '' } = $$props;
let children = {};
async function bepis(ev) {
for (let child of Object.values(children)) child.bepis(ev);
}
function embedding_binding($$value, i) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
children[i] = $$value;
$$invalidate(2, children);
});
}
function fileinfo_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('files' in $$props) $$invalidate(0, files = $$props.files);
if ('id' in $$props) $$invalidate(1, id = $$props.id);
};
return [files, id, children, dispatch, bepis, embedding_binding, fileinfo_handler];
}
class Embeddings extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$3, create_fragment$3, safe_not_equal, { dispatch: 3, files: 0, id: 1, bepis: 4 });
}
get dispatch() {
return this.$$.ctx[3];
}
get files() {
return this.$$.ctx[0];
}
set files(files) {
this.$$set({ files });
flush();
}
get id() {
return this.$$.ctx[1];
}
set id(id) {
this.$$set({ id });
flush();
}
get bepis() {
return this.$$.ctx[4];
}
}
/* src/Components/EyeButton.svelte generated by Svelte v3.44.3 */
function get_each_context$2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
return child_ctx;
}
// (36:0) {#if $settings.eye}
function create_if_block_3(ctx) {
let span;
let t_value = (/*$appState*/ ctx[5].is4chanX
? ""
: !/*visible*/ ctx[3] ? "👁" : "🤦") + "";
let t;
let mounted;
let dispose;
return {
c() {
span = element("span");
t = text$1(t_value);
attr(span, "class", "fa clickable svelte-64lw6s");
toggle_class(span, "fa-eye", !/*visible*/ ctx[3]);
toggle_class(span, "fa-eye-slash", /*visible*/ ctx[3]);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
if (!mounted) {
dispose = listen(span, "click", /*reveal*/ ctx[6]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*$appState, visible*/ 40 && t_value !== (t_value = (/*$appState*/ ctx[5].is4chanX
? ""
: !/*visible*/ ctx[3] ? "👁" : "🤦") + "")) set_data(t, t_value);
if (dirty & /*visible*/ 8) {
toggle_class(span, "fa-eye", !/*visible*/ ctx[3]);
}
if (dirty & /*visible*/ 8) {
toggle_class(span, "fa-eye-slash", /*visible*/ ctx[3]);
}
},
d(detaching) {
if (detaching) detach(span);
mounted = false;
dispose();
}
};
}
// (54:2) {#if file.source}
function create_if_block_2(ctx) {
let a;
let t;
let a_href_value;
return {
c() {
a = element("a");
t = text$1("Source");
attr(a, "href", a_href_value = /*file*/ ctx[12].source);
attr(a, "target", "_blank");
attr(a, "class", "clickable svelte-64lw6s");
},
m(target, anchor) {
insert(target, a, anchor);
append(a, t);
},
p(ctx, dirty) {
if (dirty & /*files*/ 1 && a_href_value !== (a_href_value = /*file*/ ctx[12].source)) {
attr(a, "href", a_href_value);
}
},
d(detaching) {
if (detaching) detach(a);
}
};
}
// (58:2) {#if file.page}
function create_if_block_1(ctx) {
let a;
let t_value = /*file*/ ctx[12].page.title + "";
let t;
let a_href_value;
return {
c() {
a = element("a");
t = text$1(t_value);
attr(a, "href", a_href_value = /*file*/ ctx[12].page.url);
attr(a, "target", "_blank");
attr(a, "class", "clickable svelte-64lw6s");
},
m(target, anchor) {
insert(target, a, anchor);
append(a, t);
},
p(ctx, dirty) {
if (dirty & /*files*/ 1 && t_value !== (t_value = /*file*/ ctx[12].page.title + "")) set_data(t, t_value);
if (dirty & /*files*/ 1 && a_href_value !== (a_href_value = /*file*/ ctx[12].page.url)) {
attr(a, "href", a_href_value);
}
},
d(detaching) {
if (detaching) detach(a);
}
};
}
// (64:2) {#if isNotChrome && isVideo}
function create_if_block(ctx) {
let a;
let mounted;
let dispose;
return {
c() {
a = element("a");
a.textContent = "[PEE contract]";
attr(a, "alt", "By clicking this you agree to stay hydrated");
attr(a, "class", "clickable svelte-64lw6s");
},
m(target, anchor) {
insert(target, a, anchor);
if (!mounted) {
dispose = listen(a, "click", /*click_handler_1*/ ctx[11]);
mounted = true;
}
},
p: noop$1,
d(detaching) {
if (detaching) detach(a);
mounted = false;
dispose();
}
};
}
// (46:0) {#each files as file}
function create_each_block$2(ctx) {
let span;
let t0_value = (/*$appState*/ ctx[5].is4chanX ? "" : "🖫") + "";
let t0;
let span_title_value;
let t1;
let t2;
let t3;
let if_block2_anchor;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[10](/*file*/ ctx[12]);
}
let if_block0 = /*file*/ ctx[12].source && create_if_block_2(ctx);
let if_block1 = /*file*/ ctx[12].page && create_if_block_1(ctx);
let if_block2 = /*isNotChrome*/ ctx[7] && /*isVideo*/ ctx[2] && create_if_block(ctx);
return {
c() {
span = element("span");
t0 = text$1(t0_value);
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
t3 = space();
if (if_block2) if_block2.c();
if_block2_anchor = empty();
attr(span, "title", span_title_value = /*file*/ ctx[12].filename);
attr(span, "class", "fa fa-download clickable svelte-64lw6s");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
insert(target, t1, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t2, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, t3, anchor);
if (if_block2) if_block2.m(target, anchor);
insert(target, if_block2_anchor, anchor);
if (!mounted) {
dispose = listen(span, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*$appState*/ 32 && t0_value !== (t0_value = (/*$appState*/ ctx[5].is4chanX ? "" : "🖫") + "")) set_data(t0, t0_value);
if (dirty & /*files*/ 1 && span_title_value !== (span_title_value = /*file*/ ctx[12].filename)) {
attr(span, "title", span_title_value);
}
if (/*file*/ ctx[12].source) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_2(ctx);
if_block0.c();
if_block0.m(t2.parentNode, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*file*/ ctx[12].page) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_1(ctx);
if_block1.c();
if_block1.m(t3.parentNode, t3);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
if (/*isNotChrome*/ ctx[7] && /*isVideo*/ ctx[2]) {
if (if_block2) {
if_block2.p(ctx, dirty);
} else {
if_block2 = create_if_block(ctx);
if_block2.c();
if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
}
} else if (if_block2) {
if_block2.d(1);
if_block2 = null;
}
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(t1);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t2);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(t3);
if (if_block2) if_block2.d(detaching);
if (detaching) detach(if_block2_anchor);
mounted = false;
dispose();
}
};
}
function create_fragment$2(ctx) {
let t;
let each_1_anchor;
let if_block = /*$settings*/ ctx[4].eye && create_if_block_3(ctx);
let each_value = /*files*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
}
return {
c() {
if (if_block) if_block.c();
t = space();
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, t, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*$settings*/ ctx[4].eye) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block_3(ctx);
if_block.c();
if_block.m(t.parentNode, t);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*inst, isNotChrome, isVideo, files, downloadFile, $appState*/ 423) {
each_value = /*files*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$2(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$2(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(t);
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$2($$self, $$props, $$invalidate) {
let $settings;
let $appState;
component_subscribe($$self, settings, $$value => $$invalidate(4, $settings = $$value));
component_subscribe($$self, appState, $$value => $$invalidate(5, $appState = $$value));
let { id = "" } = $$props;
let { files } = $$props;
let { inst } = $$props;
let isVideo = false;
inst.$on("fileinfo", info => {
$$invalidate(2, isVideo = isVideo || info.detail.type.mime.startsWith("video/"));
});
let visible = false;
function reveal() {
$$invalidate(3, visible = !visible);
document.dispatchEvent(new CustomEvent("reveal", { detail: { id } }));
}
const isNotChrome = !navigator.userAgent.includes("Chrome/");
async function downloadFile(file) {
const a = document.createElement("a");
document.body.appendChild(a);
a.style.display = "none";
let url;
if (typeof file.data != "string") {
const thumb = Buffer$1.isBuffer(file.data)
? file.data
: await file.data();
const type = await fileTypeFromBuffer(thumb);
url = URL.createObjectURL(new Blob([thumb], { type: type && type.mime }));
} else url = file.data;
a.href = url;
a.download = file.filename;
a.click();
window.URL.revokeObjectURL(url);
}
const click_handler = file => downloadFile(file);
const click_handler_1 = ev => {
inst.bepis(ev);
};
$$self.$$set = $$props => {
if ('id' in $$props) $$invalidate(9, id = $$props.id);
if ('files' in $$props) $$invalidate(0, files = $$props.files);
if ('inst' in $$props) $$invalidate(1, inst = $$props.inst);
};
return [
files,
inst,
isVideo,
visible,
$settings,
$appState,
reveal,
isNotChrome,
downloadFile,
id,
click_handler,
click_handler_1
];
}
class EyeButton extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$2, create_fragment$2, safe_not_equal, { id: 9, files: 0, inst: 1 });
}
get id() {
return this.$$.ctx[9];
}
set id(id) {
this.$$set({ id });
flush();
}
get files() {
return this.$$.ctx[0];
}
set files(files) {
this.$$set({ files });
flush();
}
get inst() {
return this.$$.ctx[1];
}
set inst(inst) {
this.$$set({ inst });
flush();
}
}
/* src/Components/NotificationsHandler.svelte generated by Svelte v3.44.3 */
function get_each_context$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[4] = list[i];
return child_ctx;
}
// (12:2) {#each nots as not (not.id)}
function create_each_block$1(key_1, ctx) {
let span1;
let t0_value = /*not*/ ctx[4].content + "";
let t0;
let span0;
let span1_class_value;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[2](/*not*/ ctx[4]);
}
return {
key: key_1,
first: null,
c() {
span1 = element("span");
t0 = text$1(t0_value);
span0 = element("span");
span0.textContent = "X";
attr(span0, "class", "clickable svelte-120v8nn");
attr(span1, "class", span1_class_value = "" + (null_to_empty(/*not*/ ctx[4].type) + " svelte-120v8nn"));
this.first = span1;
},
m(target, anchor) {
insert(target, span1, anchor);
append(span1, t0);
append(span1, span0);
if (!mounted) {
dispose = listen(span0, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*nots*/ 1 && t0_value !== (t0_value = /*not*/ ctx[4].content + "")) set_data(t0, t0_value);
if (dirty & /*nots*/ 1 && span1_class_value !== (span1_class_value = "" + (null_to_empty(/*not*/ ctx[4].type) + " svelte-120v8nn"))) {
attr(span1, "class", span1_class_value);
}
},
d(detaching) {
if (detaching) detach(span1);
mounted = false;
dispose();
}
};
}
function create_fragment$1(ctx) {
let div;
let each_blocks = [];
let each_1_lookup = new Map();
let each_value = /*nots*/ ctx[0];
const get_key = ctx => /*not*/ ctx[4].id;
for (let i = 0; i < each_value.length; i += 1) {
let child_ctx = get_each_context$1(ctx, each_value, i);
let key = get_key(child_ctx);
each_1_lookup.set(key, each_blocks[i] = create_each_block$1(key, child_ctx));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "root svelte-120v8nn");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*nots, removeId*/ 3) {
each_value = /*nots*/ ctx[0];
each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value, each_1_lookup, div, destroy_block, create_each_block$1, null, get_each_context$1);
}
},
i: noop$1,
o: noop$1,
d(detaching) {
if (detaching) detach(div);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].d();
}
}
};
}
function instance$1($$self, $$props, $$invalidate) {
let { nots = [] } = $$props;
const removeId = id => $$invalidate(0, nots = nots.filter(e => e.id != id));
let gid = 0;
document.addEventListener('CreateNotification', e => {
const id = gid++;
$$invalidate(0, nots = [...nots, { ...e.detail, id }]);
setTimeout(() => removeId(id), (e.detail.lifetime || 3) * 1000);
});
const click_handler = not => removeId(not.id);
$$self.$$set = $$props => {
if ('nots' in $$props) $$invalidate(0, nots = $$props.nots);
};
return [nots, removeId, click_handler];
}
class NotificationsHandler extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance$1, create_fragment$1, safe_not_equal, { nots: 0 });
}
get nots() {
return this.$$.ctx[0];
}
set nots(nots) {
this.$$set({ nots });
flush();
}
}
function _arrayLikeToArray$1(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithoutHoles$1(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
}
function _iterableToArray$1(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread$1() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray$1(arr) {
return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1();
}
function _unsupportedIterableToArray$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
}
var V4chan = {
getFileThumbnail: function(post) {
return post.querySelector("div.file");
},
getPost: function(post) {
return post.querySelector(".post");
},
postsWithFiles: function(h) {
return _toConsumableArray$1((h || document).querySelectorAll(".file")).map(function(e) {
return e.closest(".postContainer");
});
},
settingsHost: function() {
return document.getElementById("navtopright");
},
catalogControlHost: function() {
return document.getElementById("settings");
},
getImageLink: function(post) {
var ref;
return ((ref = post.querySelector('a[target="_blank"]')) === null || ref === void 0 ? void 0 : ref.getAttribute("href")) || "";
},
getFilename: function(post) {
var a = post.querySelector('a[target="_blank"]');
if (a && a.title) return a.title;
return (a === null || a === void 0 ? void 0 : a.textContent) || "";
},
getMD5: function(post) {
var ref;
return ((ref = post.querySelector("img[data-md5]")) === null || ref === void 0 ? void 0 : ref.getAttribute("data-md5")) || "";
},
getThumbnailLink: function(post) {
var ref;
return ((ref = post.querySelector("img[data-md5]")) === null || ref === void 0 ? void 0 : ref.getAttribute("src")) || "";
},
getInfoBox: function(post) {
return post.querySelector("div.fileText");
},
getPostIdPrefix: function() {
return "p";
},
getTextBox: function(post) {
return post.querySelector("blockquote");
}
};
var X4chan = {
getFileThumbnail: function(post) {
return post.querySelector("div.file");
},
getPost: function(post) {
return post.querySelector(".post");
},
postsWithFiles: function(h) {
return _toConsumableArray$1((h || document).querySelectorAll('.postContainer:not([class*="noFile"])'));
},
settingsHost: function() {
return document.getElementById("shortcuts");
},
catalogControlHost: function() {
return document.getElementById("index-options");
},
getImageLink: function(post) {
var ref;
return ((ref = post.querySelector('a[target="_blank"]')) === null || ref === void 0 ? void 0 : ref.getAttribute("href")) || "";
},
getFilename: function(post) {
var ref;
post.querySelector('a[target="_blank"]');
var origlink = post.querySelector('.file-info > a[target*="_blank"]');
return ((ref = origlink.querySelector(".fnfull") || origlink) === null || ref === void 0 ? void 0 : ref.textContent) || "";
},
getMD5: function(post) {
var ref;
return ((ref = post.querySelector("img[data-md5]")) === null || ref === void 0 ? void 0 : ref.getAttribute("data-md5")) || "";
},
getThumbnailLink: function(post) {
var ref;
return ((ref = post.querySelector("img[data-md5]")) === null || ref === void 0 ? void 0 : ref.getAttribute("src")) || "";
},
getInfoBox: function(post) {
return post.querySelector("span.file-info");
},
getPostIdPrefix: V4chan.getPostIdPrefix,
getTextBox: V4chan.getTextBox
};
var FoolFuuka = {
getFileThumbnail: function(post) {
return post.classList.contains("post_is_op") ? post.querySelector(".thread_image_link") : post.querySelector(".thread_image_box");
},
getPost: function(post) {
return post.querySelector(".post_wrapper");
},
postsWithFiles: function(h) {
return _toConsumableArray$1((h || document).querySelectorAll('article[class*="has_image"]'));
},
settingsHost: function() {
return document.querySelector(".letters");
},
catalogControlHost: function() {
return document.getElementById("index-options");
},
getImageLink: function(post) {
var ref;
return ((ref = post.querySelector("a[rel]")) === null || ref === void 0 ? void 0 : ref.getAttribute("href")) || "";
},
getFilename: function(post) {
var ref;
var opfn = (ref = post.querySelector("a.post_file_filename")) === null || ref === void 0 ? void 0 : ref.textContent;
if (opfn) return opfn;
var a = post.querySelector("a[rel]");
return (a === null || a === void 0 ? void 0 : a.title) || "";
},
getMD5: function(post) {
var ref;
return ((ref = post.querySelector("img[data-md5]")) === null || ref === void 0 ? void 0 : ref.getAttribute("data-md5")) || "";
},
getThumbnailLink: function(post) {
var e = post.querySelector("img[data-md5]");
return (e === null || e === void 0 ? void 0 : e.getAttribute("src")) || (e === null || e === void 0 ? void 0 : e.getAttribute("data-src")) || "";
},
getInfoBox: function(post) {
return post.querySelector("span.post_controls");
},
getPostIdPrefix: function() {
return "";
},
getTextBox: function(post) {
return post.querySelector(".text");
}
};
var getQueryProcessor = function(is4chanX) {
var ref, ref1;
if ([
"boards.4chan.org",
"boards.4channel.org"
].includes(location.host)) return is4chanX ? X4chan : V4chan;
if ((ref1 = (ref = document.querySelector('meta[name="generator"]')) === null || ref === void 0 ? void 0 : ref.getAttribute("content")) === null || ref1 === void 0 ? void 0 : ref1.startsWith("FoolFuuka")) return FoolFuuka;
};
/**
* Finite State Machine generation utilities
*/
/**
* Define a basic state machine state. j is the list of character transitions,
* jr is the list of regex-match transitions, jd is the default state to
* transition to t is the accepting token type, if any. If this is the terminal
* state, then it does not emit a token.
* @param {string|class} token to emit
*/
function State(token) {
this.j = {}; // IMPLEMENTATION 1
// this.j = []; // IMPLEMENTATION 2
this.jr = [];
this.jd = null;
this.t = token;
}
/**
* Take the transition from this state to the next one on the given input.
* If this state does not exist deterministically, will create it.
*
* @param {string} input character or token to transition on
* @param {string|class} [token] token or multi-token to emit when reaching
* this state
*/
State.prototype = {
/**
* @param {State} state
*/
accepts: function accepts() {
return !!this.t;
},
/**
* Short for "take transition", this is a method for building/working with
* state machines.
*
* If a state already exists for the given input, returns it.
*
* If a token is specified, that state will emit that token when reached by
* the linkify engine.
*
* If no state exists, it will be initialized with some default transitions
* that resemble existing default transitions.
*
* If a state is given for the second argument, that state will be
* transitioned to on the given input regardless of what that input
* previously did.
*
* @param {string} input character or token to transition on
* @param {Token|State} tokenOrState transition to a matching state
* @returns State taken after the given input
*/
tt: function tt(input, tokenOrState) {
if (tokenOrState && tokenOrState.j) {
// State, default a basic transition
this.j[input] = tokenOrState;
return tokenOrState;
} // See if there's a direct state transition (not regex or default)
var token = tokenOrState;
var nextState = this.j[input];
if (nextState) {
if (token) {
nextState.t = token;
} // overrwites previous token
return nextState;
} // Create a new state for this input
nextState = makeState(); // Take the transition using the usual default mechanisms
var templateState = takeT(this, input);
if (templateState) {
// Some default state transition, make a prime state based on this one
Object.assign(nextState.j, templateState.j);
nextState.jr.append(templateState.jr);
nextState.jr = templateState.jd;
nextState.t = token || templateState.t;
} else {
nextState.t = token;
}
this.j[input] = nextState;
return nextState;
}
};
/**
* Utility function to create state without using new keyword (reduced file size
* when minified)
*/
var makeState = function makeState() {
return new State();
};
/**
* Similar to previous except it is an accepting state that emits a token
* @param {Token} token
*/
var makeAcceptingState = function makeAcceptingState(token) {
return new State(token);
};
/**
* Create a transition from startState to nextState via the given character
* @param {State} startState transition from thie starting state
* @param {Token} input via this input character or other concrete token type
* @param {State} nextState to this next state
*/
var makeT = function makeT(startState, input, nextState) {
// IMPLEMENTATION 1: Add to object (fast)
if (!startState.j[input]) {
startState.j[input] = nextState;
} // IMPLEMENTATION 2: Add to array (slower)
// startState.j.push([input, nextState]);
};
/**
*
* @param {State} startState stransition from this starting state
* @param {RegExp} regex Regular expression to match on input
* @param {State} nextState transition to this next state if there's are regex match
*/
var makeRegexT = function makeRegexT(startState, regex, nextState) {
startState.jr.push([regex, nextState]);
};
/**
* Follow the transition from the given character to the next state
* @param {State} state
* @param {Token} input character or other concrete token type to transition
* @returns {?State} the next state, if any
*/
var takeT = function takeT(state, input) {
// IMPLEMENTATION 1: Object key lookup (faster)
var nextState = state.j[input];
if (nextState) {
return nextState;
} // IMPLEMENTATION 2: List lookup (slower)
// Loop through all the state transitions and see if there's a match
// for (let i = 0; i < state.j.length; i++) {
// const val = state.j[i][0];
// const nextState = state.j[i][1];
// if (input === val) { return nextState; }
// }
for (var i = 0; i < state.jr.length; i++) {
var regex = state.jr[i][0];
var _nextState = state.jr[i][1];
if (regex.test(input)) {
return _nextState;
}
} // Nowhere left to jump! Return default, if any
return state.jd;
};
/**
* Similar to makeT, but takes a list of characters that all transition to the
* same nextState startState
* @param {State} startState
* @param {Array} chars
* @param {State} nextState
*/
var makeMultiT = function makeMultiT(startState, chars, nextState) {
for (var i = 0; i < chars.length; i++) {
makeT(startState, chars[i], nextState);
}
};
/**
* Set up a list of multiple transitions at once. transitions is a list of
* tuples, where the first element is the transitions character and the second
* is the state to transition to
* @param {State} startState
* @param {Array} transitions
*/
var makeBatchT = function makeBatchT(startState, transitions) {
for (var i = 0; i < transitions.length; i++) {
var input = transitions[i][0];
var nextState = transitions[i][1];
makeT(startState, input, nextState);
}
};
/**
* For state machines that transition on characters only; given a non-empty
* target string, generates states (if required) for each consecutive substring
* of characters starting from the beginning of the string. The final state will
* have a special value, as specified in options. All other "in between"
* substrings will have a default end state.
*
* This turns the state machine into a Trie-like data structure (rather than a
* intelligently-designed DFA).
* @param {State} state
* @param {string} str
* @param {Token} endStateFactory
* @param {Token} defaultStateFactory
*/
var makeChainT = function makeChainT(state, str, endState, defaultStateFactory) {
var i = 0,
len = str.length,
nextState; // Find the next state without a jump to the next character
while (i < len && (nextState = state.j[str[i]])) {
state = nextState;
i++;
}
if (i >= len) {
return [];
} // no new tokens were added
while (i < len - 1) {
nextState = defaultStateFactory();
makeT(state, str[i], nextState);
state = nextState;
i++;
}
makeT(state, str[len - 1], endState);
};
/******************************************************************************
Text Tokens
Tokens composed of strings
******************************************************************************/
// A valid web domain token
var DOMAIN = 'DOMAIN';
var LOCALHOST = 'LOCALHOST'; // special case of domain
// Valid top-level domain (see tlds.js)
var TLD = 'TLD'; // Any sequence of digits 0-9
var NUM = 'NUM'; // A web URL protocol. Supported types include
// - `http:`
// - `https:`
// - `ftp:`
// - `ftps:`
// - user-defined custom protocols
var PROTOCOL = 'PROTOCOL'; // Start of the email URI protocol
var MAILTO = 'MAILTO'; // mailto:
// Any number of consecutive whitespace characters that are not newline
var WS = 'WS'; // New line (unix style)
var NL = 'NL'; // \n
// Opening/closing bracket classes
var OPENBRACE = 'OPENBRACE'; // {
var OPENBRACKET = 'OPENBRACKET'; // [
var OPENANGLEBRACKET = 'OPENANGLEBRACKET'; // <
var OPENPAREN = 'OPENPAREN'; // (
var CLOSEBRACE = 'CLOSEBRACE'; // }
var CLOSEBRACKET = 'CLOSEBRACKET'; // ]
var CLOSEANGLEBRACKET = 'CLOSEANGLEBRACKET'; // >
var CLOSEPAREN = 'CLOSEPAREN'; // )
// Various symbols
var AMPERSAND = 'AMPERSAND'; // &
var APOSTROPHE = 'APOSTROPHE'; // '
var ASTERISK = 'ASTERISK'; // *
var AT = 'AT'; // @
var BACKSLASH = 'BACKSLASH'; // \
var BACKTICK = 'BACKTICK'; // `
var CARET = 'CARET'; // ^
var COLON = 'COLON'; // :
var COMMA = 'COMMA'; // ,
var DOLLAR = 'DOLLAR'; // $
var DOT = 'DOT'; // .
var EQUALS = 'EQUALS'; // =
var EXCLAMATION = 'EXCLAMATION'; // !
var HYPHEN = 'HYPHEN'; // -
var PERCENT = 'PERCENT'; // %
var PIPE = 'PIPE'; // |
var PLUS = 'PLUS'; // +
var POUND = 'POUND'; // #
var QUERY = 'QUERY'; // ?
var QUOTE = 'QUOTE'; // "
var SEMI = 'SEMI'; // ;
var SLASH = 'SLASH'; // /
var TILDE = 'TILDE'; // ~
var UNDERSCORE = 'UNDERSCORE'; // _
// Default token - anything that is not one of the above
var SYM = 'SYM';
var text = /*#__PURE__*/Object.freeze({
__proto__: null,
DOMAIN: DOMAIN,
LOCALHOST: LOCALHOST,
TLD: TLD,
NUM: NUM,
PROTOCOL: PROTOCOL,
MAILTO: MAILTO,
WS: WS,
NL: NL,
OPENBRACE: OPENBRACE,
OPENBRACKET: OPENBRACKET,
OPENANGLEBRACKET: OPENANGLEBRACKET,
OPENPAREN: OPENPAREN,
CLOSEBRACE: CLOSEBRACE,
CLOSEBRACKET: CLOSEBRACKET,
CLOSEANGLEBRACKET: CLOSEANGLEBRACKET,
CLOSEPAREN: CLOSEPAREN,
AMPERSAND: AMPERSAND,
APOSTROPHE: APOSTROPHE,
ASTERISK: ASTERISK,
AT: AT,
BACKSLASH: BACKSLASH,
BACKTICK: BACKTICK,
CARET: CARET,
COLON: COLON,
COMMA: COMMA,
DOLLAR: DOLLAR,
DOT: DOT,
EQUALS: EQUALS,
EXCLAMATION: EXCLAMATION,
HYPHEN: HYPHEN,
PERCENT: PERCENT,
PIPE: PIPE,
PLUS: PLUS,
POUND: POUND,
QUERY: QUERY,
QUOTE: QUOTE,
SEMI: SEMI,
SLASH: SLASH,
TILDE: TILDE,
UNDERSCORE: UNDERSCORE,
SYM: SYM
});
// NOTE: punycode versions of IDNs are not included here because these will not
// be as commonly used without the http prefix anyway and linkify will already
// force-encode those.
// To be updated with the values in this list
// http://data.iana.org/TLD/tlds-alpha-by-domain.txt
// Version 2021022800, Last Updated Sun Feb 28 07:07:01 2021 UTC
var tlds = 'aaa \
aarp \
abarth \
abb \
abbott \
abbvie \
abc \
able \
abogado \
abudhabi \
ac \
academy \
accenture \
accountant \
accountants \
aco \
actor \
ad \
adac \
ads \
adult \
ae \
aeg \
aero \
aetna \
af \
afamilycompany \
afl \
africa \
ag \
agakhan \
agency \
ai \
aig \
airbus \
airforce \
airtel \
akdn \
al \
alfaromeo \
alibaba \
alipay \
allfinanz \
allstate \
ally \
alsace \
alstom \
am \
amazon \
americanexpress \
americanfamily \
amex \
amfam \
amica \
amsterdam \
analytics \
android \
anquan \
anz \
ao \
aol \
apartments \
app \
apple \
aq \
aquarelle \
ar \
arab \
aramco \
archi \
army \
arpa \
art \
arte \
as \
asda \
asia \
associates \
at \
athleta \
attorney \
au \
auction \
audi \
audible \
audio \
auspost \
author \
auto \
autos \
avianca \
aw \
aws \
ax \
axa \
az \
azure \
ba \
baby \
baidu \
banamex \
bananarepublic \
band \
bank \
bar \
barcelona \
barclaycard \
barclays \
barefoot \
bargains \
baseball \
basketball \
bauhaus \
bayern \
bb \
bbc \
bbt \
bbva \
bcg \
bcn \
bd \
be \
beats \
beauty \
beer \
bentley \
berlin \
best \
bestbuy \
bet \
bf \
bg \
bh \
bharti \
bi \
bible \
bid \
bike \
bing \
bingo \
bio \
biz \
bj \
black \
blackfriday \
blockbuster \
blog \
bloomberg \
blue \
bm \
bms \
bmw \
bn \
bnpparibas \
bo \
boats \
boehringer \
bofa \
bom \
bond \
boo \
book \
booking \
bosch \
bostik \
boston \
bot \
boutique \
box \
br \
bradesco \
bridgestone \
broadway \
broker \
brother \
brussels \
bs \
bt \
budapest \
bugatti \
build \
builders \
business \
buy \
buzz \
bv \
bw \
by \
bz \
bzh \
ca \
cab \
cafe \
cal \
call \
calvinklein \
cam \
camera \
camp \
cancerresearch \
canon \
capetown \
capital \
capitalone \
car \
caravan \
cards \
care \
career \
careers \
cars \
casa \
case \
cash \
casino \
cat \
catering \
catholic \
cba \
cbn \
cbre \
cbs \
cc \
cd \
center \
ceo \
cern \
cf \
cfa \
cfd \
cg \
ch \
chanel \
channel \
charity \
chase \
chat \
cheap \
chintai \
christmas \
chrome \
church \
ci \
cipriani \
circle \
cisco \
citadel \
citi \
citic \
city \
cityeats \
ck \
cl \
claims \
cleaning \
click \
clinic \
clinique \
clothing \
cloud \
club \
clubmed \
cm \
cn \
co \
coach \
codes \
coffee \
college \
cologne \
com \
comcast \
commbank \
community \
company \
compare \
computer \
comsec \
condos \
construction \
consulting \
contact \
contractors \
cooking \
cookingchannel \
cool \
coop \
corsica \
country \
coupon \
coupons \
courses \
cpa \
cr \
credit \
creditcard \
creditunion \
cricket \
crown \
crs \
cruise \
cruises \
csc \
cu \
cuisinella \
cv \
cw \
cx \
cy \
cymru \
cyou \
cz \
dabur \
dad \
dance \
data \
date \
dating \
datsun \
day \
dclk \
dds \
de \
deal \
dealer \
deals \
degree \
delivery \
dell \
deloitte \
delta \
democrat \
dental \
dentist \
desi \
design \
dev \
dhl \
diamonds \
diet \
digital \
direct \
directory \
discount \
discover \
dish \
diy \
dj \
dk \
dm \
dnp \
do \
docs \
doctor \
dog \
domains \
dot \
download \
drive \
dtv \
dubai \
duck \
dunlop \
dupont \
durban \
dvag \
dvr \
dz \
earth \
eat \
ec \
eco \
edeka \
edu \
education \
ee \
eg \
email \
emerck \
energy \
engineer \
engineering \
enterprises \
epson \
equipment \
er \
ericsson \
erni \
es \
esq \
estate \
et \
etisalat \
eu \
eurovision \
eus \
events \
exchange \
expert \
exposed \
express \
extraspace \
fage \
fail \
fairwinds \
faith \
family \
fan \
fans \
farm \
farmers \
fashion \
fast \
fedex \
feedback \
ferrari \
ferrero \
fi \
fiat \
fidelity \
fido \
film \
final \
finance \
financial \
fire \
firestone \
firmdale \
fish \
fishing \
fit \
fitness \
fj \
fk \
flickr \
flights \
flir \
florist \
flowers \
fly \
fm \
fo \
foo \
food \
foodnetwork \
football \
ford \
forex \
forsale \
forum \
foundation \
fox \
fr \
free \
fresenius \
frl \
frogans \
frontdoor \
frontier \
ftr \
fujitsu \
fujixerox \
fun \
fund \
furniture \
futbol \
fyi \
ga \
gal \
gallery \
gallo \
gallup \
game \
games \
gap \
garden \
gay \
gb \
gbiz \
gd \
gdn \
ge \
gea \
gent \
genting \
george \
gf \
gg \
ggee \
gh \
gi \
gift \
gifts \
gives \
giving \
gl \
glade \
glass \
gle \
global \
globo \
gm \
gmail \
gmbh \
gmo \
gmx \
gn \
godaddy \
gold \
goldpoint \
golf \
goo \
goodyear \
goog \
google \
gop \
got \
gov \
gp \
gq \
gr \
grainger \
graphics \
gratis \
green \
gripe \
grocery \
group \
gs \
gt \
gu \
guardian \
gucci \
guge \
guide \
guitars \
guru \
gw \
gy \
hair \
hamburg \
hangout \
haus \
hbo \
hdfc \
hdfcbank \
health \
healthcare \
help \
helsinki \
here \
hermes \
hgtv \
hiphop \
hisamitsu \
hitachi \
hiv \
hk \
hkt \
hm \
hn \
hockey \
holdings \
holiday \
homedepot \
homegoods \
homes \
homesense \
honda \
horse \
hospital \
host \
hosting \
hot \
hoteles \
hotels \
hotmail \
house \
how \
hr \
hsbc \
ht \
hu \
hughes \
hyatt \
hyundai \
ibm \
icbc \
ice \
icu \
id \
ie \
ieee \
ifm \
ikano \
il \
im \
imamat \
imdb \
immo \
immobilien \
in \
inc \
industries \
infiniti \
info \
ing \
ink \
institute \
insurance \
insure \
int \
international \
intuit \
investments \
io \
ipiranga \
iq \
ir \
irish \
is \
ismaili \
ist \
istanbul \
it \
itau \
itv \
iveco \
jaguar \
java \
jcb \
je \
jeep \
jetzt \
jewelry \
jio \
jll \
jm \
jmp \
jnj \
jo \
jobs \
joburg \
jot \
joy \
jp \
jpmorgan \
jprs \
juegos \
juniper \
kaufen \
kddi \
ke \
kerryhotels \
kerrylogistics \
kerryproperties \
kfh \
kg \
kh \
ki \
kia \
kim \
kinder \
kindle \
kitchen \
kiwi \
km \
kn \
koeln \
komatsu \
kosher \
kp \
kpmg \
kpn \
kr \
krd \
kred \
kuokgroup \
kw \
ky \
kyoto \
kz \
la \
lacaixa \
lamborghini \
lamer \
lancaster \
lancia \
land \
landrover \
lanxess \
lasalle \
lat \
latino \
latrobe \
law \
lawyer \
lb \
lc \
lds \
lease \
leclerc \
lefrak \
legal \
lego \
lexus \
lgbt \
li \
lidl \
life \
lifeinsurance \
lifestyle \
lighting \
like \
lilly \
limited \
limo \
lincoln \
linde \
link \
lipsy \
live \
living \
lixil \
lk \
llc \
llp \
loan \
loans \
locker \
locus \
loft \
lol \
london \
lotte \
lotto \
love \
lpl \
lplfinancial \
lr \
ls \
lt \
ltd \
ltda \
lu \
lundbeck \
luxe \
luxury \
lv \
ly \
ma \
macys \
madrid \
maif \
maison \
makeup \
man \
management \
mango \
map \
market \
marketing \
markets \
marriott \
marshalls \
maserati \
mattel \
mba \
mc \
mckinsey \
md \
me \
med \
media \
meet \
melbourne \
meme \
memorial \
men \
menu \
merckmsd \
mg \
mh \
miami \
microsoft \
mil \
mini \
mint \
mit \
mitsubishi \
mk \
ml \
mlb \
mls \
mm \
mma \
mn \
mo \
mobi \
mobile \
moda \
moe \
moi \
mom \
monash \
money \
monster \
mormon \
mortgage \
moscow \
moto \
motorcycles \
mov \
movie \
mp \
mq \
mr \
ms \
msd \
mt \
mtn \
mtr \
mu \
museum \
mutual \
mv \
mw \
mx \
my \
mz \
na \
nab \
nagoya \
name \
nationwide \
natura \
navy \
nba \
nc \
ne \
nec \
net \
netbank \
netflix \
network \
neustar \
new \
news \
next \
nextdirect \
nexus \
nf \
nfl \
ng \
ngo \
nhk \
ni \
nico \
nike \
nikon \
ninja \
nissan \
nissay \
nl \
no \
nokia \
northwesternmutual \
norton \
now \
nowruz \
nowtv \
np \
nr \
nra \
nrw \
ntt \
nu \
nyc \
nz \
obi \
observer \
off \
office \
okinawa \
olayan \
olayangroup \
oldnavy \
ollo \
om \
omega \
one \
ong \
onl \
online \
onyourside \
ooo \
open \
oracle \
orange \
org \
organic \
origins \
osaka \
otsuka \
ott \
ovh \
pa \
page \
panasonic \
paris \
pars \
partners \
parts \
party \
passagens \
pay \
pccw \
pe \
pet \
pf \
pfizer \
pg \
ph \
pharmacy \
phd \
philips \
phone \
photo \
photography \
photos \
physio \
pics \
pictet \
pictures \
pid \
pin \
ping \
pink \
pioneer \
pizza \
pk \
pl \
place \
play \
playstation \
plumbing \
plus \
pm \
pn \
pnc \
pohl \
poker \
politie \
porn \
post \
pr \
pramerica \
praxi \
press \
prime \
pro \
prod \
productions \
prof \
progressive \
promo \
properties \
property \
protection \
pru \
prudential \
ps \
pt \
pub \
pw \
pwc \
py \
qa \
qpon \
quebec \
quest \
qvc \
racing \
radio \
raid \
re \
read \
realestate \
realtor \
realty \
recipes \
red \
redstone \
redumbrella \
rehab \
reise \
reisen \
reit \
reliance \
ren \
rent \
rentals \
repair \
report \
republican \
rest \
restaurant \
review \
reviews \
rexroth \
rich \
richardli \
ricoh \
ril \
rio \
rip \
rmit \
ro \
rocher \
rocks \
rodeo \
rogers \
room \
rs \
rsvp \
ru \
rugby \
ruhr \
run \
rw \
rwe \
ryukyu \
sa \
saarland \
safe \
safety \
sakura \
sale \
salon \
samsclub \
samsung \
sandvik \
sandvikcoromant \
sanofi \
sap \
sarl \
sas \
save \
saxo \
sb \
sbi \
sbs \
sc \
sca \
scb \
schaeffler \
schmidt \
scholarships \
school \
schule \
schwarz \
science \
scjohnson \
scot \
sd \
se \
search \
seat \
secure \
security \
seek \
select \
sener \
services \
ses \
seven \
sew \
sex \
sexy \
sfr \
sg \
sh \
shangrila \
sharp \
shaw \
shell \
shia \
shiksha \
shoes \
shop \
shopping \
shouji \
show \
showtime \
si \
silk \
sina \
singles \
site \
sj \
sk \
ski \
skin \
sky \
skype \
sl \
sling \
sm \
smart \
smile \
sn \
sncf \
so \
soccer \
social \
softbank \
software \
sohu \
solar \
solutions \
song \
sony \
soy \
spa \
space \
sport \
spot \
spreadbetting \
sr \
srl \
ss \
st \
stada \
staples \
star \
statebank \
statefarm \
stc \
stcgroup \
stockholm \
storage \
store \
stream \
studio \
study \
style \
su \
sucks \
supplies \
supply \
support \
surf \
surgery \
suzuki \
sv \
swatch \
swiftcover \
swiss \
sx \
sy \
sydney \
systems \
sz \
tab \
taipei \
talk \
taobao \
target \
tatamotors \
tatar \
tattoo \
tax \
taxi \
tc \
tci \
td \
tdk \
team \
tech \
technology \
tel \
temasek \
tennis \
teva \
tf \
tg \
th \
thd \
theater \
theatre \
tiaa \
tickets \
tienda \
tiffany \
tips \
tires \
tirol \
tj \
tjmaxx \
tjx \
tk \
tkmaxx \
tl \
tm \
tmall \
tn \
to \
today \
tokyo \
tools \
top \
toray \
toshiba \
total \
tours \
town \
toyota \
toys \
tr \
trade \
trading \
training \
travel \
travelchannel \
travelers \
travelersinsurance \
trust \
trv \
tt \
tube \
tui \
tunes \
tushu \
tv \
tvs \
tw \
tz \
ua \
ubank \
ubs \
ug \
uk \
unicom \
university \
uno \
uol \
ups \
us \
uy \
uz \
va \
vacations \
vana \
vanguard \
vc \
ve \
vegas \
ventures \
verisign \
versicherung \
vet \
vg \
vi \
viajes \
video \
vig \
viking \
villas \
vin \
vip \
virgin \
visa \
vision \
viva \
vivo \
vlaanderen \
vn \
vodka \
volkswagen \
volvo \
vote \
voting \
voto \
voyage \
vu \
vuelos \
wales \
walmart \
walter \
wang \
wanggou \
watch \
watches \
weather \
weatherchannel \
webcam \
weber \
website \
wed \
wedding \
weibo \
weir \
wf \
whoswho \
wien \
wiki \
williamhill \
win \
windows \
wine \
winners \
wme \
wolterskluwer \
woodside \
work \
works \
world \
wow \
ws \
wtc \
wtf \
xbox \
xerox \
xfinity \
xihuan \
xin \
xxx \
xyz \
yachts \
yahoo \
yamaxun \
yandex \
ye \
yodobashi \
yoga \
yokohama \
you \
youtube \
yt \
yun \
za \
zappos \
zara \
zero \
zip \
zm \
zone \
zuerich \
zw \
vermögensberater-ctb \
vermögensberatung-pwb \
ελ \
ευ \
бг \
бел \
дети \
ею \
католик \
ком \
қаз \
мкд \
мон \
москва \
онлайн \
орг \
рус \
рф \
сайт \
срб \
укр \
გე \
հայ \
ישראל \
קום \
ابوظبي \
اتصالات \
ارامكو \
الاردن \
البحرين \
الجزائر \
السعودية \
العليان \
المغرب \
امارات \
ایران \
بارت \
بازار \
بھارت \
بيتك \
پاکستان \
ڀارت \
تونس \
سودان \
سورية \
شبكة \
عراق \
عرب \
عمان \
فلسطين \
قطر \
كاثوليك \
كوم \
مصر \
مليسيا \
موريتانيا \
موقع \
همراه \
कॉम \
नेट \
भारत \
भारतम् \
भारोत \
संगठन \
বাংলা \
ভারত \
ভাৰত \
ਭਾਰਤ \
ભારત \
ଭାରତ \
இந்தியா \
இலங்கை \
சிங்கப்பூர் \
భారత్ \
ಭಾರತ \
ഭാരതം \
ලංකා \
คอม \
ไทย \
ລາວ \
닷넷 \
닷컴 \
삼성 \
한국 \
アマゾン \
グーグル \
クラウド \
コム \
ストア \
セール \
ファッション \
ポイント \
みんな \
世界 \
中信 \
中国 \
中國 \
中文网 \
亚马逊 \
企业 \
佛山 \
信息 \
健康 \
八卦 \
公司 \
公益 \
台湾 \
台灣 \
商城 \
商店 \
商标 \
嘉里 \
嘉里大酒店 \
在线 \
大众汽车 \
大拿 \
天主教 \
娱乐 \
家電 \
广东 \
微博 \
慈善 \
我爱你 \
手机 \
招聘 \
政务 \
政府 \
新加坡 \
新闻 \
时尚 \
書籍 \
机构 \
淡马锡 \
游戏 \
澳門 \
点看 \
移动 \
组织机构 \
网址 \
网店 \
网站 \
网络 \
联通 \
诺基亚 \
谷歌 \
购物 \
通販 \
集团 \
電訊盈科 \
飞利浦 \
食品 \
餐厅 \
香格里拉 \
香港'.split(' ');
/**
The scanner provides an interface that takes a string of text as input, and
outputs an array of tokens instances that can be used for easy URL parsing.
@module linkify
@submodule scanner
@main scanner
*/
var LETTER = /(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/; // Any Unicode character with letter data type
var EMOJI = /(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEDD-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDDFF\uDE70-\uDE74\uDE78-\uDE7C\uDE80-\uDE86\uDE90-\uDEAC\uDEB0-\uDEBA\uDEC0-\uDEC5\uDED0-\uDED9\uDEE0-\uDEE7\uDEF0-\uDEF6])/; // Any Unicode emoji character
var EMOJI_VARIATION = /\uFE0F/; // Variation selector, follows heart and others
var DIGIT = /\d/;
var SPACE = /\s/;
/**
* Initialize the scanner character-based state machine for the given start state
* @return {State} scanner starting state
*/
function init$2() {
var customProtocols = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// Frequently used states
var S_START = makeState();
var S_NUM = makeAcceptingState(NUM);
var S_DOMAIN = makeAcceptingState(DOMAIN);
var S_DOMAIN_HYPHEN = makeState(); // domain followed by 1 or more hyphen characters
var S_WS = makeAcceptingState(WS);
var DOMAIN_REGEX_TRANSITIONS = [[DIGIT, S_DOMAIN], [LETTER, S_DOMAIN], [EMOJI, S_DOMAIN], [EMOJI_VARIATION, S_DOMAIN]]; // Create a state which emits a domain token
var makeDomainState = function makeDomainState() {
var state = makeAcceptingState(DOMAIN);
state.j = {
'-': S_DOMAIN_HYPHEN
};
state.jr = [].concat(DOMAIN_REGEX_TRANSITIONS);
return state;
}; // Create a state which does not emit a domain state but the usual alphanumeric
// transitions are domains
var makeNearDomainState = function makeNearDomainState(token) {
var state = makeDomainState();
state.t = token;
return state;
}; // States for special URL symbols that accept immediately after start
makeBatchT(S_START, [["'", makeAcceptingState(APOSTROPHE)], ['{', makeAcceptingState(OPENBRACE)], ['[', makeAcceptingState(OPENBRACKET)], ['<', makeAcceptingState(OPENANGLEBRACKET)], ['(', makeAcceptingState(OPENPAREN)], ['}', makeAcceptingState(CLOSEBRACE)], [']', makeAcceptingState(CLOSEBRACKET)], ['>', makeAcceptingState(CLOSEANGLEBRACKET)], [')', makeAcceptingState(CLOSEPAREN)], ['&', makeAcceptingState(AMPERSAND)], ['*', makeAcceptingState(ASTERISK)], ['@', makeAcceptingState(AT)], ['`', makeAcceptingState(BACKTICK)], ['^', makeAcceptingState(CARET)], [':', makeAcceptingState(COLON)], [',', makeAcceptingState(COMMA)], ['$', makeAcceptingState(DOLLAR)], ['.', makeAcceptingState(DOT)], ['=', makeAcceptingState(EQUALS)], ['!', makeAcceptingState(EXCLAMATION)], ['-', makeAcceptingState(HYPHEN)], ['%', makeAcceptingState(PERCENT)], ['|', makeAcceptingState(PIPE)], ['+', makeAcceptingState(PLUS)], ['#', makeAcceptingState(POUND)], ['?', makeAcceptingState(QUERY)], ['"', makeAcceptingState(QUOTE)], ['/', makeAcceptingState(SLASH)], [';', makeAcceptingState(SEMI)], ['~', makeAcceptingState(TILDE)], ['_', makeAcceptingState(UNDERSCORE)], ['\\', makeAcceptingState(BACKSLASH)]]); // Whitespace jumps
// Tokens of only non-newline whitespace are arbitrarily long
makeT(S_START, '\n', makeAcceptingState(NL));
makeRegexT(S_START, SPACE, S_WS); // If any whitespace except newline, more whitespace!
makeT(S_WS, '\n', makeState()); // non-accepting state
makeRegexT(S_WS, SPACE, S_WS); // Generates states for top-level domains
// Note that this is most accurate when tlds are in alphabetical order
for (var i = 0; i < tlds.length; i++) {
makeChainT(S_START, tlds[i], makeNearDomainState(TLD), makeDomainState);
} // Collect the states generated by different protocls
var S_PROTOCOL_FILE = makeDomainState();
var S_PROTOCOL_FTP = makeDomainState();
var S_PROTOCOL_HTTP = makeDomainState();
var S_MAILTO = makeDomainState();
makeChainT(S_START, 'file', S_PROTOCOL_FILE, makeDomainState);
makeChainT(S_START, 'ftp', S_PROTOCOL_FTP, makeDomainState);
makeChainT(S_START, 'http', S_PROTOCOL_HTTP, makeDomainState);
makeChainT(S_START, 'mailto', S_MAILTO, makeDomainState); // Protocol states
var S_PROTOCOL_SECURE = makeDomainState();
var S_FULL_PROTOCOL = makeAcceptingState(PROTOCOL); // Full protocol ends with COLON
var S_FULL_MAILTO = makeAcceptingState(MAILTO); // Mailto ends with COLON
// Secure protocols (end with 's')
makeT(S_PROTOCOL_FTP, 's', S_PROTOCOL_SECURE);
makeT(S_PROTOCOL_FTP, ':', S_FULL_PROTOCOL);
makeT(S_PROTOCOL_HTTP, 's', S_PROTOCOL_SECURE);
makeT(S_PROTOCOL_HTTP, ':', S_FULL_PROTOCOL); // Become protocol tokens after a COLON
makeT(S_PROTOCOL_FILE, ':', S_FULL_PROTOCOL);
makeT(S_PROTOCOL_SECURE, ':', S_FULL_PROTOCOL);
makeT(S_MAILTO, ':', S_FULL_MAILTO); // Register custom protocols
var S_CUSTOM_PROTOCOL = makeDomainState();
for (var _i = 0; _i < customProtocols.length; _i++) {
makeChainT(S_START, customProtocols[_i], S_CUSTOM_PROTOCOL, makeDomainState);
}
makeT(S_CUSTOM_PROTOCOL, ':', S_FULL_PROTOCOL); // Localhost
makeChainT(S_START, 'localhost', makeNearDomainState(LOCALHOST), makeDomainState); // Everything else
// DOMAINs make more DOMAINs
// Number and character transitions
makeRegexT(S_START, DIGIT, S_NUM);
makeRegexT(S_START, LETTER, S_DOMAIN);
makeRegexT(S_START, EMOJI, S_DOMAIN);
makeRegexT(S_START, EMOJI_VARIATION, S_DOMAIN);
makeRegexT(S_NUM, DIGIT, S_NUM);
makeRegexT(S_NUM, LETTER, S_DOMAIN); // number becomes DOMAIN
makeRegexT(S_NUM, EMOJI, S_DOMAIN); // number becomes DOMAIN
makeRegexT(S_NUM, EMOJI_VARIATION, S_DOMAIN); // number becomes DOMAIN
makeT(S_NUM, '-', S_DOMAIN_HYPHEN); // Default domain transitions
makeT(S_DOMAIN, '-', S_DOMAIN_HYPHEN);
makeT(S_DOMAIN_HYPHEN, '-', S_DOMAIN_HYPHEN);
makeRegexT(S_DOMAIN, DIGIT, S_DOMAIN);
makeRegexT(S_DOMAIN, LETTER, S_DOMAIN);
makeRegexT(S_DOMAIN, EMOJI, S_DOMAIN);
makeRegexT(S_DOMAIN, EMOJI_VARIATION, S_DOMAIN);
makeRegexT(S_DOMAIN_HYPHEN, DIGIT, S_DOMAIN);
makeRegexT(S_DOMAIN_HYPHEN, LETTER, S_DOMAIN);
makeRegexT(S_DOMAIN_HYPHEN, EMOJI, S_DOMAIN);
makeRegexT(S_DOMAIN_HYPHEN, EMOJI_VARIATION, S_DOMAIN); // Set default transition for start state (some symbol)
S_START.jd = makeAcceptingState(SYM);
return S_START;
}
/**
Given a string, returns an array of TOKEN instances representing the
composition of that string.
@method run
@param {State} start scanner starting state
@param {string} str input string to scan
@return {{t: string, v: string, s: number, l: number}[]} list of tokens, each with a type and value
*/
function run$1(start, str) {
// State machine is not case sensitive, so input is tokenized in lowercased
// form (still returns the regular case though) Uses selective `toLowerCase`
// is used because lowercasing the entire string causes the length and
// character position to vary in some non-English strings with V8-based
// runtimes.
var iterable = stringToArray(str.replace(/[A-Z]/g, function (c) {
return c.toLowerCase();
}));
var charCount = iterable.length; // <= len if there are emojis, etc
var tokens = []; // return value
// cursor through the string itself, accounting for characters that have
// width with length 2 such as emojis
var cursor = 0; // Cursor through the array-representation of the string
var charCursor = 0; // Tokenize the string
while (charCursor < charCount) {
var state = start;
var nextState = null;
var tokenLength = 0;
var latestAccepting = null;
var sinceAccepts = -1;
var charsSinceAccepts = -1;
while (charCursor < charCount && (nextState = takeT(state, iterable[charCursor]))) {
state = nextState; // Keep track of the latest accepting state
if (state.accepts()) {
sinceAccepts = 0;
charsSinceAccepts = 0;
latestAccepting = state;
} else if (sinceAccepts >= 0) {
sinceAccepts += iterable[charCursor].length;
charsSinceAccepts++;
}
tokenLength += iterable[charCursor].length;
cursor += iterable[charCursor].length;
charCursor++;
} // Roll back to the latest accepting state
cursor -= sinceAccepts;
charCursor -= charsSinceAccepts;
tokenLength -= sinceAccepts; // No more jumps, just make a new token from the last accepting one
// TODO: If possible, don't output v, instead output range where values ocur
tokens.push({
t: latestAccepting.t,
// token type/name
v: str.substr(cursor - tokenLength, tokenLength),
// string value
s: cursor - tokenLength,
// start index
e: cursor // end index (excluding)
});
}
return tokens;
}
/**
* Convert a String to an Array of characters, taking into account that some
* characters like emojis take up two string indexes.
*
* Adapted from core-js (MIT license)
* https://github.com/zloirock/core-js/blob/2d69cf5f99ab3ea3463c395df81e5a15b68f49d9/packages/core-js/internals/string-multibyte.js
*
* @function stringToArray
* @param {string} str
* @returns {string[]}
*/
function stringToArray(str) {
var result = [];
var len = str.length;
var index = 0;
while (index < len) {
var first = str.charCodeAt(index);
var second = void 0;
var char = first < 0xd800 || first > 0xdbff || index + 1 === len || (second = str.charCodeAt(index + 1)) < 0xdc00 || second > 0xdfff ? str[index] // single character
: str.slice(index, index + 2); // two-index characters
result.push(char);
index += char.length;
}
return result;
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
/**
* @property {string} defaultProtocol
* @property {{[string]: (event) => void}]} [events]
*/
var defaults = {
defaultProtocol: 'http',
events: null,
format: noop,
formatHref: noop,
nl2br: false,
tagName: 'a',
target: null,
rel: null,
validate: true,
truncate: 0,
className: null,
attributes: null,
ignoreTags: []
};
/**
* @class Options
* @param {Object} [opts] Set option properties besides the defaults
*/
function Options(opts) {
opts = opts || {};
this.defaultProtocol = 'defaultProtocol' in opts ? opts.defaultProtocol : defaults.defaultProtocol;
this.events = 'events' in opts ? opts.events : defaults.events;
this.format = 'format' in opts ? opts.format : defaults.format;
this.formatHref = 'formatHref' in opts ? opts.formatHref : defaults.formatHref;
this.nl2br = 'nl2br' in opts ? opts.nl2br : defaults.nl2br;
this.tagName = 'tagName' in opts ? opts.tagName : defaults.tagName;
this.target = 'target' in opts ? opts.target : defaults.target;
this.rel = 'rel' in opts ? opts.rel : defaults.rel;
this.validate = 'validate' in opts ? opts.validate : defaults.validate;
this.truncate = 'truncate' in opts ? opts.truncate : defaults.truncate;
this.className = 'className' in opts ? opts.className : defaults.className;
this.attributes = opts.attributes || defaults.attributes;
this.ignoreTags = []; // Make all tags names upper case
var ignoredTags = 'ignoreTags' in opts ? opts.ignoreTags : defaults.ignoreTags;
for (var i = 0; i < ignoredTags.length; i++) {
this.ignoreTags.push(ignoredTags[i].toUpperCase());
}
}
Options.prototype = {
/**
* Given the token, return all options for how it should be displayed
*/
resolve: function resolve(token) {
var href = token.toHref(this.defaultProtocol);
return {
formatted: this.get('format', token.toString(), token),
formattedHref: this.get('formatHref', href, token),
tagName: this.get('tagName', href, token),
className: this.get('className', href, token),
target: this.get('target', href, token),
rel: this.get('rel', href, token),
events: this.getObject('events', href, token),
attributes: this.getObject('attributes', href, token),
truncate: this.get('truncate', href, token)
};
},
/**
* Returns true or false based on whether a token should be displayed as a
* link based on the user options. By default,
*/
check: function check(token) {
return this.get('validate', token.toString(), token);
},
// Private methods
/**
* Resolve an option's value based on the value of the option and the given
* params.
* @param {string} key Name of option to use
* @param operator will be passed to the target option if it's method
* @param {MultiToken} token The token from linkify.tokenize
*/
get: function get(key, operator, token) {
var option = this[key];
if (!option) {
return option;
}
var optionValue;
switch (_typeof(option)) {
case 'function':
return option(operator, token.t);
case 'object':
optionValue = token.t in option ? option[token.t] : defaults[key];
return typeof optionValue === 'function' ? optionValue(operator, token.t) : optionValue;
}
return option;
},
getObject: function getObject(key, operator, token) {
var option = this[key];
return typeof option === 'function' ? option(operator, token.t) : option;
}
};
function noop(val) {
return val;
}
/******************************************************************************
Multi-Tokens
Tokens composed of arrays of TextTokens
******************************************************************************/
function inherits(parent, child) {
var props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var extended = Object.create(parent.prototype);
for (var p in props) {
extended[p] = props[p];
}
extended.constructor = child;
child.prototype = extended;
return child;
}
/**
Abstract class used for manufacturing tokens of text tokens. That is rather
than the value for a token being a small string of text, it's value an array
of text tokens.
Used for grouping together URLs, emails, hashtags, and other potential
creations.
@class MultiToken
@param {string} value
@param {{t: string, v: string, s: number, e: number}[]} tokens
@abstract
*/
function MultiToken() {}
MultiToken.prototype = {
/**
String representing the type for this token
@property t
@default 'token'
*/
t: 'token',
/**
Is this multitoken a link?
@property isLink
@default false
*/
isLink: false,
/**
Return the string this token represents.
@method toString
@return {string}
*/
toString: function toString() {
return this.v;
},
/**
What should the value for this token be in the `href` HTML attribute?
Returns the `.toString` value by default.
@method toHref
@return {string}
*/
toHref: function toHref() {
return this.toString();
},
/**
* The start index of this token in the original input string
* @returns {number}
*/
startIndex: function startIndex() {
return this.tk[0].s;
},
/**
* The end index of this token in the original input string (up to this
* index but not including it)
* @returns {number}
*/
endIndex: function endIndex() {
return this.tk[this.tk.length - 1].e;
},
/**
Returns a hash of relevant values for this token, which includes keys
* type - Kind of token ('url', 'email', etc.)
* value - Original text
* href - The value that should be added to the anchor tag's href
attribute
@method toObject
@param {string} [protocol] `'http'` by default
*/
toObject: function toObject() {
var protocol = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaults.defaultProtocol;
return {
type: this.t,
value: this.v,
isLink: this.isLink,
href: this.toHref(protocol),
start: this.startIndex(),
end: this.endIndex()
};
}
}; // Base token
/**
* Create a new token that can be emitted by the parser state machine
* @param {string} type readable type of the token
* @param {object} props properties to assign or override, including isLink = true or false
* @returns {(value: string, tokens: {t: string, v: string, s: number, e: number}) => MultiToken} new token class
*/
function createTokenClass(type, props) {
function Token(value, tokens) {
this.t = type;
this.v = value;
this.tk = tokens;
}
inherits(MultiToken, Token, props);
return Token;
}
/**
Represents an arbitrarily mailto email address with the prefix included
@class MailtoEmail
@extends MultiToken
*/
var MailtoEmail = createTokenClass('email', {
isLink: true
});
/**
Represents a list of tokens making up a valid email address
@class Email
@extends MultiToken
*/
var Email = createTokenClass('email', {
isLink: true,
toHref: function toHref() {
return 'mailto:' + this.toString();
}
});
/**
Represents some plain text
@class Text
@extends MultiToken
*/
var Text = createTokenClass('text');
/**
Multi-linebreak token - represents a line break
@class Nl
@extends MultiToken
*/
var Nl = createTokenClass('nl');
/**
Represents a list of text tokens making up a valid URL
@class Url
@extends MultiToken
*/
var Url = createTokenClass('url', {
isLink: true,
/**
Lowercases relevant parts of the domain and adds the protocol if
required. Note that this will not escape unsafe HTML characters in the
URL.
@method href
@param {string} protocol
@return {string}
*/
toHref: function toHref() {
var protocol = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaults.defaultProtocol;
var tokens = this.tk;
var hasProtocol = false;
var hasSlashSlash = false;
var result = [];
var i = 0; // Make the first part of the domain lowercase
// Lowercase protocol
while (tokens[i].t === PROTOCOL) {
hasProtocol = true;
result.push(tokens[i].v);
i++;
} // Skip slash-slash
while (tokens[i].t === SLASH) {
hasSlashSlash = true;
result.push(tokens[i].v);
i++;
} // Continue pushing characters
for (; i < tokens.length; i++) {
result.push(tokens[i].v);
}
result = result.join('');
if (!(hasProtocol || hasSlashSlash)) {
result = "".concat(protocol, "://").concat(result);
}
return result;
},
hasProtocol: function hasProtocol() {
return this.tk[0].t === PROTOCOL;
}
});
var multi = /*#__PURE__*/Object.freeze({
__proto__: null,
MultiToken: MultiToken,
Base: MultiToken,
createTokenClass: createTokenClass,
MailtoEmail: MailtoEmail,
Email: Email,
Text: Text,
Nl: Nl,
Url: Url
});
/**
Not exactly parser, more like the second-stage scanner (although we can
theoretically hotswap the code here with a real parser in the future... but
for a little URL-finding utility abstract syntax trees may be a little
overkill).
URL format: http://en.wikipedia.org/wiki/URI_scheme
Email format: http://en.wikipedia.org/wiki/Email_address (links to RFC in
reference)
@module linkify
@submodule parser
@main run
*/
/**
* Generate the parser multi token-based state machine
* @returns {State} the starting state
*/
function init$1() {
// The universal starting state.
var S_START = makeState(); // Intermediate states for URLs. Note that domains that begin with a protocol
// are treated slighly differently from those that don't.
var S_PROTOCOL = makeState(); // e.g., 'http:'
var S_MAILTO = makeState(); // 'mailto:'
var S_PROTOCOL_SLASH = makeState(); // e.g., 'http:/''
var S_PROTOCOL_SLASH_SLASH = makeState(); // e.g.,'http://'
var S_DOMAIN = makeState(); // parsed string ends with a potential domain name (A)
var S_DOMAIN_DOT = makeState(); // (A) domain followed by DOT
var S_TLD = makeAcceptingState(Url); // (A) Simplest possible URL with no query string
var S_TLD_COLON = makeState(); // (A) URL followed by colon (potential port number here)
var S_TLD_PORT = makeAcceptingState(Url); // TLD followed by a port number
var S_URL = makeAcceptingState(Url); // Long URL with optional port and maybe query string
var S_URL_NON_ACCEPTING = makeState(); // URL followed by some symbols (will not be part of the final URL)
var S_URL_OPENBRACE = makeState(); // URL followed by {
var S_URL_OPENBRACKET = makeState(); // URL followed by [
var S_URL_OPENANGLEBRACKET = makeState(); // URL followed by <
var S_URL_OPENPAREN = makeState(); // URL followed by (
var S_URL_OPENBRACE_Q = makeAcceptingState(Url); // URL followed by { and some symbols that the URL can end it
var S_URL_OPENBRACKET_Q = makeAcceptingState(Url); // URL followed by [ and some symbols that the URL can end it
var S_URL_OPENANGLEBRACKET_Q = makeAcceptingState(Url); // URL followed by < and some symbols that the URL can end it
var S_URL_OPENPAREN_Q = makeAcceptingState(Url); // URL followed by ( and some symbols that the URL can end it
var S_URL_OPENBRACE_SYMS = makeState(); // S_URL_OPENBRACE_Q followed by some symbols it cannot end it
var S_URL_OPENBRACKET_SYMS = makeState(); // S_URL_OPENBRACKET_Q followed by some symbols it cannot end it
var S_URL_OPENANGLEBRACKET_SYMS = makeState(); // S_URL_OPENANGLEBRACKET_Q followed by some symbols it cannot end it
var S_URL_OPENPAREN_SYMS = makeState(); // S_URL_OPENPAREN_Q followed by some symbols it cannot end it
var S_EMAIL_DOMAIN = makeState(); // parsed string starts with local email info + @ with a potential domain name (C)
var S_EMAIL_DOMAIN_DOT = makeState(); // (C) domain followed by DOT
var S_EMAIL = makeAcceptingState(Email); // (C) Possible email address (could have more tlds)
var S_EMAIL_COLON = makeState(); // (C) URL followed by colon (potential port number here)
var S_EMAIL_PORT = makeAcceptingState(Email); // (C) Email address with a port
var S_MAILTO_EMAIL = makeAcceptingState(MailtoEmail); // Email that begins with the mailto prefix (D)
var S_MAILTO_EMAIL_NON_ACCEPTING = makeState(); // (D) Followed by some non-query string chars
var S_LOCALPART = makeState(); // Local part of the email address
var S_LOCALPART_AT = makeState(); // Local part of the email address plus @
var S_LOCALPART_DOT = makeState(); // Local part of the email address plus '.' (localpart cannot end in .)
var S_NL = makeAcceptingState(Nl); // single new line
// Make path from start to protocol (with '//')
makeT(S_START, NL, S_NL);
makeT(S_START, PROTOCOL, S_PROTOCOL);
makeT(S_START, MAILTO, S_MAILTO);
makeT(S_PROTOCOL, SLASH, S_PROTOCOL_SLASH);
makeT(S_PROTOCOL_SLASH, SLASH, S_PROTOCOL_SLASH_SLASH); // The very first potential domain name
makeT(S_START, TLD, S_DOMAIN);
makeT(S_START, DOMAIN, S_DOMAIN);
makeT(S_START, LOCALHOST, S_TLD);
makeT(S_START, NUM, S_DOMAIN); // Force URL for protocol followed by anything sane
makeT(S_PROTOCOL_SLASH_SLASH, TLD, S_URL);
makeT(S_PROTOCOL_SLASH_SLASH, DOMAIN, S_URL);
makeT(S_PROTOCOL_SLASH_SLASH, NUM, S_URL);
makeT(S_PROTOCOL_SLASH_SLASH, LOCALHOST, S_URL); // Account for dots and hyphens
// hyphens are usually parts of domain names
makeT(S_DOMAIN, DOT, S_DOMAIN_DOT);
makeT(S_EMAIL_DOMAIN, DOT, S_EMAIL_DOMAIN_DOT); // Hyphen can jump back to a domain name
// After the first domain and a dot, we can find either a URL or another domain
makeT(S_DOMAIN_DOT, TLD, S_TLD);
makeT(S_DOMAIN_DOT, DOMAIN, S_DOMAIN);
makeT(S_DOMAIN_DOT, NUM, S_DOMAIN);
makeT(S_DOMAIN_DOT, LOCALHOST, S_DOMAIN);
makeT(S_EMAIL_DOMAIN_DOT, TLD, S_EMAIL);
makeT(S_EMAIL_DOMAIN_DOT, DOMAIN, S_EMAIL_DOMAIN);
makeT(S_EMAIL_DOMAIN_DOT, NUM, S_EMAIL_DOMAIN);
makeT(S_EMAIL_DOMAIN_DOT, LOCALHOST, S_EMAIL_DOMAIN); // S_TLD accepts! But the URL could be longer, try to find a match greedily
// The `run` function should be able to "rollback" to the accepting state
makeT(S_TLD, DOT, S_DOMAIN_DOT);
makeT(S_EMAIL, DOT, S_EMAIL_DOMAIN_DOT); // Become real URLs after `SLASH` or `COLON NUM SLASH`
// Here PSS and non-PSS converge
makeT(S_TLD, COLON, S_TLD_COLON);
makeT(S_TLD, SLASH, S_URL);
makeT(S_TLD_COLON, NUM, S_TLD_PORT);
makeT(S_TLD_PORT, SLASH, S_URL);
makeT(S_EMAIL, COLON, S_EMAIL_COLON);
makeT(S_EMAIL_COLON, NUM, S_EMAIL_PORT); // Types of characters the URL can definitely end in
var qsAccepting = [AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, DOMAIN, EQUALS, HYPHEN, LOCALHOST, NUM, PERCENT, PIPE, PLUS, POUND, PROTOCOL, SLASH, SYM, TILDE, TLD, UNDERSCORE]; // Types of tokens that can follow a URL and be part of the query string
// but cannot be the very last characters
// Characters that cannot appear in the URL at all should be excluded
var qsNonAccepting = [APOSTROPHE, CLOSEANGLEBRACKET, CLOSEBRACE, CLOSEBRACKET, CLOSEPAREN, COLON, COMMA, DOT, EXCLAMATION, OPENANGLEBRACKET, OPENBRACE, OPENBRACKET, OPENPAREN, QUERY, QUOTE, SEMI]; // These states are responsible primarily for determining whether or not to
// include the final round bracket.
// URL, followed by an opening bracket
makeT(S_URL, OPENBRACE, S_URL_OPENBRACE);
makeT(S_URL, OPENBRACKET, S_URL_OPENBRACKET);
makeT(S_URL, OPENANGLEBRACKET, S_URL_OPENANGLEBRACKET);
makeT(S_URL, OPENPAREN, S_URL_OPENPAREN); // URL with extra symbols at the end, followed by an opening bracket
makeT(S_URL_NON_ACCEPTING, OPENBRACE, S_URL_OPENBRACE);
makeT(S_URL_NON_ACCEPTING, OPENBRACKET, S_URL_OPENBRACKET);
makeT(S_URL_NON_ACCEPTING, OPENANGLEBRACKET, S_URL_OPENANGLEBRACKET);
makeT(S_URL_NON_ACCEPTING, OPENPAREN, S_URL_OPENPAREN); // Closing bracket component. This character WILL be included in the URL
makeT(S_URL_OPENBRACE, CLOSEBRACE, S_URL);
makeT(S_URL_OPENBRACKET, CLOSEBRACKET, S_URL);
makeT(S_URL_OPENANGLEBRACKET, CLOSEANGLEBRACKET, S_URL);
makeT(S_URL_OPENPAREN, CLOSEPAREN, S_URL);
makeT(S_URL_OPENBRACE_Q, CLOSEBRACE, S_URL);
makeT(S_URL_OPENBRACKET_Q, CLOSEBRACKET, S_URL);
makeT(S_URL_OPENANGLEBRACKET_Q, CLOSEANGLEBRACKET, S_URL);
makeT(S_URL_OPENPAREN_Q, CLOSEPAREN, S_URL);
makeT(S_URL_OPENBRACE_SYMS, CLOSEBRACE, S_URL);
makeT(S_URL_OPENBRACKET_SYMS, CLOSEBRACKET, S_URL);
makeT(S_URL_OPENANGLEBRACKET_SYMS, CLOSEANGLEBRACKET, S_URL);
makeT(S_URL_OPENPAREN_SYMS, CLOSEPAREN, S_URL); // URL that beings with an opening bracket, followed by a symbols.
// Note that the final state can still be `S_URL_OPENBRACE_Q` (if the URL only
// has a single opening bracket for some reason).
makeMultiT(S_URL_OPENBRACE, qsAccepting, S_URL_OPENBRACE_Q);
makeMultiT(S_URL_OPENBRACKET, qsAccepting, S_URL_OPENBRACKET_Q);
makeMultiT(S_URL_OPENANGLEBRACKET, qsAccepting, S_URL_OPENANGLEBRACKET_Q);
makeMultiT(S_URL_OPENPAREN, qsAccepting, S_URL_OPENPAREN_Q);
makeMultiT(S_URL_OPENBRACE, qsNonAccepting, S_URL_OPENBRACE_SYMS);
makeMultiT(S_URL_OPENBRACKET, qsNonAccepting, S_URL_OPENBRACKET_SYMS);
makeMultiT(S_URL_OPENANGLEBRACKET, qsNonAccepting, S_URL_OPENANGLEBRACKET_SYMS);
makeMultiT(S_URL_OPENPAREN, qsNonAccepting, S_URL_OPENPAREN_SYMS); // URL that begins with an opening bracket, followed by some symbols
makeMultiT(S_URL_OPENBRACE_Q, qsAccepting, S_URL_OPENBRACE_Q);
makeMultiT(S_URL_OPENBRACKET_Q, qsAccepting, S_URL_OPENBRACKET_Q);
makeMultiT(S_URL_OPENANGLEBRACKET_Q, qsAccepting, S_URL_OPENANGLEBRACKET_Q);
makeMultiT(S_URL_OPENPAREN_Q, qsAccepting, S_URL_OPENPAREN_Q);
makeMultiT(S_URL_OPENBRACE_Q, qsNonAccepting, S_URL_OPENBRACE_Q);
makeMultiT(S_URL_OPENBRACKET_Q, qsNonAccepting, S_URL_OPENBRACKET_Q);
makeMultiT(S_URL_OPENANGLEBRACKET_Q, qsNonAccepting, S_URL_OPENANGLEBRACKET_Q);
makeMultiT(S_URL_OPENPAREN_Q, qsNonAccepting, S_URL_OPENPAREN_Q);
makeMultiT(S_URL_OPENBRACE_SYMS, qsAccepting, S_URL_OPENBRACE_Q);
makeMultiT(S_URL_OPENBRACKET_SYMS, qsAccepting, S_URL_OPENBRACKET_Q);
makeMultiT(S_URL_OPENANGLEBRACKET_SYMS, qsAccepting, S_URL_OPENANGLEBRACKET_Q);
makeMultiT(S_URL_OPENPAREN_SYMS, qsAccepting, S_URL_OPENPAREN_Q);
makeMultiT(S_URL_OPENBRACE_SYMS, qsNonAccepting, S_URL_OPENBRACE_SYMS);
makeMultiT(S_URL_OPENBRACKET_SYMS, qsNonAccepting, S_URL_OPENBRACKET_SYMS);
makeMultiT(S_URL_OPENANGLEBRACKET_SYMS, qsNonAccepting, S_URL_OPENANGLEBRACKET_SYMS);
makeMultiT(S_URL_OPENPAREN_SYMS, qsNonAccepting, S_URL_OPENPAREN_SYMS); // Account for the query string
makeMultiT(S_URL, qsAccepting, S_URL);
makeMultiT(S_URL_NON_ACCEPTING, qsAccepting, S_URL);
makeMultiT(S_URL, qsNonAccepting, S_URL_NON_ACCEPTING);
makeMultiT(S_URL_NON_ACCEPTING, qsNonAccepting, S_URL_NON_ACCEPTING); // Email address-specific state definitions
// Note: We are not allowing '/' in email addresses since this would interfere
// with real URLs
// For addresses with the mailto prefix
// 'mailto:' followed by anything sane is a valid email
makeT(S_MAILTO, TLD, S_MAILTO_EMAIL);
makeT(S_MAILTO, DOMAIN, S_MAILTO_EMAIL);
makeT(S_MAILTO, NUM, S_MAILTO_EMAIL);
makeT(S_MAILTO, LOCALHOST, S_MAILTO_EMAIL); // Greedily get more potential valid email values
makeMultiT(S_MAILTO_EMAIL, qsAccepting, S_MAILTO_EMAIL);
makeMultiT(S_MAILTO_EMAIL, qsNonAccepting, S_MAILTO_EMAIL_NON_ACCEPTING);
makeMultiT(S_MAILTO_EMAIL_NON_ACCEPTING, qsAccepting, S_MAILTO_EMAIL);
makeMultiT(S_MAILTO_EMAIL_NON_ACCEPTING, qsNonAccepting, S_MAILTO_EMAIL_NON_ACCEPTING); // For addresses without the mailto prefix
// Tokens allowed in the localpart of the email
var localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, CLOSEBRACE, DOLLAR, DOMAIN, EQUALS, HYPHEN, NUM, OPENBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, TLD, UNDERSCORE]; // Some of the tokens in `localpartAccepting` are already accounted for here and
// will not be overwritten (don't worry)
makeMultiT(S_DOMAIN, localpartAccepting, S_LOCALPART);
makeT(S_DOMAIN, AT, S_LOCALPART_AT);
makeMultiT(S_TLD, localpartAccepting, S_LOCALPART);
makeT(S_TLD, AT, S_LOCALPART_AT);
makeMultiT(S_DOMAIN_DOT, localpartAccepting, S_LOCALPART); // Now in localpart of address
// TODO: IP addresses and what if the email starts with numbers?
makeMultiT(S_LOCALPART, localpartAccepting, S_LOCALPART);
makeT(S_LOCALPART, AT, S_LOCALPART_AT); // close to an email address now
makeT(S_LOCALPART, DOT, S_LOCALPART_DOT);
makeMultiT(S_LOCALPART_DOT, localpartAccepting, S_LOCALPART);
makeT(S_LOCALPART_AT, TLD, S_EMAIL_DOMAIN);
makeT(S_LOCALPART_AT, DOMAIN, S_EMAIL_DOMAIN);
makeT(S_LOCALPART_AT, NUM, S_EMAIL_DOMAIN);
makeT(S_LOCALPART_AT, LOCALHOST, S_EMAIL); // States following `@` defined above
return S_START;
}
/**
* Run the parser state machine on a list of scanned string-based tokens to
* create a list of multi tokens, each of which represents a URL, email address,
* plain text, etc.
*
* @param {State} start parser start state
* @param {string} input the original input used to generate the given tokens
* @param {{t: string, v: string, s: number, e: number}[]} tokens list of scanned tokens
* @returns {MultiToken[]}
*/
function run(start, input, tokens) {
var len = tokens.length;
var cursor = 0;
var multis = [];
var textTokens = [];
while (cursor < len) {
var state = start;
var secondState = null;
var nextState = null;
var multiLength = 0;
var latestAccepting = null;
var sinceAccepts = -1;
while (cursor < len && !(secondState = takeT(state, tokens[cursor].t))) {
// Starting tokens with nowhere to jump to.
// Consider these to be just plain text
textTokens.push(tokens[cursor++]);
}
while (cursor < len && (nextState = secondState || takeT(state, tokens[cursor].t))) {
// Get the next state
secondState = null;
state = nextState; // Keep track of the latest accepting state
if (state.accepts()) {
sinceAccepts = 0;
latestAccepting = state;
} else if (sinceAccepts >= 0) {
sinceAccepts++;
}
cursor++;
multiLength++;
}
if (sinceAccepts < 0) {
// No accepting state was found, part of a regular text token
// Add all the tokens we looked at to the text tokens array
for (var i = cursor - multiLength; i < cursor; i++) {
textTokens.push(tokens[i]);
}
} else {
// Accepting state!
// First close off the textTokens (if available)
if (textTokens.length > 0) {
multis.push(parserCreateMultiToken(Text, input, textTokens));
textTokens = [];
} // Roll back to the latest accepting state
cursor -= sinceAccepts;
multiLength -= sinceAccepts; // Create a new multitoken
var Multi = latestAccepting.t;
var subtokens = tokens.slice(cursor - multiLength, cursor);
multis.push(parserCreateMultiToken(Multi, input, subtokens));
}
} // Finally close off the textTokens (if available)
if (textTokens.length > 0) {
multis.push(parserCreateMultiToken(Text, input, textTokens));
}
return multis;
}
/**
* Utility function for instantiating a new multitoken with all the relevant
* fields during parsing.
* @param {Class<MultiToken>} Multi class to instantiate
* @param {string} input original input string
* @param {{t: string, v: string, s: number, e: number}[]} tokens consecutive tokens scanned from input string
* @returns {MultiToken}
*/
function parserCreateMultiToken(Multi, input, tokens) {
var startIdx = tokens[0].s;
var endIdx = tokens[tokens.length - 1].e;
var value = input.substr(startIdx, endIdx - startIdx);
return new Multi(value, tokens);
}
var warn = typeof console !== 'undefined' && console && console.warn || function () {}; // Side-effect initialization state
var INIT = {
scanner: null,
parser: null,
pluginQueue: [],
customProtocols: [],
initialized: false
};
/**
* Register a linkify extension plugin
* @param {string} name of plugin to register
* @param {Function} plugin function that accepts mutable linkify state
*/
function registerPlugin(name, plugin) {
for (var i = 0; i < INIT.pluginQueue.length; i++) {
if (name === INIT.pluginQueue[i][0]) {
warn("linkifyjs: plugin \"".concat(name, "\" already registered - will be overwritten"));
INIT.pluginQueue[i] = [name, plugin];
return;
}
}
INIT.pluginQueue.push([name, plugin]);
if (INIT.initialized) {
warn("linkifyjs: already initialized - will not register plugin \"".concat(name, "\" until you manually call linkify.init(). To avoid this warning, please register all plugins before invoking linkify the first time."));
}
}
/**
* Initialize the linkify state machine. Called automatically the first time
* linkify is called on a string, but may be called manually as well.
*/
function init() {
// Initialize state machines
INIT.scanner = {
start: init$2(INIT.customProtocols),
tokens: text
};
INIT.parser = {
start: init$1(),
tokens: multi
};
var utils = {
createTokenClass: createTokenClass
}; // Initialize plugins
for (var i = 0; i < INIT.pluginQueue.length; i++) {
INIT.pluginQueue[i][1]({
scanner: INIT.scanner,
parser: INIT.parser,
utils: utils
});
}
INIT.initialized = true;
}
/**
Parse a string into tokens that represent linkable and non-linkable sub-components
@param {string} str
@return {MultiToken[]} tokens
*/
function tokenize(str) {
if (!INIT.initialized) {
init();
}
return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));
}
/**
Convert strings of text into linkable HTML text
*/
function escapeText(text) {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function escapeAttr(href) {
return href.replace(/"/g, '&quot;');
}
function attributesToString(attributes) {
if (!attributes) {
return '';
}
var result = [];
for (var attr in attributes) {
var val = attributes[attr] + '';
result.push("".concat(attr, "=\"").concat(escapeAttr(val), "\""));
}
return result.join(' ');
}
/**
* Convert a plan text string to an HTML string with links. Expects that the
* given strings does not contain any HTML entities. Use the linkify-html
* interface if you need to parse HTML entities.
*
* @param {string} str string to linkify
* @param {object} [opts] overridable options
* @returns {string}
*/
function linkifyStr(str) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
opts = new Options(opts);
var tokens = tokenize(str);
var result = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.t === 'nl' && opts.nl2br) {
result.push('<br>\n');
continue;
} else if (!token.isLink || !opts.check(token)) {
result.push(escapeText(token.toString()));
continue;
}
var _opts$resolve = opts.resolve(token),
formatted = _opts$resolve.formatted,
formattedHref = _opts$resolve.formattedHref,
tagName = _opts$resolve.tagName,
className = _opts$resolve.className,
target = _opts$resolve.target,
rel = _opts$resolve.rel,
attributes = _opts$resolve.attributes;
var link = ["<".concat(tagName, " href=\"").concat(escapeAttr(formattedHref), "\"")];
if (className) {
link.push(" class=\"".concat(escapeAttr(className), "\""));
}
if (target) {
link.push(" target=\"".concat(escapeAttr(target), "\""));
}
if (rel) {
link.push(" rel=\"".concat(escapeAttr(rel), "\""));
}
if (attributes) {
link.push(" ".concat(attributesToString(attributes)));
}
link.push(">".concat(escapeText(formatted), "</").concat(tagName, ">"));
result.push(link.join(''));
}
return result.join('');
}
if (!String.prototype.linkify) {
Object.defineProperty(String.prototype, 'linkify', {
writable: false,
value: function linkify(options) {
return linkifyStr(this, options);
}
});
}
/* src/Components/TextEmbeddings.svelte generated by Svelte v3.44.3 */
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[2] = list[i];
return child_ctx;
}
// (6:0) {#each contents as content}
function create_each_block(ctx) {
let div;
let html_tag;
let raw_value = linkifyStr(/*content*/ ctx[2]) + "";
let t;
return {
c() {
div = element("div");
html_tag = new HtmlTag();
t = space();
html_tag.a = t;
attr(div, "class", "additionnal svelte-nv2bo1");
},
m(target, anchor) {
insert(target, div, anchor);
html_tag.m(raw_value, div);
append(div, t);
},
p: noop$1,
d(detaching) {
if (detaching) detach(div);
}
};
}
function create_fragment(ctx) {
let each_1_anchor;
let each_value = /*contents*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*sanLink, contents*/ 1) {
each_value = /*contents*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop$1,
o: noop$1,
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { files } = $$props;
let contents = files.map(e => e.data.toString());
$$self.$$set = $$props => {
if ('files' in $$props) $$invalidate(1, files = $$props.files);
};
return [contents, files];
}
class TextEmbeddings extends SvelteComponent {
constructor(options) {
super();
init$3(this, options, instance, create_fragment, safe_not_equal, { files: 1 });
}
get files() {
return this.$$.ctx[1];
}
set files(files) {
this.$$set({ files });
flush();
}
}
function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator$1(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var HydrusClient = /*#__PURE__*/ function() {
function HydrusClient(ak) {
var origin = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "http://127.0.0.1", port = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 45869;
_classCallCheck(this, HydrusClient);
this.ak = ak;
this.origin = origin;
this.port = port;
}
var _proto = HydrusClient.prototype;
_proto.get = function get(params) {
var _this = this;
return _asyncToGenerator$1(regeneratorRuntime$1.mark(function _callee() {
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return fetch(_this.baseUrl + params, {
headers: {
"Hydrus-Client-API-Access-Key": _this.ak
}
});
case 2:
return _ctx.abrupt("return", _ctx.sent);
case 3:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_proto.verify = function verify() {
var _this = this;
return _asyncToGenerator$1(regeneratorRuntime$1.mark(function _callee() {
var ret;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.prev = 0;
_ctx.next = 3;
return _this.get("/verify_access_key");
case 3:
ret = _ctx.sent;
_ctx.next = 6;
return ret.json();
case 6:
return _ctx.abrupt("return", !!_ctx.sent);
case 9:
_ctx.prev = 9;
_ctx.t0 = _ctx["catch"](0);
return _ctx.abrupt("return", false);
case 12:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
0,
9
]
]);
}))();
};
_proto.idsByTags = function idsByTags(taglist, args) {
var _this = this;
return _asyncToGenerator$1(regeneratorRuntime$1.mark(function _callee() {
var req;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return _this.get("/get_files/search_files?tags=" + encodeURIComponent(JSON.stringify(taglist)) + (args ? "&" + Object.entries(args).map(function(e) {
return "".concat(e[0], "=").concat(encodeURIComponent(e[1]));
}).join("&") : ""));
case 2:
req = _ctx.sent;
_ctx.next = 5;
return req.json();
case 5:
return _ctx.abrupt("return", _ctx.sent);
case 6:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_proto.getMetaDataByIds = function getMetaDataByIds(ids) {
var _this = this;
return _asyncToGenerator$1(regeneratorRuntime$1.mark(function _callee() {
var req;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return _this.get("/get_files/file_metadata?file_ids=" + encodeURIComponent(JSON.stringify(ids)));
case 2:
req = _ctx.sent;
_ctx.next = 5;
return req.json();
case 5:
return _ctx.abrupt("return", _ctx.sent);
case 6:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_proto.getFile = function getFile(id) {
var _this = this;
return _asyncToGenerator$1(regeneratorRuntime$1.mark(function _callee() {
var req;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return _this.get("/get_files/file?file_id=" + id);
case 2:
req = _ctx.sent;
_ctx.next = 5;
return req.arrayBuffer();
case 5:
return _ctx.abrupt("return", _ctx.sent);
case 6:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_proto.getThumbnail = function getThumbnail(id) {
var _this = this;
return _asyncToGenerator$1(regeneratorRuntime$1.mark(function _callee() {
var req;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return _this.get("/get_files/thumbnail?file_id=" + id);
case 2:
req = _ctx.sent;
_ctx.next = 5;
return req.arrayBuffer();
case 5:
return _ctx.abrupt("return", _ctx.sent);
case 6:
case "end":
return _ctx.stop();
}
}, _callee);
}))();
};
_createClass(HydrusClient, [
{
key: "baseUrl",
get: function get() {
return "".concat(this.origin, ":").concat(this.port);
}
}
]);
return HydrusClient;
}();
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _instanceof(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _objectSpread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
var qp;
exports.csettings = initial_settings;
var processors = [
thirdeye,
pomf,
pngv3,
jpg,
webm,
gif
];
var cappState;
settings.subscribe(function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(b) {
var hydCli, herror, valid;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (!b.hyd) {
_ctx.next = 17;
break;
}
if (!b.ak) {
_ctx.next = 17;
break;
}
hydCli = new HydrusClient(b.ak);
console.log(b.ak);
_ctx.prev = 5;
_ctx.next = 8;
return hydCli.verify();
case 8:
valid = _ctx.sent;
if (!valid) herror = "Hydrus appears to not be running or the key is wrong.";
appState.set(_objectSpread({}, cappState, {
akValid: valid,
client: hydCli,
herror: herror
}));
_ctx.next = 17;
break;
case 13:
_ctx.prev = 13;
_ctx.t0 = _ctx["catch"](5);
herror = "Hydrus appears to not be running";
appState.set(_objectSpread({}, cappState, {
akValid: false,
client: null,
herror: herror
}));
case 17:
exports.csettings = b;
processors = _toConsumableArray(!exports.csettings.te ? [
thirdeye
] : []).concat([
pngv3,
pomf,
jpg,
webm,
gif
]);
case 19:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
5,
13
]
]);
}));
return function(b) {
return _ref.apply(this, arguments);
};
}());
appState.subscribe(function(v) {
cappState = v;
});
var processImage = function() {
var _ref1 = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee1(src, fn, hex, prevurl, onfound) {
return regeneratorRuntime$1.wrap(function _callee$(_ctx1) {
while(1)switch(_ctx1.prev = _ctx1.next){
case 0:
return _ctx1.abrupt("return", Promise.all(processors.filter(function(e) {
return e.match(fn);
}).map(function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(proc) {
var md5, iter, cumul, found, chunk, ref, value, done;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (!proc.skip) {
_ctx.next = 12;
break;
}
md5 = Buffer$1.from(hex, "base64");
_ctx.next = 4;
return proc.has_embed(md5, fn, prevurl);
case 4:
_ctx.t0 = _ctx.sent;
if (!(_ctx.t0 === true)) {
_ctx.next = 11;
break;
}
onfound();
_ctx.next = 9;
return proc.extract(md5, fn);
case 9:
_ctx.t1 = _ctx.sent;
return _ctx.abrupt("return", [
_ctx.t1,
true
]);
case 11:
return _ctx.abrupt("return");
case 12:
iter = streamRemote(src);
if (iter) {
_ctx.next = 15;
break;
}
return _ctx.abrupt("return");
case 15:
cumul = Buffer$1.alloc(0);
chunk = {
done: true
};
case 18:
_ctx.next = 20;
return iter.next(found === false);
case 20:
ref = _ctx.sent;
value = ref.value;
done = ref.done;
if (done) {
chunk = {
done: true
};
} else {
chunk = {
done: false,
value: value
};
}
if (!done) cumul = Buffer$1.concat([
cumul,
value
]);
_ctx.next = 27;
return proc.has_embed(cumul);
case 27:
found = _ctx.sent;
case 28:
if (found !== false && !chunk.done) {
_ctx.next = 18;
break;
}
case 29:
_ctx.next = 31;
return iter.next(true);
case 31:
if (!(found === false)) {
_ctx.next = 33;
break;
}
return _ctx.abrupt("return");
case 33:
onfound();
_ctx.next = 36;
return proc.extract(cumul);
case 36:
_ctx.t2 = _ctx.sent;
return _ctx.abrupt("return", [
_ctx.t2,
false
]);
case 38:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function(proc) {
return _ref.apply(this, arguments);
};
}())));
case 1:
case "end":
return _ctx1.stop();
}
}, _callee1);
}));
return function processImage(src, fn, hex, prevurl, onfound) {
return _ref1.apply(this, arguments);
};
}();
var textToElement = function(s) {
return document.createRange().createContextualFragment(s).children[0];
};
var pendingPosts = [];
var signalNewEmbeds = debounce(_asyncToGenerator(regeneratorRuntime$1.mark(function _callee() {
var boardname, reshaped, res;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (exports.csettings.tm) {
_ctx.next = 2;
break;
}
return _ctx.abrupt("return");
case 2:
_ctx.prev = 2;
boardname = location.pathname.match(/\/([^/]*)\//)[1];
reshaped = Object.fromEntries(_toConsumableArray(new Set(pendingPosts.map(function(e) {
return e.op;
}))).map(function(e1) {
return [
e1,
pendingPosts.filter(function(p) {
return p.op == e1;
}).map(function(e) {
return e.id;
})
];
}));
console.log(reshaped);
_ctx.next = 8;
return fetch("https://shoujo.coom.tech/listing/" + boardname, {
method: "POST",
body: JSON.stringify(reshaped),
headers: {
"content-type": "application/json"
}
});
case 8:
res = _ctx.sent;
_ctx.next = 11;
return res.json();
case 11:
pendingPosts = [];
_ctx.next = 17;
break;
case 14:
_ctx.prev = 14;
_ctx.t0 = _ctx["catch"](2);
// silently fail
console.error(_ctx.t0);
case 17:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
2,
14
]
]);
})), 5000, {
trailing: true
});
var processPost = function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(post) {
var origlink, thumbLink, res2;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
origlink = qp.getImageLink(post);
if (origlink) {
_ctx.next = 3;
break;
}
return _ctx.abrupt("return");
case 3:
thumbLink = qp.getThumbnailLink(post);
if (thumbLink) {
_ctx.next = 6;
break;
}
return _ctx.abrupt("return");
case 6:
_ctx.next = 8;
return processImage(origlink, qp.getFilename(post), qp.getMD5(post), thumbLink, function() {
var ref;
if (exports.csettings.tm) {
// dont report results from archive, only live threads
if ([
"boards.4chan.org",
"boards.4channel.org"
].includes(location.host)) {
if (!cappState.isCatalog) {
// we must be in a thread, thus the following is valid
var op = +location.pathname.match(/\/thread\/(.*)/)[1];
pendingPosts.push({
id: +post.id.match(/([0-9]+)/)[1],
op: op
});
signalNewEmbeds(); // let it run async
}
}
}
(ref = post.querySelector(".post")) === null || ref === void 0 ? void 0 : ref.classList.add("embedfound");
});
case 8:
res2 = _ctx.sent;
res2 = res2 === null || res2 === void 0 ? void 0 : res2.filter(function(e) {
return e;
});
if (!(!res2 || res2.length == 0)) {
_ctx.next = 12;
break;
}
return _ctx.abrupt("return");
case 12:
processAttachments(post, res2 === null || res2 === void 0 ? void 0 : res2.flatMap(function(e) {
return e[0].map(function(k) {
return [
k,
e[1]
];
});
}));
case 13:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function processPost(post) {
return _ref.apply(this, arguments);
};
}();
var versionCheck = function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee() {
var ref, lmajor, lminor, _BUILD_VERSION, major, minor;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.t0 = _slicedToArray;
_ctx.next = 3;
return ifetch("https://git.coom.tech/coomdev/PEE/raw/branch/%e4%b8%ad%e5%87%ba%e3%81%97/main.meta.js");
case 3:
_ctx.next = 5;
return _ctx.sent.text();
case 5:
_ctx.t1 = _ctx.sent.split("\n").filter(function(e) {
return e.includes("// @version");
})[0].match(/.*version\s+(.*)/)[1].split(".").map(function(e) {
return +e;
});
ref = (0, _ctx.t0)(_ctx.t1, 2);
lmajor = ref[0];
lminor = ref[1];
_BUILD_VERSION = _slicedToArray([0,191], 2), major = _BUILD_VERSION[0], minor = _BUILD_VERSION[1];
if (major < lmajor || major == lmajor && minor < lminor) {
fireNotification("info", "Last PEE version is ".concat(lmajor, ".").concat(lminor, ", you're on ").concat(major, ".").concat(minor));
}
case 11:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function versionCheck() {
return _ref.apply(this, arguments);
};
}();
// Not using the clipboard API because it needs focus
function copyTextToClipboard(text) {
var copyFrom = document.createElement("textarea");
copyFrom.textContent = text;
document.body.appendChild(copyFrom);
copyFrom.select();
document.execCommand("copy");
copyFrom.blur();
document.body.removeChild(copyFrom);
navigator.clipboard.writeText(text);
}
var scrapeBoard = function() {
var _ref2 = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee2(self) {
var boardname, res1, pages, threads, filenames, n, processFile, range, hasEmbed, total, processed, int, counters, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, k, text;
return regeneratorRuntime$1.wrap(function _callee$(_ctx2) {
while(1)switch(_ctx2.prev = _ctx2.next){
case 0:
if (exports.csettings.tm) {
fireNotification("success", "Scrapping board with telemetry on! Thank you for your service, selfless stranger ;_;7");
}
self.disabled = true;
self.textContent = "Searching...";
boardname = location.pathname.match(/\/([^/]*)\//)[1];
_ctx2.next = 6;
return ifetch("https://a.4cdn.org/".concat(boardname, "/threads.json"));
case 6:
res1 = _ctx2.sent;
_ctx2.next = 9;
return res1.json();
case 9:
pages = _ctx2.sent;
fireNotification("info", "Fetching all threads...");
_ctx2.next = 13;
return Promise.all(pages.reduce(function(a, b) {
return _toConsumableArray(a).concat(_toConsumableArray(b.threads));
}, []).map(function(e) {
return e.no;
}).map(function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(id) {
var res;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.prev = 0;
_ctx.next = 3;
return ifetch("https://a.4cdn.org/".concat(boardname, "/thread/").concat(id, ".json"));
case 3:
res = _ctx.sent;
_ctx.next = 6;
return res.json();
case 6:
return _ctx.abrupt("return", _ctx.sent);
case 9:
_ctx.prev = 9;
_ctx.t0 = _ctx["catch"](0);
return _ctx.abrupt("return", undefined);
case 12:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
0,
9
]
]);
}));
return function(id) {
return _ref.apply(this, arguments);
};
}()));
case 13:
threads = _ctx2.sent.filter(function(e) {
return e;
}).map(function(e) {
return e;
});
filenames = threads.reduce(function(a, b) {
return _toConsumableArray(a).concat(_toConsumableArray(b.posts.filter(function(p) {
return p.ext;
}).map(function(p) {
return p;
})));
}, []).filter(function(p) {
return p.ext != ".webm" && p.ext != ".gif";
}).map(function(p) {
return [
p.resto || p.no,
"https://i.4cdn.org/".concat(boardname, "/").concat(p.tim).concat(p.ext),
p.md5,
p.filename + p.ext,
p.no
];
});
console.log(filenames);
fireNotification("info", "Analyzing images...");
n = 7;
processFile = function(src, fn, hex) {
return Promise.all(processors.filter(function(e) {
return e.match(fn);
}).map(function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(proc) {
var md5, iter, cumul, found, chunk, ref, value, done;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
if (!proc.skip) {
_ctx.next = 5;
break;
}
md5 = Buffer$1.from(hex, "base64");
_ctx.next = 4;
return proc.has_embed(md5, fn);
case 4:
return _ctx.abrupt("return", _ctx.sent);
case 5:
iter = streamRemote(src);
if (iter) {
_ctx.next = 8;
break;
}
return _ctx.abrupt("return", false);
case 8:
cumul = Buffer$1.alloc(0);
chunk = {
done: true
};
case 11:
_ctx.next = 13;
return iter.next(found === false);
case 13:
ref = _ctx.sent;
value = ref.value;
done = ref.done;
if (done) {
chunk = {
done: true
};
} else {
chunk = {
done: false,
value: value
};
}
if (!done) cumul = Buffer$1.concat([
cumul,
value
]);
_ctx.next = 20;
return proc.has_embed(cumul);
case 20:
found = _ctx.sent;
case 21:
if (found !== false && !chunk.done) {
_ctx.next = 11;
break;
}
case 22:
_ctx.next = 24;
return iter.next(true);
case 24:
return _ctx.abrupt("return", found === true);
case 25:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function(proc) {
return _ref.apply(this, arguments);
};
}()));
};
range = ~~(filenames.length / n) + 1;
hasEmbed = [];
total = filenames.length;
processed = 0;
int = setInterval(function() {
fireNotification("info", "Processed [".concat(processed, " / ").concat(total, "] files"));
}, 5000);
_ctx2.next = 26;
return Promise.all(_toConsumableArray(new Array(n + 1)).map(function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(e2, i) {
var postsslice, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, post, res;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
postsslice = filenames.slice(i * range, (i + 1) * range);
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx.prev = 2;
_iterator = postsslice[Symbol.iterator]();
case 4:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_ctx.next = 20;
break;
}
post = _step.value;
_ctx.prev = 6;
_ctx.next = 9;
return processFile(post[1], post[3], post[2]);
case 9:
res = _ctx.sent;
processed++;
if (res.some(function(e) {
return e;
})) {
hasEmbed.push(post);
// dont report results from archive, only live threads
if ([
"boards.4chan.org",
"boards.4channel.org"
].includes(location.host)) {
pendingPosts.push({
id: post[4],
op: post[0]
});
signalNewEmbeds(); // let it run async
}
}
_ctx.next = 17;
break;
case 14:
_ctx.prev = 14;
_ctx.t0 = _ctx["catch"](6);
console.log(_ctx.t0);
case 17:
_iteratorNormalCompletion = true;
_ctx.next = 4;
break;
case 20:
_ctx.next = 26;
break;
case 22:
_ctx.prev = 22;
_ctx.t1 = _ctx["catch"](2);
_didIteratorError = true;
_iteratorError = _ctx.t1;
case 26:
_ctx.prev = 26;
_ctx.prev = 27;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 29:
_ctx.prev = 29;
if (!_didIteratorError) {
_ctx.next = 32;
break;
}
throw _iteratorError;
case 32:
return _ctx.finish(29);
case 33:
return _ctx.finish(26);
case 34:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
2,
22,
26,
34
],
[
6,
14
],
[
27,
,
29,
33
]
]);
}));
return function(e2, i) {
return _ref.apply(this, arguments);
};
}()));
case 26:
clearInterval(int);
counters = {};
_iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
_ctx2.prev = 29;
for(_iterator1 = hasEmbed[Symbol.iterator](); !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
k = _step1.value;
counters[k[0]] = k[0] in counters ? counters[k[0]] + 1 : 1;
}
_ctx2.next = 37;
break;
case 33:
_ctx2.prev = 33;
_ctx2.t0 = _ctx2["catch"](29);
_didIteratorError1 = true;
_iteratorError1 = _ctx2.t0;
case 37:
_ctx2.prev = 37;
_ctx2.prev = 38;
if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
_iterator1.return();
}
case 40:
_ctx2.prev = 40;
if (!_didIteratorError1) {
_ctx2.next = 43;
break;
}
throw _iteratorError1;
case 43:
return _ctx2.finish(40);
case 44:
return _ctx2.finish(37);
case 45:
console.log(counters);
fireNotification("success", "Processing finished! Results pasted in the clipboard");
text = Object.entries(counters).sort(function(a, b) {
return b[1] - a[1];
}).map(function(e) {
return ">>".concat(e[0], " (").concat(e[1], ")");
}).join("\n");
console.log(text);
copyTextToClipboard(text);
self.textContent = "Copy Results";
self.disabled = false;
self.onclick = function() {
copyTextToClipboard(text);
};
case 53:
case "end":
return _ctx2.stop();
}
}, _callee2, null, [
[
29,
33,
37,
45
],
[
38,
,
40,
44
]
]);
}));
return function scrapeBoard(self) {
return _ref2.apply(this, arguments);
};
}();
var startup = function() {
var _ref3 = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee3() {
var is4chanX, meta1, lqp, postQuote, qr1, show, notificationHost, mo, posts, scts, button, appHost, scrollHost, opts, button1, n, range, _args = arguments;
return regeneratorRuntime$1.wrap(function _callee$(_ctx3) {
while(1)switch(_ctx3.prev = _ctx3.next){
case 0:
is4chanX = _args.length > 0 && _args[0] !== void 0 ? _args[0] : true;
meta1 = document.querySelector('meta[name="referrer"]');
if (meta1) {
meta1.setAttribute("name", "referrer");
meta1.setAttribute("content", "no-referrer");
}
appState.set(_objectSpread({}, cappState, {
is4chanX: is4chanX
}));
lqp = getQueryProcessor(is4chanX);
if (lqp) {
_ctx3.next = 9;
break;
}
return _ctx3.abrupt("return");
case 9:
qp = lqp;
case 10:
if (exports.csettings.vercheck) versionCheck();
postQuote = function(param) {
var scanner = param.scanner, parser = param.parser, utils = param.utils;
var _tokens = scanner.tokens, CLOSEANGLEBRACKET = _tokens.CLOSEANGLEBRACKET, NUM = _tokens.NUM;
var START_STATE = parser.start;
var pref = qp.getPostIdPrefix();
var endQuote = utils.createTokenClass("postQuote", {
isLink: true,
toHref: function toHref() {
return "#".concat(pref).concat(this.toString().substr(2));
}
});
// A post quote (>>123456789) is made of
var MEMEARROW1 = START_STATE.tt(CLOSEANGLEBRACKET); // One meme arrow followed by
var MEMEARROW2 = MEMEARROW1.tt(CLOSEANGLEBRACKET); // another meme arrow, terminated by
MEMEARROW2.tt(NUM, endQuote); // a number
};
registerPlugin("quote", postQuote);
if (!is4chanX && location.host.startsWith("boards.4chan")) {
qr1 = QR;
show = qr1.show.bind(qr1);
qr1.show = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
show.apply(void 0, _toConsumableArray(args));
document.dispatchEvent(new CustomEvent("QRDialogCreation", {
detail: document.getElementById("quickReply")
}));
};
document.addEventListener("QRGetFile", function(e) {
var qr = document.getElementById("qrFile");
document.dispatchEvent(new CustomEvent("QRFile", {
detail: ((qr === null || qr === void 0 ? void 0 : qr.files) || [])[0]
}));
});
document.addEventListener("QRSetFile", function(e) {
var qr = document.getElementById("qrFile");
if (!qr) return;
var dt = new DataTransfer();
dt.items.add(new File([
e.detail.file
], e.detail.name));
qr.files = dt.files;
});
notificationHost = document.createElement("span");
new NotificationsHandler({
target: notificationHost
});
document.body.append(notificationHost);
}
mo = new MutationObserver(function(reco) {
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = reco[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var rec = _step.value;
if (rec.type == "childList") rec.addedNodes.forEach(function(e) {
if (!_instanceof(e, HTMLElement)) return;
// apparently querySelector cannot select the root element if it matches
var el1 = qp.postsWithFiles(e);
if (!el1 && e.classList.contains("postContainer")) el1 = [
e
];
if (el1) _toConsumableArray(el1).map(function(el) {
return processPost(el);
});
});
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
});
document.querySelectorAll(".board").forEach(function(e) {
mo.observe(e, {
childList: true,
subtree: true
});
});
posts = qp.postsWithFiles();
scts = qp.settingsHost();
button = textToElement("<span></span>");
new SettingsButton({
target: button
});
scts === null || scts === void 0 ? void 0 : scts.appendChild(button);
appHost = textToElement('<div class="pee-settings"></div>');
new App({
target: appHost
});
document.body.append(appHost);
scrollHost = textToElement('<div class="pee-scroll"></div>');
new ScrollHighlighter({
target: scrollHost
});
document.body.append(scrollHost);
appState.set(_objectSpread({}, cappState, {
isCatalog: !!document.querySelector(".catalog-small") || !!location.pathname.match(/\/catalog$/)
}));
//await processPost(posts[0] as any);
if (cappState.isCatalog) {
opts = qp.catalogControlHost();
if (opts) {
button1 = document.createElement("button");
button1.textContent = "\u304A\u3082\u3089\u3057";
button1.onclick = function() {
return scrapeBoard(button1);
};
opts.insertAdjacentElement("beforebegin", button1);
}
}
n = 7;
range = ~~(posts.length / n) + 1;
_ctx3.next = 33;
return Promise.all(_toConsumableArray(new Array(n + 1)).map(function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(e, i) {
var postsslice, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, post;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
postsslice = posts.slice(i * range, (i + 1) * range);
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx.prev = 2;
_iterator = postsslice[Symbol.iterator]();
case 4:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_ctx.next = 17;
break;
}
post = _step.value;
_ctx.prev = 6;
_ctx.next = 9;
return processPost(post);
case 9:
_ctx.next = 14;
break;
case 11:
_ctx.prev = 11;
_ctx.t0 = _ctx["catch"](6);
console.log("Processing failed for post", post, _ctx.t0);
case 14:
_iteratorNormalCompletion = true;
_ctx.next = 4;
break;
case 17:
_ctx.next = 23;
break;
case 19:
_ctx.prev = 19;
_ctx.t1 = _ctx["catch"](2);
_didIteratorError = true;
_iteratorError = _ctx.t1;
case 23:
_ctx.prev = 23;
_ctx.prev = 24;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 26:
_ctx.prev = 26;
if (!_didIteratorError) {
_ctx.next = 29;
break;
}
throw _iteratorError;
case 29:
return _ctx.finish(26);
case 30:
return _ctx.finish(23);
case 31:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
2,
19,
23,
31
],
[
6,
11
],
[
24,
,
26,
30
]
]);
}));
return function(e, i) {
return _ref.apply(this, arguments);
};
}()));
case 33:
case "end":
return _ctx3.stop();
}
}, _callee3);
//await Promise.all(posts.map(e => processPost(e as any)));
}));
return function startup() {
return _ref3.apply(this, arguments);
};
}();
document.addEventListener("4chanXInitFinished", function() {
return startup(true);
});
document.addEventListener("4chanParsingDone", function() {
return startup(false);
}, {
once: true
});
if (supportedAltDomain()) {
window.addEventListener("load", function() {
startup(false);
}, {
once: true
});
}
document.addEventListener("4chanThreadUpdated", function(e3) {
document.dispatchEvent(new CustomEvent("ThreadUpdate", {
detail: {
newPosts: _toConsumableArray(document.querySelector(".thread").children).slice(-e3.detail.count).map(function(e) {
return "b." + e.id.slice(2);
})
}
}));
});
document.addEventListener("ThreadUpdate", function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(e) {
var newPosts, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, post, postContainer;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
newPosts = e.detail.newPosts;
_iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
_ctx.prev = 2;
for(_iterator = newPosts[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
post = _step.value;
postContainer = document.getElementById("pc" + post.substring(post.indexOf(".") + 1));
processPost(postContainer);
}
_ctx.next = 10;
break;
case 6:
_ctx.prev = 6;
_ctx.t0 = _ctx["catch"](2);
_didIteratorError = true;
_iteratorError = _ctx.t0;
case 10:
_ctx.prev = 10;
_ctx.prev = 11;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 13:
_ctx.prev = 13;
if (!_didIteratorError) {
_ctx.next = 16;
break;
}
throw _iteratorError;
case 16:
return _ctx.finish(13);
case 17:
return _ctx.finish(10);
case 18:
case "end":
return _ctx.stop();
}
}, _callee, null, [
[
2,
6,
10,
18
],
[
11,
,
13,
17
]
]);
}));
return function(e) {
return _ref.apply(this, arguments);
};
}());
document.addEventListener("QRDialogCreation", function(e) {
var a = document.createElement("span");
new PostOptions({
target: a,
props: {
processors: processors,
textinput: (e.detail || e.target).querySelector("textarea")
}
});
var prevFile;
var target;
var somethingChanged = function() {
var _ref = _asyncToGenerator(regeneratorRuntime$1.mark(function _callee(m) {
var currentFile;
return regeneratorRuntime$1.wrap(function _callee$(_ctx) {
while(1)switch(_ctx.prev = _ctx.next){
case 0:
_ctx.next = 2;
return getSelectedFile();
case 2:
currentFile = _ctx.sent;
if (prevFile != currentFile) {
prevFile = currentFile;
document.dispatchEvent(new CustomEvent("PEEFile", {
detail: prevFile
}));
}
case 4:
case "end":
return _ctx.stop();
}
}, _callee);
}));
return function somethingChanged(m) {
return _ref.apply(this, arguments);
};
}();
var obs = new MutationObserver(somethingChanged);
if (!cappState.is4chanX) {
var ref;
target = e.detail;
a.style.display = "inline-block";
(ref = target.querySelector("input[type=submit]")) === null || ref === void 0 ? void 0 : ref.insertAdjacentElement("beforebegin", a);
var filesinp = target.querySelector("#qrFile");
filesinp.addEventListener("change", somethingChanged);
} else {
var ref1;
target = e.target;
(ref1 = target.querySelector("#qr-filename-container")) === null || ref1 === void 0 ? void 0 : ref1.appendChild(a);
var filesinp1 = target.querySelector("#file-n-submit");
obs.observe(filesinp1, {
attributes: true
});
}
}, {
once: !cappState.is4chanX
}); // 4chan's normal extension destroys the QR form everytime
var customStyles = document.createElement("style");
customStyles.appendChild(document.createTextNode(globalCss));
document.documentElement.insertBefore(customStyles, null);
var meta = document.querySelector('meta[name="referrer"]');
if (meta) {
meta.setAttribute("name", "referrer");
meta.setAttribute("content", "no-referrer");
}
function processAttachments(post, ress) {
if (ress.length == 0) return;
var replyBox = qp.getPost(post);
var external = ress[0][1];
if (external) replyBox === null || replyBox === void 0 ? void 0 : replyBox.classList.add("hasext");
else replyBox === null || replyBox === void 0 ? void 0 : replyBox.classList.add("hasembed");
if (ress.length > 1) replyBox === null || replyBox === void 0 ? void 0 : replyBox.classList.add("hasmultiple");
if (!cappState.foundPosts.includes(replyBox)) cappState.foundPosts.push(replyBox);
appState.set(cappState);
var isCatalog = replyBox === null || replyBox === void 0 ? void 0 : replyBox.classList.contains("catalog-post");
// add buttons
if (!isCatalog) {
var ft = qp.getFileThumbnail(post);
var info = qp.getInfoBox(post);
var quot = qp.getTextBox(post);
var textInsertCursor = document.createElement("div");
quot === null || quot === void 0 ? void 0 : quot.appendChild(textInsertCursor);
var filehost = ft.querySelector(".filehost");
var eyehost = info.querySelector(".eyehost");
var imgcont = filehost || document.createElement("div");
var eyecont = eyehost || document.createElement("span");
if (!filehost) {
ft.append(imgcont);
imgcont.classList.add("fileThumb");
imgcont.classList.add("filehost");
} else {
imgcont.innerHTML = "";
}
if (!eyehost) {
info.append(eyecont);
eyecont.classList.add("eyehost");
} else {
eyecont.innerHTML = "";
}
var id = ~~(Math.random() * 20000000);
new TextEmbeddings({
target: textInsertCursor,
props: {
files: ress.map(function(e) {
return e[0];
}).filter(function(e) {
return Buffer$1.isBuffer(e.data) && e.filename.endsWith(".txt") && e.filename.startsWith("message");
})
}
});
var emb = new Embeddings({
target: imgcont,
props: {
files: ress.map(function(e) {
return e[0];
}),
id: "" + id
}
});
new EyeButton({
target: eyecont,
props: {
files: ress.map(function(e) {
return e[0];
}),
inst: emb,
id: "" + id
}
});
} else {
var opFile = post.querySelector(".catalog-link");
var ahem = opFile === null || opFile === void 0 ? void 0 : opFile.querySelector(".catalog-host");
var imgcont1 = ahem || document.createElement("div");
imgcont1.className = "catalog-host";
if (ahem) {
imgcont1.innerHTML = "";
}
new Embeddings({
target: imgcont1,
props: {
files: ress.map(function(e) {
return e[0];
})
}
});
if (!ahem) opFile === null || opFile === void 0 ? void 0 : opFile.append(imgcont1);
}
post.setAttribute("data-processed", "true");
}
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({});
//# sourceMappingURL=main-es5.js.map