create project

This commit is contained in:
ismailsosic
2022-12-27 12:05:56 +01:00
parent 2a33a2d3de
commit cd2143287c
16035 changed files with 2489703 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
/**
* FNV-1a Hash implementation
* @author Travis Webb (tjwebb) <me@traviswebb.com>
*
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
*
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
* and still making use of Javascript's 53-bit integer space.
*/ export const fnv1a52 = (str)=>{
const len = str.length;
let i = 0, t0 = 0, v0 = 0x2325, t1 = 0, v1 = 0x8422, t2 = 0, v2 = 0x9ce4, t3 = 0, v3 = 0xcbf2;
while(i < len){
v0 ^= str.charCodeAt(i++);
t0 = v0 * 435;
t1 = v1 * 435;
t2 = v2 * 435;
t3 = v3 * 435;
t2 += v0 << 8;
t3 += v1 << 8;
t1 += t0 >>> 16;
v0 = t0 & 65535;
t2 += t1 >>> 16;
v1 = t1 & 65535;
v3 = t3 + (t2 >>> 16) & 65535;
v2 = t2 & 65535;
}
return (v3 & 15) * 281474976710656 + v2 * 4294967296 + v1 * 65536 + (v0 ^ v3 >> 4);
};
export const generateETag = (payload, weak = false)=>{
const prefix = weak ? 'W/"' : '"';
return prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '"';
};
//# sourceMappingURL=etag.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../server/lib/etag.ts"],"names":["fnv1a52","str","len","length","i","t0","v0","t1","v1","t2","v2","t3","v3","charCodeAt","generateETag","payload","weak","prefix","toString"],"mappings":"AAAA;;;;;;;;GAQG,CACH,OAAO,MAAMA,OAAO,GAAG,CAACC,GAAW,GAAK;IACtC,MAAMC,GAAG,GAAGD,GAAG,CAACE,MAAM;IACtB,IAAIC,CAAC,GAAG,CAAC,EACPC,EAAE,GAAG,CAAC,EACNC,EAAE,GAAG,MAAM,EACXC,EAAE,GAAG,CAAC,EACNC,EAAE,GAAG,MAAM,EACXC,EAAE,GAAG,CAAC,EACNC,EAAE,GAAG,MAAM,EACXC,EAAE,GAAG,CAAC,EACNC,EAAE,GAAG,MAAM;IAEb,MAAOR,CAAC,GAAGF,GAAG,CAAE;QACdI,EAAE,IAAIL,GAAG,CAACY,UAAU,CAACT,CAAC,EAAE,CAAC;QACzBC,EAAE,GAAGC,EAAE,GAAG,GAAG;QACbC,EAAE,GAAGC,EAAE,GAAG,GAAG;QACbC,EAAE,GAAGC,EAAE,GAAG,GAAG;QACbC,EAAE,GAAGC,EAAE,GAAG,GAAG;QACbH,EAAE,IAAIH,EAAE,IAAI,CAAC;QACbK,EAAE,IAAIH,EAAE,IAAI,CAAC;QACbD,EAAE,IAAIF,EAAE,KAAK,EAAE;QACfC,EAAE,GAAGD,EAAE,GAAG,KAAK;QACfI,EAAE,IAAIF,EAAE,KAAK,EAAE;QACfC,EAAE,GAAGD,EAAE,GAAG,KAAK;QACfK,EAAE,GAAG,AAACD,EAAE,GAAG,CAACF,EAAE,KAAK,EAAE,CAAC,GAAI,KAAK;QAC/BC,EAAE,GAAGD,EAAE,GAAG,KAAK;KAChB;IAED,OACE,CAACG,EAAE,GAAG,EAAE,CAAC,GAAG,eAAe,GAC3BF,EAAE,GAAG,UAAU,GACfF,EAAE,GAAG,KAAK,GACV,CAACF,EAAE,GAAIM,EAAE,IAAI,CAAC,AAAC,CAAC,CACjB;CACF,CAAA;AAED,OAAO,MAAME,YAAY,GAAG,CAACC,OAAe,EAAEC,IAAI,GAAG,KAAK,GAAK;IAC7D,MAAMC,MAAM,GAAGD,IAAI,GAAG,KAAK,GAAG,GAAG;IACjC,OACEC,MAAM,GAAGjB,OAAO,CAACe,OAAO,CAAC,CAACG,QAAQ,CAAC,EAAE,CAAC,GAAGH,OAAO,CAACZ,MAAM,CAACe,QAAQ,CAAC,EAAE,CAAC,GAAG,GAAG,CAC3E;CACF,CAAA"}

View File

@@ -0,0 +1,48 @@
import { fileExists } from "../../lib/file-exists";
import { getPagePaths } from "../../shared/lib/page-path/get-page-paths";
import { nonNullable } from "../../lib/non-nullable";
import { join, sep, normalize } from "path";
import { promises } from "fs";
import { warn } from "../../build/output/log";
import chalk from "../../lib/chalk";
async function isTrueCasePagePath(pagePath, pagesDir) {
const pageSegments = normalize(pagePath).split(sep).filter(Boolean);
const segmentExistsPromises = pageSegments.map(async (segment, i)=>{
const segmentParentDir = join(pagesDir, ...pageSegments.slice(0, i));
const parentDirEntries = await promises.readdir(segmentParentDir);
return parentDirEntries.includes(segment);
});
return (await Promise.all(segmentExistsPromises)).every(Boolean);
}
/**
* Finds a page file with the given parameters. If the page is duplicated with
* multiple extensions it will throw, otherwise it will return the *relative*
* path to the page file or null if it is not found.
*
* @param pagesDir Absolute path to the pages folder with trailing `/pages`.
* @param normalizedPagePath The page normalized (it will be denormalized).
* @param pageExtensions Array of page extensions.
*/ export async function findPageFile(pagesDir, normalizedPagePath, pageExtensions, isAppDir) {
const pagePaths = getPagePaths(normalizedPagePath, pageExtensions, isAppDir);
const [existingPath, ...others] = (await Promise.all(pagePaths.map(async (path)=>{
const filePath = join(pagesDir, path);
return await fileExists(filePath) ? path : null;
}))).filter(nonNullable);
if (!existingPath) {
return null;
}
if (!await isTrueCasePagePath(existingPath, pagesDir)) {
return null;
}
if (others.length > 0) {
warn(`Duplicate page detected. ${chalk.cyan(join("pages", existingPath))} and ${chalk.cyan(join("pages", others[0]))} both resolve to ${chalk.cyan(normalizedPagePath)}.`);
}
return existingPath;
}
// Determine if the file is leaf node page file under layouts,
// The filename should start with 'page' and end with one of the allowed extensions
export function isLayoutsLeafPage(filePath, pageExtensions) {
return new RegExp(`(^page|[\\\\/]page)\\.(?:${pageExtensions.join("|")})$`).test(filePath);
}
//# sourceMappingURL=find-page-file.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../server/lib/find-page-file.ts"],"names":["fileExists","getPagePaths","nonNullable","join","sep","normalize","promises","warn","chalk","isTrueCasePagePath","pagePath","pagesDir","pageSegments","split","filter","Boolean","segmentExistsPromises","map","segment","i","segmentParentDir","slice","parentDirEntries","readdir","includes","Promise","all","every","findPageFile","normalizedPagePath","pageExtensions","isAppDir","pagePaths","existingPath","others","path","filePath","length","cyan","isLayoutsLeafPage","RegExp","test"],"mappings":"AAAA,SAASA,UAAU,QAAQ,uBAAuB,CAAA;AAClD,SAASC,YAAY,QAAQ,2CAA2C,CAAA;AACxE,SAASC,WAAW,QAAQ,wBAAwB,CAAA;AACpD,SAASC,IAAI,EAAEC,GAAG,EAAEC,SAAS,QAAQ,MAAM,CAAA;AAC3C,SAASC,QAAQ,QAAQ,IAAI,CAAA;AAC7B,SAASC,IAAI,QAAQ,wBAAwB,CAAA;AAC7C,OAAOC,KAAK,MAAM,iBAAiB,CAAA;AAEnC,eAAeC,kBAAkB,CAACC,QAAgB,EAAEC,QAAgB,EAAE;IACpE,MAAMC,YAAY,GAAGP,SAAS,CAACK,QAAQ,CAAC,CAACG,KAAK,CAACT,GAAG,CAAC,CAACU,MAAM,CAACC,OAAO,CAAC;IACnE,MAAMC,qBAAqB,GAAGJ,YAAY,CAACK,GAAG,CAAC,OAAOC,OAAO,EAAEC,CAAC,GAAK;QACnE,MAAMC,gBAAgB,GAAGjB,IAAI,CAACQ,QAAQ,KAAKC,YAAY,CAACS,KAAK,CAAC,CAAC,EAAEF,CAAC,CAAC,CAAC;QACpE,MAAMG,gBAAgB,GAAG,MAAMhB,QAAQ,CAACiB,OAAO,CAACH,gBAAgB,CAAC;QACjE,OAAOE,gBAAgB,CAACE,QAAQ,CAACN,OAAO,CAAC,CAAA;KAC1C,CAAC;IAEF,OAAO,CAAC,MAAMO,OAAO,CAACC,GAAG,CAACV,qBAAqB,CAAC,CAAC,CAACW,KAAK,CAACZ,OAAO,CAAC,CAAA;CACjE;AAED;;;;;;;;GAQG,CACH,OAAO,eAAea,YAAY,CAChCjB,QAAgB,EAChBkB,kBAA0B,EAC1BC,cAAwB,EACxBC,QAAiB,EACO;IACxB,MAAMC,SAAS,GAAG/B,YAAY,CAAC4B,kBAAkB,EAAEC,cA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/compiled/lru-cache";
import { FETCH_CACHE_HEADER } from "../../../client/components/app-router-headers";
let memoryCache;
export default class FetchCache {
constructor(ctx){
if (ctx.maxMemoryCacheSize && !memoryCache) {
memoryCache = new LRUCache({
max: ctx.maxMemoryCacheSize,
length ({ value }) {
var ref;
if (!value) {
return 25;
} else if (value.kind === "REDIRECT") {
return JSON.stringify(value.props).length;
} else if (value.kind === "IMAGE") {
throw new Error("invariant image should not be incremental-cache");
} else if (value.kind === "FETCH") {
return JSON.stringify(value.data || "").length;
}
// rough estimate of size of cache value
return value.html.length + (((ref = JSON.stringify(value.pageData)) == null ? void 0 : ref.length) || 0);
}
});
}
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
this.headers = {};
this.headers["Content-Type"] = "application/json";
if (FETCH_CACHE_HEADER in ctx._requestHeaders) {
const newHeaders = JSON.parse(ctx._requestHeaders[FETCH_CACHE_HEADER]);
for(const k in newHeaders){
this.headers[k] = newHeaders[k];
}
}
this.cacheEndpoint = `https://${ctx._requestHeaders["x-vercel-sc-host"]}${ctx._requestHeaders["x-vercel-sc-basepath"] || ""}`;
if (this.debug) {
console.log("using cache endpoint", this.cacheEndpoint);
}
}
async get(key, fetchCache) {
if (!fetchCache) return null;
let data = memoryCache == null ? void 0 : memoryCache.get(key);
// get data from fetch cache
if (!data) {
try {
const start = Date.now();
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/getItems`, {
method: "POST",
body: JSON.stringify([
key
]),
headers: this.headers
});
if (!res.ok) {
console.error(await res.text());
throw new Error(`invalid response from cache ${res.status}`);
}
const items = await res.json();
const item = items[key];
if (!item || !item.value) {
console.log({
item
});
throw new Error(`invalid item returned`);
}
const cached = JSON.parse(item.value);
if (!cached || cached.kind !== "FETCH") {
this.debug && console.log({
cached
});
throw new Error(`invalid cache value`);
}
data = {
lastModified: Date.now() - item.age * 1000,
value: cached
};
if (this.debug) {
console.log("got fetch cache entry duration:", Date.now() - start, data);
}
if (data) {
memoryCache == null ? void 0 : memoryCache.set(key, data);
}
} catch (err) {
// unable to get data from fetch-cache
console.error(`Failed to get from fetch-cache`, err);
}
}
return data || null;
}
async set(key, data, fetchCache) {
if (!fetchCache) return;
memoryCache == null ? void 0 : memoryCache.set(key, {
value: data,
lastModified: Date.now()
});
try {
const start = Date.now();
const body = JSON.stringify([
{
id: key,
value: JSON.stringify(data)
},
]);
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/setItems`, {
method: "POST",
headers: this.headers,
body: body
});
if (!res.ok) {
this.debug && console.log(await res.text());
throw new Error(`invalid response ${res.status}`);
}
if (this.debug) {
console.log("successfully set to fetch-cache duration:", Date.now() - start, body);
}
} catch (err) {
// unable to set to fetch-cache
console.error(`Failed to update fetch cache`, err);
}
return;
}
};
//# sourceMappingURL=fetch-cache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,130 @@
import LRUCache from "next/dist/compiled/lru-cache";
import path from "../../../shared/lib/isomorphic/path";
let memoryCache;
export default class FileSystemCache {
constructor(ctx){
this.fs = ctx.fs;
this.flushToDisk = ctx.flushToDisk;
this.serverDistDir = ctx.serverDistDir;
this.appDir = !!ctx._appDir;
if (ctx.maxMemoryCacheSize && !memoryCache) {
memoryCache = new LRUCache({
max: ctx.maxMemoryCacheSize,
length ({ value }) {
var ref;
if (!value) {
return 25;
} else if (value.kind === "REDIRECT") {
return JSON.stringify(value.props).length;
} else if (value.kind === "IMAGE") {
throw new Error("invariant image should not be incremental-cache");
} else if (value.kind === "FETCH") {
return JSON.stringify(value.data || "").length;
}
// rough estimate of size of cache value
return value.html.length + (((ref = JSON.stringify(value.pageData)) == null ? void 0 : ref.length) || 0);
}
});
}
}
async get(key, fetchCache) {
let data = memoryCache == null ? void 0 : memoryCache.get(key);
// let's check the disk for seed data
if (!data) {
try {
const { filePath , isAppPath } = await this.getFsPath({
pathname: fetchCache ? key : `${key}.html`,
fetchCache
});
const fileData = await this.fs.readFile(filePath);
const { mtime } = await this.fs.stat(filePath);
if (fetchCache) {
const lastModified = mtime.getTime();
data = {
lastModified,
value: JSON.parse(fileData)
};
} else {
const pageData = isAppPath ? await this.fs.readFile((await this.getFsPath({
pathname: `${key}.rsc`,
appDir: true
})).filePath) : JSON.parse(await this.fs.readFile(await (await this.getFsPath({
pathname: `${key}.json`,
appDir: false
})).filePath));
data = {
lastModified: mtime.getTime(),
value: {
kind: "PAGE",
html: fileData,
pageData
}
};
}
if (data) {
memoryCache == null ? void 0 : memoryCache.set(key, data);
}
} catch (_) {
// unable to get data from disk
}
}
return data || null;
}
async set(key, data) {
memoryCache == null ? void 0 : memoryCache.set(key, {
value: data,
lastModified: Date.now()
});
if (!this.flushToDisk) return;
if ((data == null ? void 0 : data.kind) === "PAGE") {
const isAppPath = typeof data.pageData === "string";
const { filePath: htmlPath } = await this.getFsPath({
pathname: `${key}.html`,
appDir: isAppPath
});
await this.fs.mkdir(path.dirname(htmlPath));
await this.fs.writeFile(htmlPath, data.html);
await this.fs.writeFile((await this.getFsPath({
pathname: `${key}.${isAppPath ? "rsc" : "json"}`,
appDir: isAppPath
})).filePath, isAppPath ? data.pageData : JSON.stringify(data.pageData));
} else if ((data == null ? void 0 : data.kind) === "FETCH") {
const { filePath } = await this.getFsPath({
pathname: key,
fetchCache: true
});
await this.fs.mkdir(path.dirname(filePath));
await this.fs.writeFile(filePath, JSON.stringify(data));
}
}
async getFsPath({ pathname , appDir , fetchCache }) {
if (fetchCache) {
// we store in .next/cache/fetch-cache so it can be persisted
// across deploys
return {
filePath: path.join(this.serverDistDir, "..", "cache", "fetch-cache", pathname),
isAppPath: false
};
}
let isAppPath = false;
let filePath = path.join(this.serverDistDir, "pages", pathname);
if (!this.appDir || appDir === false) return {
filePath,
isAppPath
};
try {
await this.fs.readFile(filePath);
return {
filePath,
isAppPath
};
} catch (err) {
return {
filePath: path.join(this.serverDistDir, "app", pathname),
isAppPath: true
};
}
}
};
//# sourceMappingURL=file-system-cache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,161 @@
import FileSystemCache from "./file-system-cache";
import path from "../../../shared/lib/isomorphic/path";
import { normalizePagePath } from "../../../shared/lib/page-path/normalize-page-path";
import FetchCache from "./fetch-cache";
function toRoute(pathname) {
return pathname.replace(/\/$/, "").replace(/\/index$/, "") || "/";
}
export class CacheHandler {
// eslint-disable-next-line
constructor(_ctx){}
async get(_key, _fetchCache) {
return {};
}
async set(_key, _data, _fetchCache) {}
}
export class IncrementalCache {
constructor({ fs , dev , appDir , flushToDisk , fetchCache , minimalMode , serverDistDir , requestHeaders , maxMemoryCacheSize , getPrerenderManifest , incrementalCacheHandlerPath }){
let cacheHandlerMod = FileSystemCache;
if (process.env.NEXT_RUNTIME !== "edge" && incrementalCacheHandlerPath) {
cacheHandlerMod = require(incrementalCacheHandlerPath);
cacheHandlerMod = cacheHandlerMod.default || cacheHandlerMod;
}
if (minimalMode && fetchCache) {
cacheHandlerMod = FetchCache;
}
if (process.env.__NEXT_TEST_MAX_ISR_CACHE) {
// Allow cache size to be overridden for testing purposes
maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10);
}
this.dev = dev;
this.minimalMode = minimalMode;
this.requestHeaders = requestHeaders;
this.prerenderManifest = getPrerenderManifest();
this.cacheHandler = new cacheHandlerMod({
dev,
fs,
flushToDisk,
serverDistDir,
maxMemoryCacheSize,
_appDir: !!appDir,
_requestHeaders: requestHeaders
});
}
calculateRevalidate(pathname, fromTime) {
// in development we don't have a prerender-manifest
// and default to always revalidating to allow easier debugging
if (this.dev) return new Date().getTime() - 1000;
// if an entry isn't present in routes we fallback to a default
// of revalidating after 1 second
const { initialRevalidateSeconds } = this.prerenderManifest.routes[toRoute(pathname)] || {
initialRevalidateSeconds: 1
};
const revalidateAfter = typeof initialRevalidateSeconds === "number" ? initialRevalidateSeconds * 1000 + fromTime : initialRevalidateSeconds;
return revalidateAfter;
}
_getPathname(pathname, fetchCache) {
return fetchCache ? pathname : normalizePagePath(pathname);
}
// x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
async fetchCacheKey(url, init = {}) {
const cacheString = JSON.stringify([
url,
init.method,
init.headers,
init.mode,
init.redirect,
init.credentials,
init.referrer,
init.referrerPolicy,
init.integrity,
init.next,
init.cache,
]);
let cacheKey;
if (process.env.NEXT_RUNTIME === "edge") {
function bufferToHex(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), (b)=>b.toString(16).padStart(2, "0")).join("");
}
const buffer1 = new TextEncoder().encode(cacheString);
cacheKey = bufferToHex(await crypto.subtle.digest("SHA-256", buffer1));
} else {
const crypto = require("crypto");
cacheKey = crypto.createHash("sha256").update(cacheString).digest("hex");
}
return cacheKey;
}
// get data from cache if available
async get(pathname, fetchCache) {
var ref, ref1;
// we don't leverage the prerender cache in dev mode
// so that getStaticProps is always called for easier debugging
if (this.dev) return null;
pathname = this._getPathname(pathname, fetchCache);
let entry = null;
const cacheData = await this.cacheHandler.get(pathname, fetchCache);
if ((cacheData == null ? void 0 : (ref = cacheData.value) == null ? void 0 : ref.kind) === "FETCH") {
const data = cacheData.value.data;
const age = Math.round((Date.now() - (cacheData.lastModified || 0)) / 1000);
const revalidate = cacheData.value.revalidate;
return {
isStale: age > revalidate,
value: {
kind: "FETCH",
data,
age,
revalidate,
isStale: age > revalidate
},
revalidateAfter: (cacheData.lastModified || Date.now()) + revalidate * 1000
};
}
const curRevalidate = (ref1 = this.prerenderManifest.routes[toRoute(pathname)]) == null ? void 0 : ref1.initialRevalidateSeconds;
const revalidateAfter = this.calculateRevalidate(pathname, (cacheData == null ? void 0 : cacheData.lastModified) || Date.now());
const isStale = revalidateAfter !== false && revalidateAfter < Date.now() ? true : undefined;
if (cacheData) {
entry = {
isStale,
curRevalidate,
revalidateAfter,
value: cacheData.value
};
}
if (!cacheData && this.prerenderManifest.notFoundRoutes.includes(pathname)) {
// for the first hit after starting the server the cache
// may not have a way to save notFound: true so if
// the prerender-manifest marks this as notFound then we
// return that entry and trigger a cache set to give it a
// chance to update in-memory entries
entry = {
isStale,
value: null,
curRevalidate,
revalidateAfter
};
this.set(pathname, entry.value, curRevalidate, fetchCache);
}
return entry;
}
// populate the incremental cache with new data
async set(pathname, data, revalidateSeconds, fetchCache) {
if (this.dev) return;
pathname = this._getPathname(pathname, fetchCache);
try {
// we use the prerender manifest memory instance
// to store revalidate timings for calculating
// revalidateAfter values so we update this on set
if (typeof revalidateSeconds !== "undefined" && !fetchCache) {
this.prerenderManifest.routes[pathname] = {
dataRoute: path.posix.join("/_next/data", `${normalizePagePath(pathname)}.json`),
srcRoute: null,
initialRevalidateSeconds: revalidateSeconds
};
}
await this.cacheHandler.set(pathname, data, fetchCache);
} catch (error) {
console.warn("Failed to update prerender cache for", pathname, error);
}
}
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
import Stream from "stream";
export function mockRequest(requestUrl, requestHeaders, requestMethod, requestConnection) {
const resBuffers = [];
const mockRes = new Stream.Writable();
const isStreamFinished = new Promise(function(resolve, reject) {
mockRes.on("finish", ()=>resolve(true));
mockRes.on("end", ()=>resolve(true));
mockRes.on("error", (err)=>reject(err));
});
mockRes.write = (chunk)=>{
resBuffers.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
};
mockRes._write = (chunk, _encoding, callback)=>{
mockRes.write(chunk);
// According to Node.js documentation, the callback MUST be invoked to signal that
// the write completed successfully. If this callback is not invoked, the 'finish' event
// will not be emitted.
// https://nodejs.org/docs/latest-v16.x/api/stream.html#writable_writechunk-encoding-callback
callback();
};
const mockHeaders = {};
mockRes.writeHead = (_status, _headers)=>Object.assign(mockHeaders, _headers);
mockRes.getHeader = (name)=>mockHeaders[name.toLowerCase()];
mockRes.getHeaders = ()=>mockHeaders;
mockRes.getHeaderNames = ()=>Object.keys(mockHeaders);
mockRes.setHeader = (name, value)=>mockHeaders[name.toLowerCase()] = value;
mockRes.removeHeader = (name)=>{
delete mockHeaders[name.toLowerCase()];
};
mockRes._implicitHeader = ()=>{};
mockRes.connection = requestConnection;
mockRes.finished = false;
mockRes.statusCode = 200;
const mockReq = new Stream.Readable();
mockReq._read = ()=>{
mockReq.emit("end");
mockReq.emit("close");
return Buffer.from("");
};
mockReq.headers = requestHeaders;
mockReq.method = requestMethod;
mockReq.url = requestUrl;
mockReq.connection = requestConnection;
return {
resBuffers,
req: mockReq,
res: mockRes,
streamPromise: isStreamFinished
};
}
//# sourceMappingURL=mock-request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../server/lib/mock-request.ts"],"names":["Stream","mockRequest","requestUrl","requestHeaders","requestMethod","requestConnection","resBuffers","mockRes","Writable","isStreamFinished","Promise","resolve","reject","on","err","write","chunk","push","Buffer","isBuffer","from","_write","_encoding","callback","mockHeaders","writeHead","_status","_headers","Object","assign","getHeader","name","toLowerCase","getHeaders","getHeaderNames","keys","setHeader","value","removeHeader","_implicitHeader","connection","finished","statusCode","mockReq","Readable","_read","emit","headers","method","url","req","res","streamPromise"],"mappings":"AAAA,OAAOA,MAAM,MAAM,QAAQ,CAAA;AAE3B,OAAO,SAASC,WAAW,CACzBC,UAAkB,EAClBC,cAA6D,EAC7DC,aAAqB,EACrBC,iBAAuB,EACvB;IACA,MAAMC,UAAU,GAAa,EAAE;IAC/B,MAAMC,OAAO,GAAQ,IAAIP,MAAM,CAACQ,QAAQ,EAAE;IAE1C,MAAMC,gBAAgB,GAAG,IAAIC,OAAO,CAAC,SAAUC,OAAO,EAAEC,MAAM,EAAE;QAC9DL,OAAO,CAACM,EAAE,CAAC,QAAQ,EAAE,IAAMF,OAAO,CAAC,IAAI,CAAC,CAAC;QACzCJ,OAAO,CAACM,EAAE,CAAC,KAAK,EAAE,IAAMF,OAAO,CAAC,IAAI,CAAC,CAAC;QACtCJ,OAAO,CAACM,EAAE,CAAC,OAAO,EAAE,CAACC,GAAQ,GAAKF,MAAM,CAACE,GAAG,CAAC,CAAC;KAC/C,CAAC;IAEFP,OAAO,CA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E1CD,OAAO,CAACE,KAAK,GAAG,IAAM;QACpBF,OAAO,CAACG,IAAI,CAAC,KAAK,CAAC;QACnBH,OAAO,CAACG,IAAI,CAAC,OAAO,CAAC;QACrB,OAAO5B,MAAM,CAACE,IAAI,CAAC,EAAE,CAAC,CAAA;KACvB;IAEDuB,OAAO,CAACI,OAAO,GAAG5C,cAAc;IAChCwC,OAAO,CAACK,MAAM,GAAG5C,aAAa;IAC9BuC,OAAO,CAACM,GAAG,GAAG/C,UAAU;IACxByC,OAAO,CAACH,UAAU,GAAGnC,iBAAiB;IAEtC,OAAO;QACLC,UAAU;QACV4C,GAAG,EAAEP,OAAO;QACZQ,GAAG,EAAE5C,OAAO;QACZ6C,aAAa,EAAE3C,gBAAgB;KAChC,CAAA;CACF"}

View File

@@ -0,0 +1,20 @@
import fs from "fs";
import { join } from "path";
/**
* Recursively read directory
* Returns array holding all relative paths
*/ export function recursiveReadDirSync(/** The directory to read */ dir, /** This doesn't have to be provided, it's used for the recursion */ arr = [], /** Used to replace the initial path, only the relative path is left, it's faster than path.relative. */ rootDir = dir) {
const result = fs.readdirSync(dir);
result.forEach((part)=>{
const absolutePath = join(dir, part);
const pathStat = fs.statSync(absolutePath);
if (pathStat.isDirectory()) {
recursiveReadDirSync(absolutePath, arr, rootDir);
return;
}
arr.push(absolutePath.replace(rootDir, ""));
});
return arr;
}
//# sourceMappingURL=recursive-readdir-sync.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../server/lib/recursive-readdir-sync.ts"],"names":["fs","join","recursiveReadDirSync","dir","arr","rootDir","result","readdirSync","forEach","part","absolutePath","pathStat","statSync","isDirectory","push","replace"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,SAASC,IAAI,QAAQ,MAAM,CAAA;AAE3B;;;GAGG,CACH,OAAO,SAASC,oBAAoB,CAClC,4BAA4B,CAC5BC,GAAW,EACX,oEAAoE,CACpEC,GAAa,GAAG,EAAE,EAClB,wGAAwG,CACxGC,OAAO,GAAGF,GAAG,EACH;IACV,MAAMG,MAAM,GAAGN,EAAE,CAACO,WAAW,CAACJ,GAAG,CAAC;IAElCG,MAAM,CAACE,OAAO,CAAC,CAACC,IAAY,GAAK;QAC/B,MAAMC,YAAY,GAAGT,IAAI,CAACE,GAAG,EAAEM,IAAI,CAAC;QACpC,MAAME,QAAQ,GAAGX,EAAE,CAACY,QAAQ,CAACF,YAAY,CAAC;QAE1C,IAAIC,QAAQ,CAACE,WAAW,EAAE,EAAE;YAC1BX,oBAAoB,CAACQ,YAAY,EAAEN,GAAG,EAAEC,OAAO,CAAC;YAChD,OAAM;SACP;QACDD,GAAG,CAACU,IAAI,CAACJ,YAAY,CAACK,OAAO,CAACV,OAAO,EAAE,EAAE,CAAC,CAAC;KAC5C,CAAC;IAEF,OAAOD,GAAG,CAAA;CACX"}

View File

@@ -0,0 +1,32 @@
// eslint-disable-next-line no-shadow
export const enum AVIFTune {
auto,
psnr,
ssim,
}
export interface EncodeOptions {
cqLevel: number
denoiseLevel: number
cqAlphaLevel: number
tileRowsLog2: number
tileColsLog2: number
speed: number
subsample: number
chromaDeltaQ: boolean
sharpness: number
tune: AVIFTune
}
export interface AVIFModule extends EmscriptenWasm.Module {
encode(
data: BufferSource,
width: number,
height: number,
options: EncodeOptions
): Uint8Array
}
declare var moduleFactory: EmscriptenWasm.ModuleFactory<AVIFModule>
export default moduleFactory

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,272 @@
import { promises as fsp } from "fs";
import * as path from "path";
import { instantiateEmscriptenWasm, pathify } from "./emscripten-utils.js";
// @ts-ignore
import mozEnc from "./mozjpeg/mozjpeg_node_enc.js";
const mozEncWasm = path.resolve(__dirname, "./mozjpeg/mozjpeg_node_enc.wasm");
// @ts-ignore
import mozDec from "./mozjpeg/mozjpeg_node_dec.js";
const mozDecWasm = path.resolve(__dirname, "./mozjpeg/mozjpeg_node_dec.wasm");
// @ts-ignore
import webpEnc from "./webp/webp_node_enc.js";
const webpEncWasm = path.resolve(__dirname, "./webp/webp_node_enc.wasm");
// @ts-ignore
import webpDec from "./webp/webp_node_dec.js";
const webpDecWasm = path.resolve(__dirname, "./webp/webp_node_dec.wasm");
// @ts-ignore
import avifEnc from "./avif/avif_node_enc.js";
const avifEncWasm = path.resolve(__dirname, "./avif/avif_node_enc.wasm");
// @ts-ignore
import avifDec from "./avif/avif_node_dec.js";
const avifDecWasm = path.resolve(__dirname, "./avif/avif_node_dec.wasm");
// PNG
// @ts-ignore
import * as pngEncDec from "./png/squoosh_png.js";
const pngEncDecWasm = path.resolve(__dirname, "./png/squoosh_png_bg.wasm");
const pngEncDecInit = ()=>pngEncDec.default(fsp.readFile(pathify(pngEncDecWasm)));
// OxiPNG
// @ts-ignore
import * as oxipng from "./png/squoosh_oxipng.js";
const oxipngWasm = path.resolve(__dirname, "./png/squoosh_oxipng_bg.wasm");
const oxipngInit = ()=>oxipng.default(fsp.readFile(pathify(oxipngWasm)));
// Resize
// @ts-ignore
import * as resize from "./resize/squoosh_resize.js";
const resizeWasm = path.resolve(__dirname, "./resize/squoosh_resize_bg.wasm");
const resizeInit = ()=>resize.default(fsp.readFile(pathify(resizeWasm)));
// rotate
const rotateWasm = path.resolve(__dirname, "./rotate/rotate.wasm");
// Our decoders currently rely on a `ImageData` global.
import ImageData from "./image_data";
globalThis.ImageData = ImageData;
function resizeNameToIndex(name) {
switch(name){
case "triangle":
return 0;
case "catrom":
return 1;
case "mitchell":
return 2;
case "lanczos3":
return 3;
default:
throw Error(`Unknown resize algorithm "${name}"`);
}
}
function resizeWithAspect({ input_width , input_height , target_width , target_height }) {
if (!target_width && !target_height) {
throw Error("Need to specify at least width or height when resizing");
}
if (target_width && target_height) {
return {
width: target_width,
height: target_height
};
}
if (!target_width) {
return {
width: Math.round(input_width / input_height * target_height),
height: target_height
};
}
return {
width: target_width,
height: Math.round(input_height / input_width * target_width)
};
}
export const preprocessors = {
resize: {
name: "Resize",
description: "Resize the image before compressing",
instantiate: async ()=>{
await resizeInit();
return (buffer, input_width, input_height, { width , height , method , premultiply , linearRGB })=>{
({ width , height } = resizeWithAspect({
input_width,
input_height,
target_width: width,
target_height: height
}));
const imageData = new ImageData(resize.resize(buffer, input_width, input_height, width, height, resizeNameToIndex(method), premultiply, linearRGB), width, height);
resize.cleanup();
return imageData;
};
},
defaultOptions: {
method: "lanczos3",
fitMethod: "stretch",
premultiply: true,
linearRGB: true
}
},
rotate: {
name: "Rotate",
description: "Rotate image",
instantiate: async ()=>{
return async (buffer, width, height, { numRotations })=>{
const degrees = numRotations * 90 % 360;
const sameDimensions = degrees === 0 || degrees === 180;
const size = width * height * 4;
const instance = (await WebAssembly.instantiate(await fsp.readFile(pathify(rotateWasm)))).instance;
const { memory } = instance.exports;
const additionalPagesNeeded = Math.ceil((size * 2 - memory.buffer.byteLength + 8) / (64 * 1024));
if (additionalPagesNeeded > 0) {
memory.grow(additionalPagesNeeded);
}
const view = new Uint8ClampedArray(memory.buffer);
view.set(buffer, 8);
instance.exports.rotate(width, height, degrees);
return new ImageData(view.slice(size + 8, size * 2 + 8), sameDimensions ? width : height, sameDimensions ? height : width);
};
},
defaultOptions: {
numRotations: 0
}
}
};
export const codecs = {
mozjpeg: {
name: "MozJPEG",
extension: "jpg",
detectors: [
/^\xFF\xD8\xFF/
],
dec: ()=>instantiateEmscriptenWasm(mozDec, mozDecWasm),
enc: ()=>instantiateEmscriptenWasm(mozEnc, mozEncWasm),
defaultEncoderOptions: {
quality: 75,
baseline: false,
arithmetic: false,
progressive: true,
optimize_coding: true,
smoothing: 0,
color_space: 3 /*YCbCr*/ ,
quant_table: 3,
trellis_multipass: false,
trellis_opt_zero: false,
trellis_opt_table: false,
trellis_loops: 1,
auto_subsample: true,
chroma_subsample: 2,
separate_chroma_quality: false,
chroma_quality: 75
},
autoOptimize: {
option: "quality",
min: 0,
max: 100
}
},
webp: {
name: "WebP",
extension: "webp",
detectors: [
/^RIFF....WEBPVP8[LX ]/s
],
dec: ()=>instantiateEmscriptenWasm(webpDec, webpDecWasm),
enc: ()=>instantiateEmscriptenWasm(webpEnc, webpEncWasm),
defaultEncoderOptions: {
quality: 75,
target_size: 0,
target_PSNR: 0,
method: 4,
sns_strength: 50,
filter_strength: 60,
filter_sharpness: 0,
filter_type: 1,
partitions: 0,
segments: 4,
pass: 1,
show_compressed: 0,
preprocessing: 0,
autofilter: 0,
partition_limit: 0,
alpha_compression: 1,
alpha_filtering: 1,
alpha_quality: 100,
lossless: 0,
exact: 0,
image_hint: 0,
emulate_jpeg_size: 0,
thread_level: 0,
low_memory: 0,
near_lossless: 100,
use_delta_palette: 0,
use_sharp_yuv: 0
},
autoOptimize: {
option: "quality",
min: 0,
max: 100
}
},
avif: {
name: "AVIF",
extension: "avif",
// eslint-disable-next-line no-control-regex
detectors: [
/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/
],
dec: ()=>instantiateEmscriptenWasm(avifDec, avifDecWasm),
enc: async ()=>{
return instantiateEmscriptenWasm(avifEnc, avifEncWasm);
},
defaultEncoderOptions: {
cqLevel: 33,
cqAlphaLevel: -1,
denoiseLevel: 0,
tileColsLog2: 0,
tileRowsLog2: 0,
speed: 6,
subsample: 1,
chromaDeltaQ: false,
sharpness: 0,
tune: 0 /* AVIFTune.auto */
},
autoOptimize: {
option: "cqLevel",
min: 62,
max: 0
}
},
oxipng: {
name: "OxiPNG",
extension: "png",
// eslint-disable-next-line no-control-regex
detectors: [
/^\x89PNG\x0D\x0A\x1A\x0A/
],
dec: async ()=>{
await pngEncDecInit();
return {
decode: (buffer)=>{
const imageData = pngEncDec.decode(buffer);
pngEncDec.cleanup();
return imageData;
}
};
},
enc: async ()=>{
await pngEncDecInit();
await oxipngInit();
return {
encode: (buffer, width, height, opts)=>{
const simplePng = pngEncDec.encode(new Uint8Array(buffer), width, height);
const imageData = oxipng.optimise(simplePng, opts.level, false);
oxipng.cleanup();
return imageData;
}
};
},
defaultEncoderOptions: {
level: 2
},
autoOptimize: {
option: "level",
min: 6,
max: 1
}
}
};
//# sourceMappingURL=codecs.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,121 @@
// These types roughly model the object that the JS files generated by Emscripten define. Copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/emscripten/index.d.ts and turned into a type definition rather than a global to support our way of using Emscripten.
declare namespace EmscriptenWasm {
type ModuleFactory<T extends Module = Module> = (
moduleOverrides?: ModuleOpts
) => Promise<T>
type EnvironmentType = 'WEB' | 'NODE' | 'SHELL' | 'WORKER'
// Options object for modularized Emscripten files. Shoe-horned by @surma.
// FIXME: This an incomplete definition!
interface ModuleOpts {
mainScriptUrlOrBlob?: string
noInitialRun?: boolean
locateFile?: (url: string) => string
onRuntimeInitialized?: () => void
}
interface Module {
print(str: string): void
printErr(str: string): void
arguments: string[]
environment: EnvironmentType
preInit: { (): void }[]
preRun: { (): void }[]
postRun: { (): void }[]
preinitializedWebGLContext: WebGLRenderingContext
noInitialRun: boolean
noExitRuntime: boolean
logReadFiles: boolean
filePackagePrefixURL: string
wasmBinary: ArrayBuffer
destroy(object: object): void
getPreloadedPackage(
remotePackageName: string,
remotePackageSize: number
): ArrayBuffer
instantiateWasm(
imports: WebAssembly.Imports,
successCallback: (module: WebAssembly.Module) => void
): WebAssembly.Exports
locateFile(url: string): string
onCustomMessage(event: MessageEvent): void
Runtime: any
ccall(
ident: string,
returnType: string | null,
argTypes: string[],
args: any[]
): any
cwrap(ident: string, returnType: string | null, argTypes: string[]): any
setValue(ptr: number, value: any, type: string, noSafe?: boolean): void
getValue(ptr: number, type: string, noSafe?: boolean): number
ALLOC_NORMAL: number
ALLOC_STACK: number
ALLOC_STATIC: number
ALLOC_DYNAMIC: number
ALLOC_NONE: number
allocate(slab: any, types: string, allocator: number, ptr: number): number
allocate(slab: any, types: string[], allocator: number, ptr: number): number
Pointer_stringify(ptr: number, length?: number): string
UTF16ToString(ptr: number): string
stringToUTF16(str: string, outPtr: number): void
UTF32ToString(ptr: number): string
stringToUTF32(str: string, outPtr: number): void
// USE_TYPED_ARRAYS == 1
HEAP: Int32Array
IHEAP: Int32Array
FHEAP: Float64Array
// USE_TYPED_ARRAYS == 2
HEAP8: Int8Array
HEAP16: Int16Array
HEAP32: Int32Array
HEAPU8: Uint8Array
HEAPU16: Uint16Array
HEAPU32: Uint32Array
HEAPF32: Float32Array
HEAPF64: Float64Array
TOTAL_STACK: number
TOTAL_MEMORY: number
FAST_MEMORY: number
addOnPreRun(cb: () => any): void
addOnInit(cb: () => any): void
addOnPreMain(cb: () => any): void
addOnExit(cb: () => any): void
addOnPostRun(cb: () => any): void
// Tools
intArrayFromString(
stringy: string,
dontAddNull?: boolean,
length?: number
): number[]
intArrayToString(array: number[]): string
writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void
writeArrayToMemory(array: number[], buffer: number): void
writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void
addRunDependency(id: any): void
removeRunDependency(id: any): void
preloadedImages: any
preloadedAudios: any
_malloc(size: number): number
_free(ptr: number): void
// Augmentations below by @surma.
onRuntimeInitialized: () => void | null
}
}

View File

@@ -0,0 +1,22 @@
import { fileURLToPath } from "url";
export function pathify(path) {
if (path.startsWith("file://")) {
path = fileURLToPath(path);
}
return path;
}
export function instantiateEmscriptenWasm(factory, path, workerJS = "") {
return factory({
locateFile (requestPath) {
// The glue code generated by emscripten uses the original
// file names of the worker file and the wasm binary.
// These will have changed in the bundling process and
// we need to inject them here.
if (requestPath.endsWith(".wasm")) return pathify(path);
if (requestPath.endsWith(".worker.js")) return pathify(workerJS);
return requestPath;
}
});
}
//# sourceMappingURL=emscripten-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../server/lib/squoosh/emscripten-utils.ts"],"names":["fileURLToPath","pathify","path","startsWith","instantiateEmscriptenWasm","factory","workerJS","locateFile","requestPath","endsWith"],"mappings":"AAAA,SAASA,aAAa,QAAQ,KAAK,CAAA;AAEnC,OAAO,SAASC,OAAO,CAACC,IAAY,EAAU;IAC5C,IAAIA,IAAI,CAACC,UAAU,CAAC,SAAS,CAAC,EAAE;QAC9BD,IAAI,GAAGF,aAAa,CAACE,IAAI,CAAC;KAC3B;IACD,OAAOA,IAAI,CAAA;CACZ;AAED,OAAO,SAASE,yBAAyB,CACvCC,OAAwC,EACxCH,IAAY,EACZI,QAAgB,GAAG,EAAE,EACT;IACZ,OAAOD,OAAO,CAAC;QACbE,UAAU,EAACC,WAAW,EAAE;YACtB,0DAA0D;YAC1D,qDAAqD;YACrD,sDAAsD;YACtD,+BAA+B;YAC/B,IAAIA,WAAW,CAACC,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAOR,OAAO,CAACC,IAAI,CAAC,CAAA;YACvD,IAAIM,WAAW,CAACC,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAOR,OAAO,CAACK,QAAQ,CAAC,CAAA;YAChE,OAAOE,WAAW,CAAA;SACnB;KACF,CAAC,CAAA;CACH"}

View File

@@ -0,0 +1,21 @@
export default class ImageData {
static from(input) {
return new ImageData(input.data || input._data, input.width, input.height);
}
get data() {
if (Object.prototype.toString.call(this._data) === "[object Object]") {
return Buffer.from(Object.values(this._data));
}
if (this._data instanceof Buffer || this._data instanceof Uint8Array || this._data instanceof Uint8ClampedArray) {
return Buffer.from(this._data);
}
throw new Error("invariant");
}
constructor(data, width, height){
this._data = data;
this.width = width;
this.height = height;
}
};
//# sourceMappingURL=image_data.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../server/lib/squoosh/image_data.ts"],"names":["ImageData","from","input","data","_data","width","height","Object","prototype","toString","call","Buffer","values","Uint8Array","Uint8ClampedArray","Error","constructor"],"mappings":"AAAA,eAAe,MAAMA,SAAS;IAC5B,OAAOC,IAAI,CAACC,KAAgB,EAAa;QACvC,OAAO,IAAIF,SAAS,CAACE,KAAK,CAACC,IAAI,IAAID,KAAK,CAACE,KAAK,EAAEF,KAAK,CAACG,KAAK,EAAEH,KAAK,CAACI,MAAM,CAAC,CAAA;KAC3E;IAMD,IAAIH,IAAI,GAAW;QACjB,IAAII,MAAM,CAACC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAAC,IAAI,CAACN,KAAK,CAAC,KAAK,iBAAiB,EAAE;YACpE,OAAOO,MAAM,CAACV,IAAI,CAACM,MAAM,CAACK,MAAM,CAAC,IAAI,CAACR,KAAK,CAAC,CAAC,CAAA;SAC9C;QACD,IACE,IAAI,CAACA,KAAK,YAAYO,MAAM,IAC5B,IAAI,CAACP,KAAK,YAAYS,UAAU,IAChC,IAAI,CAACT,KAAK,YAAYU,iBAAiB,EACvC;YACA,OAAOH,MAAM,CAACV,IAAI,CAAC,IAAI,CAACG,KAAK,CAAC,CAAA;SAC/B;QACD,MAAM,IAAIW,KAAK,CAAC,WAAW,CAAC,CAAA;KAC7B;IAEDC,YACEb,IAA6C,EAC7CE,KAAa,EACbC,MAAc,CACd;QACA,IAAI,CAACF,KAAK,GAAGD,IAAI;QACjB,IAAI,CAACE,KAAK,GAAGA,KAAK;QAClB,IAAI,CAACC,MAAM,GAAGA,MAAM;KACrB;CACF,CAAA"}

View File

@@ -0,0 +1,105 @@
import semver from "next/dist/compiled/semver";
import { codecs as supportedFormats, preprocessors } from "./codecs";
import ImageData from "./image_data";
// Fixed in Node.js 16.5.0 and newer.
// See https://github.com/nodejs/node/pull/39337
// Eventually, remove this delay when engines is updated.
// See https://github.com/vercel/next.js/blob/1bcc923439f495a1717421e06af7e64c6003072c/packages/next/package.json#L249-L251
const FIXED_VERSION = "16.5.0";
const DELAY_MS = 1000;
let _promise;
function delayOnce(ms) {
if (!_promise) {
_promise = new Promise((resolve)=>{
setTimeout(resolve, ms);
});
}
return _promise;
}
function maybeDelay() {
const isAppleM1 = process.arch === "arm64" && process.platform === "darwin";
if (isAppleM1 && semver.lt(process.version, FIXED_VERSION)) {
return delayOnce(DELAY_MS);
}
return Promise.resolve();
}
export async function decodeBuffer(_buffer) {
var ref;
const buffer = Buffer.from(_buffer);
const firstChunk = buffer.slice(0, 16);
const firstChunkString = Array.from(firstChunk).map((v)=>String.fromCodePoint(v)).join("");
const key = (ref = Object.entries(supportedFormats).find(([, { detectors }])=>detectors.some((detector)=>detector.exec(firstChunkString)))) == null ? void 0 : ref[0];
if (!key) {
throw Error(`Buffer has an unsupported format`);
}
const encoder = supportedFormats[key];
const mod = await encoder.dec();
const rgba = mod.decode(new Uint8Array(buffer));
return rgba;
}
export async function rotate(image, numRotations) {
image = ImageData.from(image);
const m = await preprocessors["rotate"].instantiate();
return await m(image.data, image.width, image.height, {
numRotations
});
}
export async function resize({ image , width , height }) {
image = ImageData.from(image);
const p = preprocessors["resize"];
const m = await p.instantiate();
await maybeDelay();
return await m(image.data, image.width, image.height, {
...p.defaultOptions,
width,
height
});
}
export async function encodeJpeg(image, { quality }) {
image = ImageData.from(image);
const e = supportedFormats["mozjpeg"];
const m = await e.enc();
await maybeDelay();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality
});
return Buffer.from(r);
}
export async function encodeWebp(image, { quality }) {
image = ImageData.from(image);
const e = supportedFormats["webp"];
const m = await e.enc();
await maybeDelay();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality
});
return Buffer.from(r);
}
export async function encodeAvif(image, { quality }) {
image = ImageData.from(image);
const e = supportedFormats["avif"];
const m = await e.enc();
await maybeDelay();
const val = e.autoOptimize.min || 62;
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
// Think of cqLevel as the "amount" of quantization (0 to 62),
// so a lower value yields higher quality (0 to 100).
cqLevel: Math.round(val - quality / 100 * val)
});
return Buffer.from(r);
}
export async function encodePng(image) {
image = ImageData.from(image);
const e = supportedFormats["oxipng"];
const m = await e.enc();
await maybeDelay();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions
});
return Buffer.from(r);
}
//# sourceMappingURL=impl.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,69 @@
import { Worker } from "next/dist/compiled/jest-worker";
import * as path from "path";
import { execOnce } from "../../../shared/lib/utils";
import { cpus } from "os";
const getWorker = execOnce(()=>new Worker(path.resolve(__dirname, "impl"), {
enableWorkerThreads: true,
// There will be at most 6 workers needed since each worker will take
// at least 1 operation type.
numWorkers: Math.max(1, Math.min(cpus().length - 1, 6)),
computeWorkerKey: (method)=>method
}));
export async function getMetadata(buffer) {
const worker = getWorker();
const { width , height } = await worker.decodeBuffer(buffer);
return {
width,
height
};
}
export async function processBuffer(buffer, operations, encoding, quality) {
const worker = getWorker();
let imageData = await worker.decodeBuffer(buffer);
for (const operation of operations){
if (operation.type === "rotate") {
imageData = await worker.rotate(imageData, operation.numRotations);
} else if (operation.type === "resize") {
const opt = {
image: imageData,
width: 0,
height: 0
};
if (operation.width && imageData.width && imageData.width > operation.width) {
opt.width = operation.width;
}
if (operation.height && imageData.height && imageData.height > operation.height) {
opt.height = operation.height;
}
if (opt.width > 0 || opt.height > 0) {
imageData = await worker.resize(opt);
}
}
}
switch(encoding){
case "jpeg":
return Buffer.from(await worker.encodeJpeg(imageData, {
quality
}));
case "webp":
return Buffer.from(await worker.encodeWebp(imageData, {
quality
}));
case "avif":
const avifQuality = quality - 20;
return Buffer.from(await worker.encodeAvif(imageData, {
quality: Math.max(avifQuality, 0)
}));
case "png":
return Buffer.from(await worker.encodePng(imageData));
default:
throw Error(`Unsupported encoding format`);
}
}
export async function decodeBuffer(buffer) {
const worker = getWorker();
const imageData = await worker.decodeBuffer(buffer);
return imageData;
}
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../server/lib/squoosh/main.ts"],"names":["Worker","path","execOnce","cpus","getWorker","resolve","__dirname","enableWorkerThreads","numWorkers","Math","max","min","length","computeWorkerKey","method","getMetadata","buffer","worker","width","height","decodeBuffer","processBuffer","operations","encoding","quality","imageData","operation","type","rotate","numRotations","opt","image","resize","Buffer","from","encodeJpeg","encodeWebp","avifQuality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AAI,CAAC,MAAMjB,MAAM,CAACsB,SAAS,CAACd,SAAS,CAAC,CAAC,CAAA;QACvD;YACE,MAAMe,KAAK,CAAC,CAAC,2BAA2B,CAAC,CAAC,CAAA;KAC7C;CACF;AAED,OAAO,eAAepB,YAAY,CAACJ,MAAc,EAAE;IACjD,MAAMC,MAAM,GAA4Bb,SAAS,EAAE,AAAO;IAC1D,MAAMqB,SAAS,GAAG,MAAMR,MAAM,CAACG,YAAY,CAACJ,MAAM,CAAC;IACnD,OAAOS,SAAS,CAAA;CACjB"}

View File

@@ -0,0 +1,38 @@
// eslint-disable-next-line no-shadow
export const enum MozJpegColorSpace {
GRAYSCALE = 1,
RGB,
YCbCr,
}
export interface EncodeOptions {
quality: number
baseline: boolean
arithmetic: boolean
progressive: boolean
optimize_coding: boolean
smoothing: number
color_space: MozJpegColorSpace
quant_table: number
trellis_multipass: boolean
trellis_opt_zero: boolean
trellis_opt_table: boolean
trellis_loops: number
auto_subsample: boolean
chroma_subsample: number
separate_chroma_quality: boolean
chroma_quality: number
}
export interface MozJPEGModule extends EmscriptenWasm.Module {
encode(
data: BufferSource,
width: number,
height: number,
options: EncodeOptions
): Uint8Array
}
declare var moduleFactory: EmscriptenWasm.ModuleFactory<MozJPEGModule>
export default moduleFactory

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,95 @@
let wasm;
let cachedTextDecoder = new TextDecoder("utf-8", {
ignoreBOM: true,
fatal: true
});
cachedTextDecoder.decode();
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len);
}
/**
* @param {Uint8Array} data
* @param {number} level
* @param {boolean} interlace
* @returns {Uint8Array}
*/ export function optimise(data, level, interlace) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.optimise(retptr, ptr0, len0, level, interlace);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally{
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
async function load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === "function") {
return await WebAssembly.instantiateStreaming(module, imports);
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return {
instance,
module
};
} else {
return instance;
}
}
}
async function init(input) {
const imports = {};
imports.wbg = {};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
input = fetch(input);
}
const { instance , module } = await load(await input, imports);
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
return wasm;
}
export default init;
// Manually remove the wasm and memory references to trigger GC
export function cleanup() {
wasm = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
//# sourceMappingURL=squoosh_oxipng.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../server/lib/squoosh/png/squoosh_oxipng.js"],"names":["wasm","cachedTextDecoder","TextDecoder","ignoreBOM","fatal","decode","cachegetUint8Memory0","getUint8Memory0","buffer","memory","Uint8Array","getStringFromWasm0","ptr","len","subarray","WASM_VECTOR_LEN","passArray8ToWasm0","arg","malloc","length","set","cachegetInt32Memory0","getInt32Memory0","Int32Array","getArrayU8FromWasm0","optimise","data","level","interlace","retptr","__wbindgen_add_to_stack_pointer","ptr0","__wbindgen_malloc","len0","r0","r1","v1","slice","__wbindgen_free","load","module","imports","Response","WebAssembly","instantiateStreaming","bytes","arrayBuffer","instantiate","instance","Instance","init","input","wbg","__wbindgen_throw","arg0","arg1","Error","Request","URL","fetch","exports","__wbindgen_wasm_module","cleanup"],"mappings":"AAAA,IAAIA,IAAI;AAER,IAAIC,iBAAiB,GAAG,IAAIC,WAAW,CAAC,OAAO,EAAE;IAC/CC,SAAS,EAAE,IAAI;IACfC,KAAK,EAAE,IAAI;CACZ,CAAC;AAEFH,iBAAiB,CAACI,MAAM,EAAE;AAE1B,IAAIC,oBAAoB,GAAG,IAAI;AAC/B,SAASC,eAAe,GAAG;IACzB,IACED,oBAAoB,KAAK,IAAI,IAC7BA,oBAAoB,CAACE,MAAM,KAAKR,IAAI,CAACS,MAAM,CAACD,MAAM,EAClD;QACAF,oBAAoB,GAAG,IAAII,UAAU,CAACV,IAAI,CAACS,MAAM,CAACD,MAAM,CAAC;KAC1D;IACD,OAAOF,oBAAoB,CAAA;CAC5B;AAED,SAASK,kBAAkB,CAACC,GAAG,EAAEC,GAAG,EAAE;IACpC,OAAOZ,iBAAiB,CAACI,MAAM,CAACE,eAAe,EAAE,CAACO,QAAQ,CAACF,GAAG,EAAEA,GAAG,GAAGC,GAAG,CAAC,CAAC,CAAA;CAC5E;AAED,IAAIE,eAAe,G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KAChD;IAED,IACE,OAAOJ,KAAK,KAAK,QAAQ,IACxB,OAAOM,OAAO,KAAK,UAAU,IAAIN,KAAK,YAAYM,OAAO,IACzD,OAAOC,GAAG,KAAK,UAAU,IAAIP,KAAK,YAAYO,GAAG,AAAC,EACnD;QACAP,KAAK,GAAGQ,KAAK,CAACR,KAAK,CAAC;KACrB;IAED,MAAM,EAAEH,QAAQ,CAAA,EAAER,MAAM,CAAA,EAAE,GAAG,MAAMD,IAAI,CAAC,MAAMY,KAAK,EAAEV,OAAO,CAAC;IAE7DzC,IAAI,GAAGgD,QAAQ,CAACY,OAAO;IACvBV,IAAI,CAACW,sBAAsB,GAAGrB,MAAM;IAEpC,OAAOxC,IAAI,CAAA;CACZ;AAED,eAAekD,IAAI,CAAA;AAEnB,+DAA+D;AAC/D,OAAO,SAASY,OAAO,GAAG;IACxB9D,IAAI,GAAG,IAAI;IACXM,oBAAoB,GAAG,IAAI;IAC3Be,oBAAoB,GAAG,IAAI;CAC5B"}

View File

@@ -0,0 +1,144 @@
let wasm;
let cachedTextDecoder = new TextDecoder("utf-8", {
ignoreBOM: true,
fatal: true
});
cachedTextDecoder.decode();
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
let cachegetUint8ClampedMemory0 = null;
function getUint8ClampedMemory0() {
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
}
return cachegetUint8ClampedMemory0;
}
function getClampedArrayU8FromWasm0(ptr, len) {
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
}
const heap = new Array(32).fill(undefined);
heap.push(undefined, null, true, false);
let heap_next = heap.length;
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len);
}
/**
* @param {Uint8Array} data
* @param {number} width
* @param {number} height
* @returns {Uint8Array}
*/ export function encode(data, width, height) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.encode(retptr, ptr0, len0, width, height);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally{
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
function getObject(idx) {
return heap[idx];
}
function dropObject(idx) {
if (idx < 36) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
/**
* @param {Uint8Array} data
* @returns {ImageData}
*/ export function decode(data) {
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.decode(ptr0, len0);
return takeObject(ret);
}
async function load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === "function") {
return await WebAssembly.instantiateStreaming(module, imports);
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return {
instance,
module
};
} else {
return instance;
}
}
}
async function init(input) {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 = function(arg0, arg1, arg2, arg3) {
var v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice();
wasm.__wbindgen_free(arg0, arg1 * 1);
var ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
input = fetch(input);
}
const { instance , module } = await load(await input, imports);
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
return wasm;
}
export default init;
// Manually remove the wasm and memory references to trigger GC
export function cleanup() {
wasm = null;
cachegetUint8ClampedMemory0 = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
//# sourceMappingURL=squoosh_png.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,95 @@
let wasm;
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
let cachegetUint8ClampedMemory0 = null;
function getUint8ClampedMemory0() {
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
}
return cachegetUint8ClampedMemory0;
}
function getClampedArrayU8FromWasm0(ptr, len) {
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
}
/**
* @param {Uint8Array} input_image
* @param {number} input_width
* @param {number} input_height
* @param {number} output_width
* @param {number} output_height
* @param {number} typ_idx
* @param {boolean} premultiply
* @param {boolean} color_space_conversion
* @returns {Uint8ClampedArray}
*/ export function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally{
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
async function load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === "function") {
return await WebAssembly.instantiateStreaming(module, imports);
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return {
instance,
module
};
} else {
return instance;
}
}
}
async function init(input) {
const imports = {};
if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
input = fetch(input);
}
const { instance , module } = await load(await input, imports);
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
return wasm;
}
export default init;
// Manually remove the wasm and memory references to trigger GC
export function cleanup() {
wasm = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
//# sourceMappingURL=squoosh_resize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../server/lib/squoosh/resize/squoosh_resize.js"],"names":["wasm","cachegetUint8Memory0","getUint8Memory0","buffer","memory","Uint8Array","WASM_VECTOR_LEN","passArray8ToWasm0","arg","malloc","ptr","length","set","cachegetInt32Memory0","getInt32Memory0","Int32Array","cachegetUint8ClampedMemory0","getUint8ClampedMemory0","Uint8ClampedArray","getClampedArrayU8FromWasm0","len","subarray","resize","input_image","input_width","input_height","output_width","output_height","typ_idx","premultiply","color_space_conversion","retptr","__wbindgen_add_to_stack_pointer","ptr0","__wbindgen_malloc","len0","r0","r1","v1","slice","__wbindgen_free","load","module","imports","Response","WebAssembly","instantiateStreaming","bytes","arrayBuffer","instantiate","instance","Instance","init","input","Request","URL","fetch","exports","__wbindgen_wasm_module","cleanup"],"mappings":"AAAA,IAAIA,IAAI;AAER,IAAIC,oBAAoB,GAAG,IAAI;AAC/B,SAASC,eAAe,GAAG;IACzB,IACED,oBAAoB,KAAK,IAAI,IAC7BA,oBAAoB,CAACE,MAAM,KAAKH,IAAI,CAACI,MAAM,CAACD,MAAM,EAClD;QACAF,oBAAoB,GAAG,IAAII,UAAU,CAACL,IAAI,CAACI,MAAM,CAACD,MAAM,CAAC;KAC1D;IACD,OAAOF,oBAAoB,CAAA;CAC5B;AAED,IAAIK,eAAe,GAAG,CAAC;AAEvB,SAASC,iBAAiB,CAACC,GAAG,EAAEC,MAAM,EAAE;IACtC,MAAMC,GAAG,GAAGD,MAAM,CAACD,GAAG,CAACG,MAAM,GAAG,CAAC,CAAC;IAClCT,eAAe,EAAE,CAACU,GAAG,CAACJ,GAAG,EAAEE,GAAG,GAAG,CAAC,CAAC;IACnCJ,eAAe,GAAGE,GAAG,CAACG,MAAM;IAC5B,OAAOD,GAAG,CAAA;CACX;AAED,IAAIG,oBAAoB,GAAG,IAAI;AAC/B,SAASC,e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AAK,YAAYE,GAAG,AAAC,EACnD;QACAF,KAAK,GAAGG,KAAK,CAACH,KAAK,CAAC;KACrB;IAED,MAAM,EAAEH,QAAQ,CAAA,EAAER,MAAM,CAAA,EAAE,GAAG,MAAMD,IAAI,CAAC,MAAMY,KAAK,EAAEV,OAAO,CAAC;IAE7D3C,IAAI,GAAGkD,QAAQ,CAACO,OAAO;IACvBL,IAAI,CAACM,sBAAsB,GAAGhB,MAAM;IAEpC,OAAO1C,IAAI,CAAA;CACZ;AAED,eAAeoD,IAAI,CAAA;AAEnB,+DAA+D;AAC/D,OAAO,SAASO,OAAO,GAAG;IACxB3D,IAAI,GAAG,IAAI;IACXC,oBAAoB,GAAG,IAAI;IAC3BY,oBAAoB,GAAG,IAAI;CAC5B"}

View File

@@ -0,0 +1,42 @@
export interface EncodeOptions {
quality: number
target_size: number
target_PSNR: number
method: number
sns_strength: number
filter_strength: number
filter_sharpness: number
filter_type: number
partitions: number
segments: number
pass: number
show_compressed: number
preprocessing: number
autofilter: number
partition_limit: number
alpha_compression: number
alpha_filtering: number
alpha_quality: number
lossless: number
exact: number
image_hint: number
emulate_jpeg_size: number
thread_level: number
low_memory: number
near_lossless: number
use_delta_palette: number
use_sharp_yuv: number
}
export interface WebPModule extends EmscriptenWasm.Module {
encode(
data: BufferSource,
width: number,
height: number,
options: EncodeOptions
): Uint8Array
}
declare var moduleFactory: EmscriptenWasm.ModuleFactory<WebPModule>
export default moduleFactory

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,56 @@
import { warn } from "../../build/output/log";
import http from "http";
import next from "../next";
import cluster from "cluster";
import v8 from "v8";
const MAXIMUM_HEAP_SIZE_ALLOWED = v8.getHeapStatistics().heap_size_limit / 1024 / 1024 * 0.9;
export function startServer(opts) {
let requestHandler;
const server = http.createServer((req, res)=>{
return requestHandler(req, res).finally(()=>{
if (cluster.worker && process.memoryUsage().heapUsed / 1024 / 1024 > MAXIMUM_HEAP_SIZE_ALLOWED) {
cluster.worker.kill();
}
});
});
if (opts.keepAliveTimeout) {
server.keepAliveTimeout = opts.keepAliveTimeout;
}
return new Promise((resolve, reject)=>{
let port = opts.port;
let retryCount = 0;
server.on("error", (err)=>{
if (port && opts.allowRetry && err.code === "EADDRINUSE" && retryCount < 10) {
warn(`Port ${port} is in use, trying ${port + 1} instead.`);
port += 1;
retryCount += 1;
server.listen(port, opts.hostname);
} else {
reject(err);
}
});
let upgradeHandler;
if (!opts.dev) {
server.on("upgrade", (req, socket, upgrade)=>{
upgradeHandler(req, socket, upgrade);
});
}
server.on("listening", ()=>{
const addr = server.address();
const hostname = !opts.hostname || opts.hostname === "0.0.0.0" ? "localhost" : opts.hostname;
const app = next({
...opts,
hostname,
customServer: false,
httpServer: server,
port: addr && typeof addr === "object" ? addr.port : port
});
requestHandler = app.getRequestHandler();
upgradeHandler = app.getUpgradeHandler();
resolve(app);
});
server.listen(port, opts.hostname);
});
}
//# sourceMappingURL=start-server.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../server/lib/start-server.ts"],"names":["warn","http","next","cluster","v8","MAXIMUM_HEAP_SIZE_ALLOWED","getHeapStatistics","heap_size_limit","startServer","opts","requestHandler","server","createServer","req","res","finally","worker","process","memoryUsage","heapUsed","kill","keepAliveTimeout","Promise","resolve","reject","port","retryCount","on","err","allowRetry","code","listen","hostname","upgradeHandler","dev","socket","upgrade","addr","address","app","customServer","httpServer","getRequestHandler","getUpgradeHandler"],"mappings":"AACA,SAASA,IAAI,QAAQ,wBAAwB,CAAA;AAC7C,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,IAAI,MAAM,SAAS,CAAA;AAC1B,OAAOC,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAOC,EAAE,MAAM,IAAI,CAAA;AAMnB,MAAMC,yBAAyB,GAC7B,AAACD,EAAE,CAACE,iBAAiB,EAAE,CAACC,eAAe,GAAG,I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AG,EAAE;YACbvB,MAAM,CAACgB,EAAE,CAAC,SAAS,EAAE,CAACd,GAAG,EAAEsB,MAAM,EAAEC,OAAO,GAAK;gBAC7CH,cAAc,CAACpB,GAAG,EAAEsB,MAAM,EAAEC,OAAO,CAAC;aACrC,CAAC;SACH;QAEDzB,MAAM,CAACgB,EAAE,CAAC,WAAW,EAAE,IAAM;YAC3B,MAAMU,IAAI,GAAG1B,MAAM,CAAC2B,OAAO,EAAE;YAC7B,MAAMN,QAAQ,GACZ,CAACvB,IAAI,CAACuB,QAAQ,IAAIvB,IAAI,CAACuB,QAAQ,KAAK,SAAS,GACzC,WAAW,GACXvB,IAAI,CAACuB,QAAQ;YAEnB,MAAMO,GAAG,GAAGrC,IAAI,CAAC;gBACf,GAAGO,IAAI;gBACPuB,QAAQ;gBACRQ,YAAY,EAAE,KAAK;gBACnBC,UAAU,EAAE9B,MAAM;gBAClBc,IAAI,EAAEY,IAAI,IAAI,OAAOA,IAAI,KAAK,QAAQ,GAAGA,IAAI,CAACZ,IAAI,GAAGA,IAAI;aAC1D,CAAC;YAEFf,cAAc,GAAG6B,GAAG,CAACG,iBAAiB,EAAE;YACxCT,cAAc,GAAGM,GAAG,CAACI,iBAAiB,EAAE;YACxCpB,OAAO,CAACgB,GAAG,CAAC;SACb,CAAC;QAEF5B,MAAM,CAACoB,MAAM,CAACN,IAAI,EAAEhB,IAAI,CAACuB,QAAQ,CAAC;KACnC,CAAC,CAAA;CACH"}

View File

@@ -0,0 +1,24 @@
export function printAndExit(message, code = 1) {
if (code === 0) {
console.log(message);
} else {
console.error(message);
}
process.exit(code);
}
export function getNodeOptionsWithoutInspect() {
const NODE_INSPECT_RE = /--inspect(-brk)?(=\S+)?( |$)/;
return (process.env.NODE_OPTIONS || "").replace(NODE_INSPECT_RE, "");
}
export function getPort(args) {
if (typeof args["--port"] === "number") {
return args["--port"];
}
const parsed = process.env.PORT && parseInt(process.env.PORT, 10);
if (typeof parsed === "number" && !Number.isNaN(parsed)) {
return parsed;
}
return 3000;
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../server/lib/utils.ts"],"names":["printAndExit","message","code","console","log","error","process","exit","getNodeOptionsWithoutInspect","NODE_INSPECT_RE","env","NODE_OPTIONS","replace","getPort","args","parsed","PORT","parseInt","Number","isNaN"],"mappings":"AAEA,OAAO,SAASA,YAAY,CAACC,OAAe,EAAEC,IAAI,GAAG,CAAC,EAAE;IACtD,IAAIA,IAAI,KAAK,CAAC,EAAE;QACdC,OAAO,CAACC,GAAG,CAACH,OAAO,CAAC;KACrB,MAAM;QACLE,OAAO,CAACE,KAAK,CAACJ,OAAO,CAAC;KACvB;IAEDK,OAAO,CAACC,IAAI,CAACL,IAAI,CAAC;CACnB;AAED,OAAO,SAASM,4BAA4B,GAAG;IAC7C,MAAMC,eAAe,iCAAiC;IACtD,OAAO,CAACH,OAAO,CAACI,GAAG,CAACC,YAAY,IAAI,EAAE,CAAC,CAACC,OAAO,CAACH,eAAe,EAAE,EAAE,CAAC,CAAA;CACrE;AAED,OAAO,SAASI,OAAO,CAACC,IAA0B,EAAU;IAC1D,IAAI,OAAOA,IAAI,CAAC,QAAQ,CAAC,KAAK,QAAQ,EAAE;QACtC,OAAOA,IAAI,CAAC,QAAQ,CAAC,CAAA;KACtB;IAED,MAAMC,MAAM,GAAGT,OAAO,CAACI,GAAG,CAACM,IAAI,IAAIC,QAAQ,CAACX,OAAO,CAACI,GAAG,CAACM,IAAI,EAAE,EAAE,CAAC;IACjE,IAAI,OAAOD,MAAM,KAAK,QAAQ,IAAI,CAACG,MAAM,CAACC,KAAK,CAACJ,MAAM,CAAC,EAAE;QACvD,OAAOA,MAAM,CAAA;KACd;IAED,OAAO,IAAI,CAAA;CACZ"}