diff --git a/.changeset/gold-rocks-cry.md b/.changeset/gold-rocks-cry.md new file mode 100644 index 000000000000..412ef354a912 --- /dev/null +++ b/.changeset/gold-rocks-cry.md @@ -0,0 +1,15 @@ +--- +'astro': minor +'@astrojs/mdx': minor +'@astrojs/markdown-remark': minor +--- + +Add a new experimental flag (`experimental.assets`) to enable our new core Assets story. + +This unlocks a few features: +- A new built-in image component and JavaScript API to transform and optimize images. +- Relative images with automatic optimization in Markdown. +- Support for validating assets using content collections. +- and more! + +See [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) on our docs site for more information on how to use this feature! diff --git a/packages/astro/client-base.d.ts b/packages/astro/client-base.d.ts index fb440995f11f..33ff9cef7c99 100644 --- a/packages/astro/client-base.d.ts +++ b/packages/astro/client-base.d.ts @@ -1,5 +1,28 @@ /// +declare module 'astro:assets' { + // Exporting things one by one is a bit cumbersome, not sure if there's a better way - erika, 2023-02-03 + type AstroAssets = { + getImage: typeof import('./dist/assets/index.js').getImage; + Image: typeof import('./components/Image.astro').default; + }; + + type WithRequired = T & { [P in K]-?: T[P] }; + type Simplify = { [KeyType in keyof T]: T[KeyType] }; + type ImgAttributes = WithRequired< + Omit, 'src' | 'width' | 'height'>, + 'alt' + >; + + export type LocalImageProps = Simplify< + import('./dist/assets/types.js').LocalImageProps + >; + export type RemoteImageProps = Simplify< + import('./dist/assets/types.js').RemoteImageProps + >; + export const { getImage, Image }: AstroAssets; +} + type MD = import('./dist/@types/astro').MarkdownInstance>; interface ExportedMarkdownModuleEntities { frontmatter: MD['frontmatter']; diff --git a/packages/astro/client-image.d.ts b/packages/astro/client-image.d.ts new file mode 100644 index 000000000000..fe8a16ede620 --- /dev/null +++ b/packages/astro/client-image.d.ts @@ -0,0 +1,48 @@ +/// + +type InputFormat = 'avif' | 'gif' | 'heic' | 'heif' | 'jpeg' | 'jpg' | 'png' | 'tiff' | 'webp'; + +interface ImageMetadata { + src: string; + width: number; + height: number; + format: InputFormat; +} + +// images +declare module '*.avif' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.gif' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.heic' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.heif' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.jpeg' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.jpg' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.png' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.tiff' { + const metadata: ImageMetadata; + export default metadata; +} +declare module '*.webp' { + const metadata: ImageMetadata; + export default metadata; +} diff --git a/packages/astro/components/Image.astro b/packages/astro/components/Image.astro new file mode 100644 index 000000000000..00b0cc5fafbc --- /dev/null +++ b/packages/astro/components/Image.astro @@ -0,0 +1,28 @@ +--- +import { getImage, type LocalImageProps, type RemoteImageProps } from 'astro:assets'; +import { AstroError, AstroErrorData } from '../dist/core/errors/index.js'; + +// The TypeScript diagnostic for JSX props uses the last member of the union to suggest props, so it would be better for +// LocalImageProps to be last. Unfortunately, when we do this the error messages that remote images get are complete nonsense +// Not 100% sure how to fix this, seems to be a TypeScript issue. Unfortunate. +type Props = LocalImageProps | RemoteImageProps; + +const props = Astro.props; + +if (props.alt === undefined || props.alt === null) { + throw new AstroError(AstroErrorData.ImageMissingAlt); +} + +// As a convenience, allow width and height to be string with a number in them, to match HTML's native `img`. +if (typeof props.width === 'string') { + props.width = parseInt(props.width); +} + +if (typeof props.height === 'string') { + props.height = parseInt(props.height); +} + +const image = await getImage(props); +--- + + diff --git a/packages/astro/package.json b/packages/astro/package.json index f91fa52e33dc..141b07477cbe 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -32,6 +32,7 @@ "./types": "./types.d.ts", "./client": "./client.d.ts", "./client-base": "./client-base.d.ts", + "./client-image": "./client-image.d.ts", "./import-meta": "./import-meta.d.ts", "./astro-jsx": "./astro-jsx.d.ts", "./tsconfigs/*.json": "./tsconfigs/*", @@ -47,6 +48,10 @@ "./client/*": "./dist/runtime/client/*", "./components": "./components/index.ts", "./components/*": "./components/*", + "./assets": "./dist/assets/index.js", + "./assets/image-endpoint": "./dist/assets/image-endpoint.js", + "./assets/services/sharp": "./dist/assets/services/sharp.js", + "./assets/services/squoosh": "./dist/assets/services/squoosh.js", "./content/internal": "./dist/content/internal.js", "./debug": "./components/Debug.astro", "./internal/*": "./dist/runtime/server/*", @@ -77,6 +82,7 @@ "env.d.ts", "client.d.ts", "client-base.d.ts", + "client-image.d.ts", "import-meta.d.ts", "astro-jsx.d.ts", "types.d.ts", @@ -86,10 +92,10 @@ ], "scripts": { "prebuild": "astro-scripts prebuild --to-string \"src/runtime/server/astro-island.ts\" \"src/runtime/client/{idle,load,media,only,visible}.ts\"", - "build": "pnpm run prebuild && astro-scripts build \"src/**/*.ts\" && tsc", + "build": "pnpm run prebuild && astro-scripts build \"src/**/*.ts\" && tsc && pnpm run postbuild", "build:ci": "pnpm run prebuild && astro-scripts build \"src/**/*.ts\"", - "dev": "astro-scripts dev --prebuild \"src/runtime/server/astro-island.ts\" --prebuild \"src/runtime/client/{idle,load,media,only,visible}.ts\" \"src/**/*.ts\"", - "postbuild": "astro-scripts copy \"src/**/*.astro\"", + "dev": "astro-scripts dev --copy-wasm --prebuild \"src/runtime/server/astro-island.ts\" --prebuild \"src/runtime/client/{idle,load,media,only,visible}.ts\" \"src/**/*.ts\"", + "postbuild": "astro-scripts copy \"src/**/*.astro\" && astro-scripts copy \"src/**/*.wasm\"", "test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js", "test:unit:match": "mocha --exit --timeout 30000 ./test/units/**/*.test.js -g", "test": "pnpm run test:unit && mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js", @@ -128,6 +134,7 @@ "github-slugger": "^2.0.0", "gray-matter": "^4.0.3", "html-escaper": "^3.0.3", + "image-size": "^1.0.2", "kleur": "^4.1.4", "magic-string": "^0.27.0", "mime": "^3.0.0", @@ -173,6 +180,7 @@ "@types/rimraf": "^3.0.2", "@types/send": "^0.17.1", "@types/server-destroy": "^1.0.1", + "@types/sharp": "^0.31.1", "@types/unist": "^2.0.6", "astro-scripts": "workspace:*", "chai": "^4.3.6", @@ -187,10 +195,19 @@ "remark-code-titles": "^0.1.2", "rollup": "^3.9.0", "sass": "^1.52.2", + "sharp": "^0.31.3", "srcset-parse": "^1.1.0", "undici": "^5.20.0", "unified": "^10.1.2" }, + "peerDependencies": { + "sharp": "^0.31.3" + }, + "peerDependenciesMeta": { + "sharp": { + "optional": true + } + }, "engines": { "node": ">=16.12.0", "npm": ">=6.14.0" diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index c915da2ec87f..95e027d46e9f 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -18,6 +18,7 @@ import type { PageBuildData } from '../core/build/types'; import type { AstroConfigSchema } from '../core/config'; import type { AstroTimer } from '../core/config/timer'; import type { AstroCookies } from '../core/cookies'; +import type { LogOptions } from '../core/logger/core'; import type { AstroComponentFactory, AstroComponentInstance } from '../runtime/server'; import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './../core/constants.js'; export type { @@ -28,6 +29,8 @@ export type { RemarkPlugins, ShikiConfig, } from '@astrojs/markdown-remark'; +export type { ExternalImageService, LocalImageService } from '../assets/services/service'; +export type { ImageTransform } from '../assets/types'; export type { SSRManifest } from '../core/app/types'; export type { AstroCookies } from '../core/cookies'; @@ -85,6 +88,7 @@ export interface CLIFlags { port?: number; config?: string; drafts?: boolean; + experimentalAssets?: boolean; } export interface BuildConfig { @@ -696,6 +700,16 @@ export interface AstroUserConfig { server?: ServerConfig | ((options: { command: 'dev' | 'preview' }) => ServerConfig); + /** + * @docs + * @kind heading + * @name Image options + */ + image?: { + // eslint-disable-next-line @typescript-eslint/ban-types + service: 'astro/assets/services/sharp' | 'astro/assets/services/squoosh' | (string & {}); + }; + /** * @docs * @kind heading @@ -918,7 +932,27 @@ export interface AstroUserConfig { * Astro offers experimental flags to give users early access to new features. * These flags are not guaranteed to be stable. */ - experimental?: object; + experimental?: { + /** + * @docs + * @name experimental.assets + * @type {boolean} + * @default `false` + * @version 2.1.0 + * @description + * Enable experimental support for optimizing and resizing images. With this enabled, a new `astro:assets` module will be exposed. + * + * To enable this feature, set `experimental.assets` to `true` in your Astro config: + * + * ```js + * { + * experimental: { + * assets: true, + * }, + * } + */ + assets?: boolean; + }; // Legacy options to be removed @@ -1432,6 +1466,11 @@ export interface AstroIntegration { }; } +export interface AstroPluginOptions { + settings: AstroSettings; + logging: LogOptions; +} + export type RouteType = 'page' | 'endpoint'; export interface RoutePart { diff --git a/packages/astro/src/assets/README.md b/packages/astro/src/assets/README.md new file mode 100644 index 000000000000..9de1c5eb4185 --- /dev/null +++ b/packages/astro/src/assets/README.md @@ -0,0 +1,3 @@ +# assets + +This directory powers the Assets story in Astro. Notably, it contains all the code related to optimizing images and serving them in the different modes Astro can run in (SSG, SSR, dev, build etc). diff --git a/packages/astro/src/assets/consts.ts b/packages/astro/src/assets/consts.ts new file mode 100644 index 000000000000..77f2ea9803d8 --- /dev/null +++ b/packages/astro/src/assets/consts.ts @@ -0,0 +1,14 @@ +export const VIRTUAL_MODULE_ID = 'astro:assets'; +export const VIRTUAL_SERVICE_ID = 'virtual:image-service'; +export const VALID_INPUT_FORMATS = [ + 'heic', + 'heif', + 'avif', + 'jpeg', + 'jpg', + 'png', + 'tiff', + 'webp', + 'gif', +] as const; +export const VALID_OUTPUT_FORMATS = ['avif', 'png', 'webp', 'jpeg', 'jpg'] as const; diff --git a/packages/astro/src/assets/image-endpoint.ts b/packages/astro/src/assets/image-endpoint.ts new file mode 100644 index 000000000000..02e258522a38 --- /dev/null +++ b/packages/astro/src/assets/image-endpoint.ts @@ -0,0 +1,66 @@ +import mime from 'mime'; +import type { APIRoute } from '../@types/astro.js'; +import { isRemotePath } from '../core/path.js'; +import { getConfiguredImageService } from './internal.js'; +import { isLocalService } from './services/service.js'; +import { etag } from './utils/etag.js'; + +async function loadRemoteImage(src: URL) { + try { + const res = await fetch(src); + + if (!res.ok) { + return undefined; + } + + return Buffer.from(await res.arrayBuffer()); + } catch (err: unknown) { + return undefined; + } +} + +/** + * Endpoint used in SSR to serve optimized images + */ +export const get: APIRoute = async ({ request }) => { + try { + const imageService = await getConfiguredImageService(); + + if (!isLocalService(imageService)) { + throw new Error('Configured image service is not a local service'); + } + + const url = new URL(request.url); + const transform = await imageService.parseURL(url); + + if (!transform || !transform.src) { + throw new Error('Incorrect transform returned by `parseURL`'); + } + + let inputBuffer: Buffer | undefined = undefined; + + // TODO: handle config subpaths? + const sourceUrl = isRemotePath(transform.src) + ? new URL(transform.src) + : new URL(transform.src, url.origin); + inputBuffer = await loadRemoteImage(sourceUrl); + + if (!inputBuffer) { + return new Response('Not Found', { status: 404 }); + } + + const { data, format } = await imageService.transform(inputBuffer, transform); + + return new Response(data, { + status: 200, + headers: { + 'Content-Type': mime.getType(format) || '', + 'Cache-Control': 'public, max-age=31536000', + ETag: etag(data.toString()), + Date: new Date().toUTCString(), + }, + }); + } catch (err: unknown) { + return new Response(`Server Error: ${err}`, { status: 500 }); + } +}; diff --git a/packages/astro/src/assets/index.ts b/packages/astro/src/assets/index.ts new file mode 100644 index 000000000000..f768c58dd0a5 --- /dev/null +++ b/packages/astro/src/assets/index.ts @@ -0,0 +1,4 @@ +export { getConfiguredImageService, getImage } from './internal.js'; +export { baseService } from './services/service.js'; +export { type LocalImageProps, type RemoteImageProps } from './types.js'; +export { imageMetadata } from './utils/metadata.js'; diff --git a/packages/astro/src/assets/internal.ts b/packages/astro/src/assets/internal.ts new file mode 100644 index 000000000000..aa69f7183260 --- /dev/null +++ b/packages/astro/src/assets/internal.ts @@ -0,0 +1,117 @@ +import fs from 'node:fs'; +import { StaticBuildOptions } from '../core/build/types.js'; +import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { ImageService, isLocalService, LocalImageService } from './services/service.js'; +import type { ImageMetadata, ImageTransform } from './types.js'; + +export function isESMImportedImage(src: ImageMetadata | string): src is ImageMetadata { + return typeof src === 'object'; +} + +export async function getConfiguredImageService(): Promise { + if (!globalThis.astroAsset.imageService) { + const { default: service }: { default: ImageService } = await import( + // @ts-expect-error + 'virtual:image-service' + ).catch((e) => { + const error = new AstroError(AstroErrorData.InvalidImageService); + (error as any).cause = e; + throw error; + }); + + globalThis.astroAsset.imageService = service; + return service; + } + + return globalThis.astroAsset.imageService; +} + +interface GetImageResult { + options: ImageTransform; + src: string; + attributes: Record; +} + +/** + * Get an optimized image and the necessary attributes to render it. + * + * **Example** + * ```astro + * --- + * import { getImage } from 'astro:assets'; + * import originalImage from '../assets/image.png'; + * + * const optimizedImage = await getImage({src: originalImage, width: 1280 }) + * --- + * + * ``` + * + * This is functionally equivalent to using the `` component, as the component calls this function internally. + */ +export async function getImage(options: ImageTransform): Promise { + const service = await getConfiguredImageService(); + let imageURL = service.getURL(options); + + // In build and for local services, we need to collect the requested parameters so we can generate the final images + if (isLocalService(service) && globalThis.astroAsset.addStaticImage) { + imageURL = globalThis.astroAsset.addStaticImage(options); + } + + return { + options, + src: imageURL, + attributes: service.getHTMLAttributes !== undefined ? service.getHTMLAttributes(options) : {}, + }; +} + +export function getStaticImageList(): Iterable<[ImageTransform, string]> { + if (!globalThis?.astroAsset?.staticImages) { + return []; + } + + return globalThis.astroAsset.staticImages?.entries(); +} + +interface GenerationData { + weight: { + before: number; + after: number; + }; +} + +export async function generateImage( + buildOpts: StaticBuildOptions, + options: ImageTransform, + filepath: string +): Promise { + if (!isESMImportedImage(options.src)) { + return undefined; + } + + const imageService = (await getConfiguredImageService()) as LocalImageService; + + let serverRoot: URL, clientRoot: URL; + if (buildOpts.settings.config.output === 'server') { + serverRoot = buildOpts.settings.config.build.server; + clientRoot = buildOpts.settings.config.build.client; + } else { + serverRoot = buildOpts.settings.config.outDir; + clientRoot = buildOpts.settings.config.outDir; + } + + const fileData = await fs.promises.readFile(new URL('.' + options.src.src, serverRoot)); + const resultData = await imageService.transform(fileData, { ...options, src: options.src.src }); + + const finalFileURL = new URL('.' + filepath, clientRoot); + const finalFolderURL = new URL('./', finalFileURL); + + await fs.promises.mkdir(finalFolderURL, { recursive: true }); + await fs.promises.writeFile(finalFileURL, resultData.data); + + return { + weight: { + before: Math.trunc(fileData.byteLength / 1024), + after: Math.trunc(resultData.data.byteLength / 1024), + }, + }; +} diff --git a/packages/astro/src/assets/services/service.ts b/packages/astro/src/assets/services/service.ts new file mode 100644 index 000000000000..3e12754551a2 --- /dev/null +++ b/packages/astro/src/assets/services/service.ts @@ -0,0 +1,174 @@ +import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import { isRemotePath } from '../../core/path.js'; +import { isESMImportedImage } from '../internal.js'; +import { ImageTransform, OutputFormat } from '../types.js'; + +export type ImageService = LocalImageService | ExternalImageService; + +export function isLocalService(service: ImageService | undefined): service is LocalImageService { + if (!service) { + return false; + } + + return 'transform' in service; +} + +export function parseQuality(quality: string): string | number { + let result = parseInt(quality); + if (Number.isNaN(result)) { + return quality; + } + + return result; +} + +interface SharedServiceProps { + /** + * Return the URL to the endpoint or URL your images are generated from. + * + * For a local service, your service should expose an endpoint handling the image requests, or use Astro's at `/_image`. + * + * For external services, this should point to the URL your images are coming from, for instance, `/_vercel/image` + * + */ + getURL: (options: ImageTransform) => string; + /** + * Return any additional HTML attributes separate from `src` that your service requires to show the image properly. + * + * For example, you might want to return the `width` and `height` to avoid CLS, or a particular `class` or `style`. + * In most cases, you'll want to return directly what your user supplied you, minus the attributes that were used to generate the image. + */ + getHTMLAttributes?: (options: ImageTransform) => Record; +} + +export type ExternalImageService = SharedServiceProps; + +type LocalImageTransform = { + src: string; + [key: string]: any; +}; + +export interface LocalImageService extends SharedServiceProps { + /** + * Parse the requested parameters passed in the URL from `getURL` back into an object to be used later by `transform` + * + * In most cases, this will get query parameters using, for example, `params.get('width')` and return those. + */ + parseURL: (url: URL) => LocalImageTransform | undefined; + /** + * Performs the image transformations on the input image and returns both the binary data and + * final image format of the optimized image. + */ + transform: ( + inputBuffer: Buffer, + transform: LocalImageTransform + ) => Promise<{ data: Buffer; format: OutputFormat }>; +} + +export type BaseServiceTransform = { + src: string; + width?: number; + height?: number; + format?: string | null; + quality?: string | null; +}; + +/** + * Basic local service using the included `_image` endpoint. + * This service intentionally does not implement `transform`. + * + * Example usage: + * ```ts + * const service = { + * getURL: baseService.getURL, + * parseURL: baseService.parseURL, + * getHTMLAttributes: baseService.getHTMLAttributes, + * async transform(inputBuffer, transformOptions) {...} + * } + * ``` + * + * This service only supports the following properties: `width`, `height`, `format` and `quality`. + * Additionally, remote URLs are passed as-is. + * + */ +export const baseService: Omit = { + getHTMLAttributes(options) { + let targetWidth = options.width; + let targetHeight = options.height; + if (isESMImportedImage(options.src)) { + const aspectRatio = options.src.width / options.src.height; + + // If we have a desired height and no width, calculate the target width automatically + if (targetHeight && !targetWidth) { + targetWidth = Math.round(targetHeight * aspectRatio); + } else if (targetWidth && !targetHeight) { + targetHeight = Math.round(targetWidth / aspectRatio); + } else { + targetWidth = options.src.width; + targetHeight = options.src.height; + } + } + + const { src, width, height, format, quality, ...attributes } = options; + + return { + ...attributes, + width: targetWidth, + height: targetHeight, + loading: attributes.loading ?? 'lazy', + decoding: attributes.decoding ?? 'async', + }; + }, + getURL(options: ImageTransform) { + if (!isESMImportedImage(options.src)) { + // For non-ESM imported images, width and height are required to avoid CLS, as we can't infer them from the file + let missingDimension: 'width' | 'height' | 'both' | undefined; + if (!options.width && !options.height) { + missingDimension = 'both'; + } else if (!options.width && options.height) { + missingDimension = 'width'; + } else if (options.width && !options.height) { + missingDimension = 'height'; + } + + if (missingDimension) { + throw new AstroError({ + ...AstroErrorData.MissingImageDimension, + message: AstroErrorData.MissingImageDimension.message(missingDimension), + }); + } + } + + // Both our currently available local services don't handle remote images, so for them we can just return as is + if (!isESMImportedImage(options.src) && isRemotePath(options.src)) { + return options.src; + } + + const searchParams = new URLSearchParams(); + searchParams.append('href', isESMImportedImage(options.src) ? options.src.src : options.src); + + options.width && searchParams.append('w', options.width.toString()); + options.height && searchParams.append('h', options.height.toString()); + options.quality && searchParams.append('q', options.quality.toString()); + options.format && searchParams.append('f', options.format); + + return '/_image?' + searchParams; + }, + parseURL(url) { + const params = url.searchParams; + + if (!params.has('href')) { + return undefined; + } + + const transform: BaseServiceTransform = { + src: params.get('href')!, + width: params.has('w') ? parseInt(params.get('w')!) : undefined, + height: params.has('h') ? parseInt(params.get('h')!) : undefined, + format: params.get('f') as OutputFormat | null, + quality: params.get('q'), + }; + + return transform; + }, +}; diff --git a/packages/astro/src/assets/services/sharp.ts b/packages/astro/src/assets/services/sharp.ts new file mode 100644 index 000000000000..a79c2c33e874 --- /dev/null +++ b/packages/astro/src/assets/services/sharp.ts @@ -0,0 +1,72 @@ +import type { FormatEnum } from 'sharp'; +import type { ImageQualityPreset, OutputFormat } from '../types.js'; +import { baseService, BaseServiceTransform, LocalImageService, parseQuality } from './service.js'; + +let sharp: typeof import('sharp'); + +const qualityTable: Record = { + low: 25, + mid: 50, + high: 80, + max: 100, +}; + +async function loadSharp() { + let sharpImport: typeof import('sharp'); + try { + sharpImport = (await import('sharp')).default; + } catch (e) { + throw new Error('Could not find Sharp. Please install Sharp manually into your project.'); + } + + return sharpImport; +} + +const sharpService: LocalImageService = { + getURL: baseService.getURL, + parseURL: baseService.parseURL, + getHTMLAttributes: baseService.getHTMLAttributes, + async transform(inputBuffer, transformOptions) { + if (!sharp) sharp = await loadSharp(); + + const transform: BaseServiceTransform = transformOptions; + + // If the user didn't specify a format, we'll default to `webp`. It offers the best ratio of compatibility / quality + // In the future, hopefully we can replace this with `avif`, alas, Edge. See https://caniuse.com/avif + if (!transform.format) { + transform.format = 'webp'; + } + + let result = sharp(inputBuffer, { failOnError: false, pages: -1 }); + + // Never resize using both width and height at the same time, prioritizing width. + if (transform.height && !transform.width) { + result.resize({ height: transform.height }); + } else if (transform.width) { + result.resize({ width: transform.width }); + } + + if (transform.format) { + let quality: number | string | undefined = undefined; + if (transform.quality) { + const parsedQuality = parseQuality(transform.quality); + if (typeof parsedQuality === 'number') { + quality = parsedQuality; + } else { + quality = transform.quality in qualityTable ? qualityTable[transform.quality] : undefined; + } + } + + result.toFormat(transform.format as keyof FormatEnum, { quality: quality }); + } + + const { data, info } = await result.toBuffer({ resolveWithObject: true }); + + return { + data: data, + format: info.format as OutputFormat, + }; + }, +}; + +export default sharpService; diff --git a/packages/astro/src/assets/services/squoosh.ts b/packages/astro/src/assets/services/squoosh.ts new file mode 100644 index 000000000000..b726b4034c06 --- /dev/null +++ b/packages/astro/src/assets/services/squoosh.ts @@ -0,0 +1,72 @@ +// TODO: Investigate removing this service once sharp lands WASM support, as libsquoosh is deprecated + +import type { ImageQualityPreset, OutputFormat } from '../types.js'; +import { baseService, BaseServiceTransform, LocalImageService, parseQuality } from './service.js'; +import { processBuffer } from './vendor/squoosh/image-pool.js'; +import type { Operation } from './vendor/squoosh/image.js'; + +const baseQuality = { low: 25, mid: 50, high: 80, max: 100 }; +const qualityTable: Record, Record> = { + avif: { + // Squoosh's AVIF encoder has a bit of a weird behavior where `62` is technically the maximum, and anything over is overkill + max: 62, + high: 45, + mid: 35, + low: 20, + }, + jpeg: baseQuality, + jpg: baseQuality, + webp: baseQuality, + // Squoosh's PNG encoder does not support a quality setting, so we can skip that here +}; + +const service: LocalImageService = { + getURL: baseService.getURL, + parseURL: baseService.parseURL, + getHTMLAttributes: baseService.getHTMLAttributes, + async transform(inputBuffer, transformOptions) { + const transform: BaseServiceTransform = transformOptions as BaseServiceTransform; + + let format = transform.format; + if (!format) { + format = 'webp'; + } + + const operations: Operation[] = []; + + // Never resize using both width and height at the same time, prioritizing width. + if (transform.height && !transform.width) { + operations.push({ + type: 'resize', + height: transform.height, + }); + } else if (transform.width) { + operations.push({ + type: 'resize', + width: transform.width, + }); + } + + let quality: number | string | undefined = undefined; + if (transform.quality) { + const parsedQuality = parseQuality(transform.quality); + if (typeof parsedQuality === 'number') { + quality = parsedQuality; + } else { + quality = + transform.quality in qualityTable[format] + ? qualityTable[format][transform.quality] + : undefined; + } + } + + const data = await processBuffer(inputBuffer, operations, format, quality); + + return { + data: Buffer.from(data), + format: format, + }; + }, +}; + +export default service; diff --git a/packages/astro/src/assets/services/vendor/squoosh/LICENSE b/packages/astro/src/assets/services/vendor/squoosh/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/packages/astro/src/assets/services/vendor/squoosh/avif/avif_enc.d.ts b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_enc.d.ts new file mode 100644 index 000000000000..d91bbf36e051 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_enc.d.ts @@ -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 + +export default moduleFactory diff --git a/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_dec.ts b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_dec.ts new file mode 100644 index 000000000000..b432feefda28 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_dec.ts @@ -0,0 +1,1765 @@ +/* eslint-disable */ +// @ts-nocheck +import { createRequire } from 'module'; +import { dirname, getModuleURL } from '../emscripten-utils.js'; +const require = createRequire(getModuleURL(import.meta.url)); + +var Module = (function () { + return function (Module) { + Module = Module || {} + + var Module = typeof Module !== 'undefined' ? Module : {} + var readyPromiseResolve, readyPromiseReject + Module['ready'] = new Promise(function (resolve, reject) { + readyPromiseResolve = resolve + readyPromiseReject = reject + }) + var moduleOverrides = {} + var key + for (key in Module) { + if (Module.hasOwnProperty(key)) { + moduleOverrides[key] = Module[key] + } + } + var arguments_ = [] + var thisProgram = './this.program' + var quit_ = function (status, toThrow) { + throw toThrow + } + var ENVIRONMENT_IS_WEB = false + var ENVIRONMENT_IS_WORKER = false + var ENVIRONMENT_IS_NODE = true + var scriptDirectory = '' + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory) + } + return scriptDirectory + path + } + var read_, readBinary + var nodeFS + var nodePath + if (ENVIRONMENT_IS_NODE) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = require('path').dirname(scriptDirectory) + '/' + } else { + scriptDirectory = dirname(getModuleURL(import.meta.url)) + '/' + } + read_ = function shell_read(filename, binary) { + if (!nodeFS) nodeFS = require('fs') + if (!nodePath) nodePath = require('path') + filename = nodePath['normalize'](filename) + return nodeFS['readFileSync'](filename, binary ? null : 'utf8') + } + readBinary = function readBinary(filename) { + var ret = read_(filename, true) + if (!ret.buffer) { + ret = new Uint8Array(ret) + } + assert(ret.buffer) + return ret + } + if (process['argv'].length > 1) { + thisProgram = process['argv'][1].replace(/\\/g, '/') + } + arguments_ = process['argv'].slice(2) + quit_ = function (status) { + process['exit'](status) + } + Module['inspect'] = function () { + return '[Emscripten Module object]' + } + } else { + } + var out = Module['print'] || console.log.bind(console) + var err = Module['printErr'] || console.warn.bind(console) + for (key in moduleOverrides) { + if (moduleOverrides.hasOwnProperty(key)) { + Module[key] = moduleOverrides[key] + } + } + moduleOverrides = null + if (Module['arguments']) arguments_ = Module['arguments'] + if (Module['thisProgram']) thisProgram = Module['thisProgram'] + if (Module['quit']) quit_ = Module['quit'] + var tempRet0 = 0 + var setTempRet0 = function (value) { + tempRet0 = value + } + var getTempRet0 = function () { + return tempRet0 + } + var wasmBinary + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'] + var noExitRuntime = Module['noExitRuntime'] || true + if (typeof WebAssembly !== 'object') { + abort('no native wasm support detected') + } + var wasmMemory + var ABORT = false + var EXITSTATUS + function assert(condition, text) { + if (!condition) { + abort('Assertion failed: ' + text) + } + } + var UTF8Decoder = new TextDecoder('utf8') + function UTF8ArrayToString(heap, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead + var endPtr = idx + while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr + return UTF8Decoder.decode( + heap.subarray + ? heap.subarray(idx, endPtr) + : new Uint8Array(heap.slice(idx, endPtr)) + ) + } + function UTF8ToString(ptr, maxBytesToRead) { + if (!ptr) return '' + var maxPtr = ptr + maxBytesToRead + for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)) + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) return 0 + var startIdx = outIdx + var endIdx = outIdx + maxBytesToWrite - 1 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i) + u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) + } + if (u <= 127) { + if (outIdx >= endIdx) break + heap[outIdx++] = u + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break + heap[outIdx++] = 192 | (u >> 6) + heap[outIdx++] = 128 | (u & 63) + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break + heap[outIdx++] = 224 | (u >> 12) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } else { + if (outIdx + 3 >= endIdx) break + heap[outIdx++] = 240 | (u >> 18) + heap[outIdx++] = 128 | ((u >> 12) & 63) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } + } + heap[outIdx] = 0 + return outIdx - startIdx + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) + } + function lengthBytesUTF8(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) + u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) + if (u <= 127) ++len + else if (u <= 2047) len += 2 + else if (u <= 65535) len += 3 + else len += 4 + } + return len + } + var UTF16Decoder = new TextDecoder('utf-16le') + function UTF16ToString(ptr, maxBytesToRead) { + var endPtr = ptr + var idx = endPtr >> 1 + var maxIdx = idx + maxBytesToRead / 2 + while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx + endPtr = idx << 1 + return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)) + var str = '' + for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { + var codeUnit = HEAP16[(ptr + i * 2) >> 1] + if (codeUnit == 0) break + str += String.fromCharCode(codeUnit) + } + return str + } + function stringToUTF16(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 2) return 0 + maxBytesToWrite -= 2 + var startPtr = outPtr + var numCharsToWrite = + maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i) + HEAP16[outPtr >> 1] = codeUnit + outPtr += 2 + } + HEAP16[outPtr >> 1] = 0 + return outPtr - startPtr + } + function lengthBytesUTF16(str) { + return str.length * 2 + } + function UTF32ToString(ptr, maxBytesToRead) { + var i = 0 + var str = '' + while (!(i >= maxBytesToRead / 4)) { + var utf32 = HEAP32[(ptr + i * 4) >> 2] + if (utf32 == 0) break + ++i + if (utf32 >= 65536) { + var ch = utf32 - 65536 + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) + } else { + str += String.fromCharCode(utf32) + } + } + return str + } + function stringToUTF32(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 4) return 0 + var startPtr = outPtr + var endPtr = startPtr + maxBytesToWrite - 4 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) { + var trailSurrogate = str.charCodeAt(++i) + codeUnit = + (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023) + } + HEAP32[outPtr >> 2] = codeUnit + outPtr += 4 + if (outPtr + 4 > endPtr) break + } + HEAP32[outPtr >> 2] = 0 + return outPtr - startPtr + } + function lengthBytesUTF32(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) ++i + len += 4 + } + return len + } + function alignUp(x, multiple) { + if (x % multiple > 0) { + x += multiple - (x % multiple) + } + return x + } + var buffer, + HEAP8, + HEAPU8, + HEAP16, + HEAPU16, + HEAP32, + HEAPU32, + HEAPF32, + HEAPF64 + function updateGlobalBufferAndViews(buf) { + buffer = buf + Module['HEAP8'] = HEAP8 = new Int8Array(buf) + Module['HEAP16'] = HEAP16 = new Int16Array(buf) + Module['HEAP32'] = HEAP32 = new Int32Array(buf) + Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf) + Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf) + Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf) + Module['HEAPF32'] = HEAPF32 = new Float32Array(buf) + Module['HEAPF64'] = HEAPF64 = new Float64Array(buf) + } + var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 + var wasmTable + var __ATPRERUN__ = [] + var __ATINIT__ = [] + var __ATPOSTRUN__ = [] + var runtimeInitialized = false + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') + Module['preRun'] = [Module['preRun']] + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()) + } + } + callRuntimeCallbacks(__ATPRERUN__) + } + function initRuntime() { + runtimeInitialized = true + callRuntimeCallbacks(__ATINIT__) + } + function postRun() { + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') + Module['postRun'] = [Module['postRun']] + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()) + } + } + callRuntimeCallbacks(__ATPOSTRUN__) + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb) + } + function addOnInit(cb) { + __ATINIT__.unshift(cb) + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb) + } + var runDependencies = 0 + var runDependencyWatcher = null + var dependenciesFulfilled = null + function addRunDependency(id) { + runDependencies++ + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + } + function removeRunDependency(id) { + runDependencies-- + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher) + runDependencyWatcher = null + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled + dependenciesFulfilled = null + callback() + } + } + } + Module['preloadedImages'] = {} + Module['preloadedAudios'] = {} + function abort(what) { + if (Module['onAbort']) { + Module['onAbort'](what) + } + what += '' + err(what) + ABORT = true + EXITSTATUS = 1 + what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' + var e = new WebAssembly.RuntimeError(what) + readyPromiseReject(e) + throw e + } + var dataURIPrefix = 'data:application/octet-stream;base64,' + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix) + } + if (Module['locateFile']) { + var wasmBinaryFile = 'avif_node_dec.wasm' + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile) + } + } else { + throw new Error('invariant') + } + function getBinary(file) { + try { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary) + } + if (readBinary) { + return readBinary(file) + } else { + throw 'both async and sync fetching of the wasm failed' + } + } catch (err) { + abort(err) + } + } + function getBinaryPromise() { + return Promise.resolve().then(function () { + return getBinary(wasmBinaryFile) + }) + } + function createWasm() { + var info = { a: asmLibraryArg } + function receiveInstance(instance, module) { + var exports = instance.exports + Module['asm'] = exports + wasmMemory = Module['asm']['C'] + updateGlobalBufferAndViews(wasmMemory.buffer) + wasmTable = Module['asm']['L'] + addOnInit(Module['asm']['D']) + removeRunDependency('wasm-instantiate') + } + addRunDependency('wasm-instantiate') + function receiveInstantiationResult(result) { + receiveInstance(result['instance']) + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise() + .then(function (binary) { + var result = WebAssembly.instantiate(binary, info) + return result + }) + .then(receiver, function (reason) { + err('failed to asynchronously prepare wasm: ' + reason) + abort(reason) + }) + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult) + } + if (Module['instantiateWasm']) { + try { + var exports = Module['instantiateWasm'](info, receiveInstance) + return exports + } catch (e) { + err('Module.instantiateWasm callback failed with error: ' + e) + return false + } + } + instantiateAsync().catch(readyPromiseReject) + return {} + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + var callback = callbacks.shift() + if (typeof callback == 'function') { + callback(Module) + continue + } + var func = callback.func + if (typeof func === 'number') { + if (callback.arg === undefined) { + wasmTable.get(func)() + } else { + wasmTable.get(func)(callback.arg) + } + } else { + func(callback.arg === undefined ? null : callback.arg) + } + } + } + function _atexit(func, arg) {} + function ___cxa_thread_atexit(a0, a1) { + return _atexit(a0, a1) + } + function __embind_register_bigint( + primitiveType, + name, + size, + minRange, + maxRange + ) {} + function getShiftFromSize(size) { + switch (size) { + case 1: + return 0 + case 2: + return 1 + case 4: + return 2 + case 8: + return 3 + default: + throw new TypeError('Unknown type size: ' + size) + } + } + function embind_init_charCodes() { + var codes = new Array(256) + for (var i = 0; i < 256; ++i) { + codes[i] = String.fromCharCode(i) + } + embind_charCodes = codes + } + var embind_charCodes = undefined + function readLatin1String(ptr) { + var ret = '' + var c = ptr + while (HEAPU8[c]) { + ret += embind_charCodes[HEAPU8[c++]] + } + return ret + } + var awaitingDependencies = {} + var registeredTypes = {} + var typeDependencies = {} + var char_0 = 48 + var char_9 = 57 + function makeLegalFunctionName(name) { + if (undefined === name) { + return '_unknown' + } + name = name.replace(/[^a-zA-Z0-9_]/g, '$') + var f = name.charCodeAt(0) + if (f >= char_0 && f <= char_9) { + return '_' + name + } else { + return name + } + } + function createNamedFunction(name, body) { + name = makeLegalFunctionName(name) + return new Function( + 'body', + 'return function ' + + name + + '() {\n' + + ' "use strict";' + + ' return body.apply(this, arguments);\n' + + '};\n' + )(body) + } + function extendError(baseErrorType, errorName) { + var errorClass = createNamedFunction(errorName, function (message) { + this.name = errorName + this.message = message + var stack = new Error(message).stack + if (stack !== undefined) { + this.stack = + this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '') + } + }) + errorClass.prototype = Object.create(baseErrorType.prototype) + errorClass.prototype.constructor = errorClass + errorClass.prototype.toString = function () { + if (this.message === undefined) { + return this.name + } else { + return this.name + ': ' + this.message + } + } + return errorClass + } + var BindingError = undefined + function throwBindingError(message) { + throw new BindingError(message) + } + var InternalError = undefined + function throwInternalError(message) { + throw new InternalError(message) + } + function whenDependentTypesAreResolved( + myTypes, + dependentTypes, + getTypeConverters + ) { + myTypes.forEach(function (type) { + typeDependencies[type] = dependentTypes + }) + function onComplete(typeConverters) { + var myTypeConverters = getTypeConverters(typeConverters) + if (myTypeConverters.length !== myTypes.length) { + throwInternalError('Mismatched type converter count') + } + for (var i = 0; i < myTypes.length; ++i) { + registerType(myTypes[i], myTypeConverters[i]) + } + } + var typeConverters = new Array(dependentTypes.length) + var unregisteredTypes = [] + var registered = 0 + dependentTypes.forEach(function (dt, i) { + if (registeredTypes.hasOwnProperty(dt)) { + typeConverters[i] = registeredTypes[dt] + } else { + unregisteredTypes.push(dt) + if (!awaitingDependencies.hasOwnProperty(dt)) { + awaitingDependencies[dt] = [] + } + awaitingDependencies[dt].push(function () { + typeConverters[i] = registeredTypes[dt] + ++registered + if (registered === unregisteredTypes.length) { + onComplete(typeConverters) + } + }) + } + }) + if (0 === unregisteredTypes.length) { + onComplete(typeConverters) + } + } + function registerType(rawType, registeredInstance, options) { + options = options || {} + if (!('argPackAdvance' in registeredInstance)) { + throw new TypeError( + 'registerType registeredInstance requires argPackAdvance' + ) + } + var name = registeredInstance.name + if (!rawType) { + throwBindingError( + 'type "' + name + '" must have a positive integer typeid pointer' + ) + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return + } else { + throwBindingError("Cannot register type '" + name + "' twice") + } + } + registeredTypes[rawType] = registeredInstance + delete typeDependencies[rawType] + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType] + delete awaitingDependencies[rawType] + callbacks.forEach(function (cb) { + cb() + }) + } + } + function __embind_register_bool( + rawType, + name, + size, + trueValue, + falseValue + ) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (wt) { + return !!wt + }, + toWireType: function (destructors, o) { + return o ? trueValue : falseValue + }, + argPackAdvance: 8, + readValueFromPointer: function (pointer) { + var heap + if (size === 1) { + heap = HEAP8 + } else if (size === 2) { + heap = HEAP16 + } else if (size === 4) { + heap = HEAP32 + } else { + throw new TypeError('Unknown boolean type size: ' + name) + } + return this['fromWireType'](heap[pointer >> shift]) + }, + destructorFunction: null, + }) + } + var emval_free_list = [] + var emval_handle_array = [ + {}, + { value: undefined }, + { value: null }, + { value: true }, + { value: false }, + ] + function __emval_decref(handle) { + if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { + emval_handle_array[handle] = undefined + emval_free_list.push(handle) + } + } + function count_emval_handles() { + var count = 0 + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + ++count + } + } + return count + } + function get_first_emval() { + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + return emval_handle_array[i] + } + } + return null + } + function init_emval() { + Module['count_emval_handles'] = count_emval_handles + Module['get_first_emval'] = get_first_emval + } + function __emval_register(value) { + switch (value) { + case undefined: { + return 1 + } + case null: { + return 2 + } + case true: { + return 3 + } + case false: { + return 4 + } + default: { + var handle = emval_free_list.length + ? emval_free_list.pop() + : emval_handle_array.length + emval_handle_array[handle] = { refcount: 1, value: value } + return handle + } + } + } + function simpleReadValueFromPointer(pointer) { + return this['fromWireType'](HEAPU32[pointer >> 2]) + } + function __embind_register_emval(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (handle) { + var rv = emval_handle_array[handle].value + __emval_decref(handle) + return rv + }, + toWireType: function (destructors, value) { + return __emval_register(value) + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: null, + }) + } + function _embind_repr(v) { + if (v === null) { + return 'null' + } + var t = typeof v + if (t === 'object' || t === 'array' || t === 'function') { + return v.toString() + } else { + return '' + v + } + } + function floatReadValueFromPointer(name, shift) { + switch (shift) { + case 2: + return function (pointer) { + return this['fromWireType'](HEAPF32[pointer >> 2]) + } + case 3: + return function (pointer) { + return this['fromWireType'](HEAPF64[pointer >> 3]) + } + default: + throw new TypeError('Unknown float type: ' + name) + } + } + function __embind_register_float(rawType, name, size) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (value) { + return value + }, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + return value + }, + argPackAdvance: 8, + readValueFromPointer: floatReadValueFromPointer(name, shift), + destructorFunction: null, + }) + } + function new_(constructor, argumentList) { + if (!(constructor instanceof Function)) { + throw new TypeError( + 'new_ called with constructor type ' + + typeof constructor + + ' which is not a function' + ) + } + var dummy = createNamedFunction( + constructor.name || 'unknownFunctionName', + function () {} + ) + dummy.prototype = constructor.prototype + var obj = new dummy() + var r = constructor.apply(obj, argumentList) + return r instanceof Object ? r : obj + } + function runDestructors(destructors) { + while (destructors.length) { + var ptr = destructors.pop() + var del = destructors.pop() + del(ptr) + } + } + function craftInvokerFunction( + humanName, + argTypes, + classType, + cppInvokerFunc, + cppTargetFunc + ) { + var argCount = argTypes.length + if (argCount < 2) { + throwBindingError( + "argTypes array size mismatch! Must at least get return value and 'this' types!" + ) + } + var isClassMethodFunc = argTypes[1] !== null && classType !== null + var needsDestructorStack = false + for (var i = 1; i < argTypes.length; ++i) { + if ( + argTypes[i] !== null && + argTypes[i].destructorFunction === undefined + ) { + needsDestructorStack = true + break + } + } + var returns = argTypes[0].name !== 'void' + var argsList = '' + var argsListWired = '' + for (var i = 0; i < argCount - 2; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired' + } + var invokerFnBody = + 'return function ' + + makeLegalFunctionName(humanName) + + '(' + + argsList + + ') {\n' + + 'if (arguments.length !== ' + + (argCount - 2) + + ') {\n' + + "throwBindingError('function " + + humanName + + " called with ' + arguments.length + ' arguments, expected " + + (argCount - 2) + + " args!');\n" + + '}\n' + if (needsDestructorStack) { + invokerFnBody += 'var destructors = [];\n' + } + var dtorStack = needsDestructorStack ? 'destructors' : 'null' + var args1 = [ + 'throwBindingError', + 'invoker', + 'fn', + 'runDestructors', + 'retType', + 'classParam', + ] + var args2 = [ + throwBindingError, + cppInvokerFunc, + cppTargetFunc, + runDestructors, + argTypes[0], + argTypes[1], + ] + if (isClassMethodFunc) { + invokerFnBody += + 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n' + } + for (var i = 0; i < argCount - 2; ++i) { + invokerFnBody += + 'var arg' + + i + + 'Wired = argType' + + i + + '.toWireType(' + + dtorStack + + ', arg' + + i + + '); // ' + + argTypes[i + 2].name + + '\n' + args1.push('argType' + i) + args2.push(argTypes[i + 2]) + } + if (isClassMethodFunc) { + argsListWired = + 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired + } + invokerFnBody += + (returns ? 'var rv = ' : '') + + 'invoker(fn' + + (argsListWired.length > 0 ? ', ' : '') + + argsListWired + + ');\n' + if (needsDestructorStack) { + invokerFnBody += 'runDestructors(destructors);\n' + } else { + for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { + var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired' + if (argTypes[i].destructorFunction !== null) { + invokerFnBody += + paramName + + '_dtor(' + + paramName + + '); // ' + + argTypes[i].name + + '\n' + args1.push(paramName + '_dtor') + args2.push(argTypes[i].destructorFunction) + } + } + } + if (returns) { + invokerFnBody += + 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n' + } else { + } + invokerFnBody += '}\n' + args1.push(invokerFnBody) + var invokerFunction = new_(Function, args1).apply(null, args2) + return invokerFunction + } + function ensureOverloadTable(proto, methodName, humanName) { + if (undefined === proto[methodName].overloadTable) { + var prevFunc = proto[methodName] + proto[methodName] = function () { + if ( + !proto[methodName].overloadTable.hasOwnProperty(arguments.length) + ) { + throwBindingError( + "Function '" + + humanName + + "' called with an invalid number of arguments (" + + arguments.length + + ') - expects one of (' + + proto[methodName].overloadTable + + ')!' + ) + } + return proto[methodName].overloadTable[arguments.length].apply( + this, + arguments + ) + } + proto[methodName].overloadTable = [] + proto[methodName].overloadTable[prevFunc.argCount] = prevFunc + } + } + function exposePublicSymbol(name, value, numArguments) { + if (Module.hasOwnProperty(name)) { + if ( + undefined === numArguments || + (undefined !== Module[name].overloadTable && + undefined !== Module[name].overloadTable[numArguments]) + ) { + throwBindingError("Cannot register public name '" + name + "' twice") + } + ensureOverloadTable(Module, name, name) + if (Module.hasOwnProperty(numArguments)) { + throwBindingError( + 'Cannot register multiple overloads of a function with the same number of arguments (' + + numArguments + + ')!' + ) + } + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + if (undefined !== numArguments) { + Module[name].numArguments = numArguments + } + } + } + function heap32VectorToArray(count, firstElement) { + var array = [] + for (var i = 0; i < count; i++) { + array.push(HEAP32[(firstElement >> 2) + i]) + } + return array + } + function replacePublicSymbol(name, value, numArguments) { + if (!Module.hasOwnProperty(name)) { + throwInternalError('Replacing nonexistent public symbol') + } + if ( + undefined !== Module[name].overloadTable && + undefined !== numArguments + ) { + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + Module[name].argCount = numArguments + } + } + function dynCallLegacy(sig, ptr, args) { + var f = Module['dynCall_' + sig] + return args && args.length + ? f.apply(null, [ptr].concat(args)) + : f.call(null, ptr) + } + function dynCall(sig, ptr, args) { + if (sig.includes('j')) { + return dynCallLegacy(sig, ptr, args) + } + return wasmTable.get(ptr).apply(null, args) + } + function getDynCaller(sig, ptr) { + var argCache = [] + return function () { + argCache.length = arguments.length + for (var i = 0; i < arguments.length; i++) { + argCache[i] = arguments[i] + } + return dynCall(sig, ptr, argCache) + } + } + function embind__requireFunction(signature, rawFunction) { + signature = readLatin1String(signature) + function makeDynCaller() { + if (signature.includes('j')) { + return getDynCaller(signature, rawFunction) + } + return wasmTable.get(rawFunction) + } + var fp = makeDynCaller() + if (typeof fp !== 'function') { + throwBindingError( + 'unknown function pointer with signature ' + + signature + + ': ' + + rawFunction + ) + } + return fp + } + var UnboundTypeError = undefined + function getTypeName(type) { + var ptr = ___getTypeName(type) + var rv = readLatin1String(ptr) + _free(ptr) + return rv + } + function throwUnboundTypeError(message, types) { + var unboundTypes = [] + var seen = {} + function visit(type) { + if (seen[type]) { + return + } + if (registeredTypes[type]) { + return + } + if (typeDependencies[type]) { + typeDependencies[type].forEach(visit) + return + } + unboundTypes.push(type) + seen[type] = true + } + types.forEach(visit) + throw new UnboundTypeError( + message + ': ' + unboundTypes.map(getTypeName).join([', ']) + ) + } + function __embind_register_function( + name, + argCount, + rawArgTypesAddr, + signature, + rawInvoker, + fn + ) { + var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr) + name = readLatin1String(name) + rawInvoker = embind__requireFunction(signature, rawInvoker) + exposePublicSymbol( + name, + function () { + throwUnboundTypeError( + 'Cannot call ' + name + ' due to unbound types', + argTypes + ) + }, + argCount - 1 + ) + whenDependentTypesAreResolved([], argTypes, function (argTypes) { + var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1)) + replacePublicSymbol( + name, + craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn), + argCount - 1 + ) + return [] + }) + } + function integerReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return signed + ? function readS8FromPointer(pointer) { + return HEAP8[pointer] + } + : function readU8FromPointer(pointer) { + return HEAPU8[pointer] + } + case 1: + return signed + ? function readS16FromPointer(pointer) { + return HEAP16[pointer >> 1] + } + : function readU16FromPointer(pointer) { + return HEAPU16[pointer >> 1] + } + case 2: + return signed + ? function readS32FromPointer(pointer) { + return HEAP32[pointer >> 2] + } + : function readU32FromPointer(pointer) { + return HEAPU32[pointer >> 2] + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_integer( + primitiveType, + name, + size, + minRange, + maxRange + ) { + name = readLatin1String(name) + if (maxRange === -1) { + maxRange = 4294967295 + } + var shift = getShiftFromSize(size) + var fromWireType = function (value) { + return value + } + if (minRange === 0) { + var bitshift = 32 - 8 * size + fromWireType = function (value) { + return (value << bitshift) >>> bitshift + } + } + var isUnsignedType = name.includes('unsigned') + registerType(primitiveType, { + name: name, + fromWireType: fromWireType, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + if (value < minRange || value > maxRange) { + throw new TypeError( + 'Passing a number "' + + _embind_repr(value) + + '" from JS side to C/C++ side to an argument of type "' + + name + + '", which is outside the valid range [' + + minRange + + ', ' + + maxRange + + ']!' + ) + } + return isUnsignedType ? value >>> 0 : value | 0 + }, + argPackAdvance: 8, + readValueFromPointer: integerReadValueFromPointer( + name, + shift, + minRange !== 0 + ), + destructorFunction: null, + }) + } + function __embind_register_memory_view(rawType, dataTypeIndex, name) { + var typeMapping = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + ] + var TA = typeMapping[dataTypeIndex] + function decodeMemoryView(handle) { + handle = handle >> 2 + var heap = HEAPU32 + var size = heap[handle] + var data = heap[handle + 1] + return new TA(buffer, data, size) + } + name = readLatin1String(name) + registerType( + rawType, + { + name: name, + fromWireType: decodeMemoryView, + argPackAdvance: 8, + readValueFromPointer: decodeMemoryView, + }, + { ignoreDuplicateRegistrations: true } + ) + } + function __embind_register_std_string(rawType, name) { + name = readLatin1String(name) + var stdStringIsUTF8 = name === 'std::string' + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var str + if (stdStringIsUTF8) { + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i + if (i == length || HEAPU8[currentBytePtr] == 0) { + var maxRead = currentBytePtr - decodeStartPtr + var stringSegment = UTF8ToString(decodeStartPtr, maxRead) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + 1 + } + } + } else { + var a = new Array(length) + for (var i = 0; i < length; ++i) { + a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) + } + str = a.join('') + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value) + } + var getLength + var valueIsOfTypeString = typeof value === 'string' + if ( + !( + valueIsOfTypeString || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int8Array + ) + ) { + throwBindingError('Cannot pass non-string to std::string') + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + getLength = function () { + return lengthBytesUTF8(value) + } + } else { + getLength = function () { + return value.length + } + } + var length = getLength() + var ptr = _malloc(4 + length + 1) + HEAPU32[ptr >> 2] = length + if (stdStringIsUTF8 && valueIsOfTypeString) { + stringToUTF8(value, ptr + 4, length + 1) + } else { + if (valueIsOfTypeString) { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i) + if (charCode > 255) { + _free(ptr) + throwBindingError( + 'String has UTF-16 code units that do not fit in 8 bits' + ) + } + HEAPU8[ptr + 4 + i] = charCode + } + } else { + for (var i = 0; i < length; ++i) { + HEAPU8[ptr + 4 + i] = value[i] + } + } + } + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_std_wstring(rawType, charSize, name) { + name = readLatin1String(name) + var decodeString, encodeString, getHeap, lengthBytesUTF, shift + if (charSize === 2) { + decodeString = UTF16ToString + encodeString = stringToUTF16 + lengthBytesUTF = lengthBytesUTF16 + getHeap = function () { + return HEAPU16 + } + shift = 1 + } else if (charSize === 4) { + decodeString = UTF32ToString + encodeString = stringToUTF32 + lengthBytesUTF = lengthBytesUTF32 + getHeap = function () { + return HEAPU32 + } + shift = 2 + } + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var HEAP = getHeap() + var str + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i * charSize + if (i == length || HEAP[currentBytePtr >> shift] == 0) { + var maxReadBytes = currentBytePtr - decodeStartPtr + var stringSegment = decodeString(decodeStartPtr, maxReadBytes) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + charSize + } + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (!(typeof value === 'string')) { + throwBindingError( + 'Cannot pass non-string to C++ string type ' + name + ) + } + var length = lengthBytesUTF(value) + var ptr = _malloc(4 + length + charSize) + HEAPU32[ptr >> 2] = length >> shift + encodeString(value, ptr + 4, length + charSize) + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_void(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + isVoid: true, + name: name, + argPackAdvance: 0, + fromWireType: function () { + return undefined + }, + toWireType: function (destructors, o) { + return undefined + }, + }) + } + var emval_symbols = {} + function getStringOrSymbol(address) { + var symbol = emval_symbols[address] + if (symbol === undefined) { + return readLatin1String(address) + } else { + return symbol + } + } + function emval_get_global() { + if (typeof globalThis === 'object') { + return globalThis + } + return (function () { + return Function + })()('return this')() + } + function __emval_get_global(name) { + if (name === 0) { + return __emval_register(emval_get_global()) + } else { + name = getStringOrSymbol(name) + return __emval_register(emval_get_global()[name]) + } + } + function __emval_incref(handle) { + if (handle > 4) { + emval_handle_array[handle].refcount += 1 + } + } + function requireRegisteredType(rawType, humanName) { + var impl = registeredTypes[rawType] + if (undefined === impl) { + throwBindingError( + humanName + ' has unknown type ' + getTypeName(rawType) + ) + } + return impl + } + function craftEmvalAllocator(argCount) { + var argsList = '' + for (var i = 0; i < argCount; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + } + var functionBody = + 'return function emval_allocator_' + + argCount + + '(constructor, argTypes, args) {\n' + for (var i = 0; i < argCount; ++i) { + functionBody += + 'var argType' + + i + + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + + i + + '], "parameter ' + + i + + '");\n' + + 'var arg' + + i + + ' = argType' + + i + + '.readValueFromPointer(args);\n' + + 'args += argType' + + i + + "['argPackAdvance'];\n" + } + functionBody += + 'var obj = new constructor(' + + argsList + + ');\n' + + 'return __emval_register(obj);\n' + + '}\n' + return new Function( + 'requireRegisteredType', + 'Module', + '__emval_register', + functionBody + )(requireRegisteredType, Module, __emval_register) + } + var emval_newers = {} + function requireHandle(handle) { + if (!handle) { + throwBindingError('Cannot use deleted val. handle = ' + handle) + } + return emval_handle_array[handle].value + } + function __emval_new(handle, argCount, argTypes, args) { + handle = requireHandle(handle) + var newer = emval_newers[argCount] + if (!newer) { + newer = craftEmvalAllocator(argCount) + emval_newers[argCount] = newer + } + return newer(handle, argTypes, args) + } + function _abort() { + abort() + } + function _longjmp(env, value) { + _setThrew(env, value || 1) + throw 'longjmp' + } + function _emscripten_longjmp(a0, a1) { + return _longjmp(a0, a1) + } + function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.copyWithin(dest, src, src + num) + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16) + updateGlobalBufferAndViews(wasmMemory.buffer) + return 1 + } catch (e) {} + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length + requestedSize = requestedSize >>> 0 + var maxHeapSize = 2147483648 + if (requestedSize > maxHeapSize) { + return false + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown) + overGrownHeapSize = Math.min( + overGrownHeapSize, + requestedSize + 100663296 + ) + var newSize = Math.min( + maxHeapSize, + alignUp(Math.max(requestedSize, overGrownHeapSize), 65536) + ) + var replacement = emscripten_realloc_buffer(newSize) + if (replacement) { + return true + } + } + return false + } + var SYSCALLS = { + mappings: {}, + buffers: [null, [], []], + printChar: function (stream, curr) { + var buffer = SYSCALLS.buffers[stream] + if (curr === 0 || curr === 10) { + ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)) + buffer.length = 0 + } else { + buffer.push(curr) + } + }, + varargs: undefined, + get: function () { + SYSCALLS.varargs += 4 + var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2] + return ret + }, + getStr: function (ptr) { + var ret = UTF8ToString(ptr) + return ret + }, + get64: function (low, high) { + return low + }, + } + function _fd_close(fd) { + return 0 + } + function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {} + function _fd_write(fd, iov, iovcnt, pnum) { + var num = 0 + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAP32[(iov + i * 8) >> 2] + var len = HEAP32[(iov + (i * 8 + 4)) >> 2] + for (var j = 0; j < len; j++) { + SYSCALLS.printChar(fd, HEAPU8[ptr + j]) + } + num += len + } + HEAP32[pnum >> 2] = num + return 0 + } + function _getTempRet0() { + return getTempRet0() + } + function _setTempRet0(val) { + setTempRet0(val) + } + embind_init_charCodes() + BindingError = Module['BindingError'] = extendError(Error, 'BindingError') + InternalError = Module['InternalError'] = extendError( + Error, + 'InternalError' + ) + init_emval() + UnboundTypeError = Module['UnboundTypeError'] = extendError( + Error, + 'UnboundTypeError' + ) + var asmLibraryArg = { + j: ___cxa_thread_atexit, + v: __embind_register_bigint, + r: __embind_register_bool, + B: __embind_register_emval, + q: __embind_register_float, + t: __embind_register_function, + e: __embind_register_integer, + d: __embind_register_memory_view, + m: __embind_register_std_string, + l: __embind_register_std_wstring, + s: __embind_register_void, + h: __emval_decref, + i: __emval_get_global, + n: __emval_incref, + o: __emval_new, + a: _abort, + g: _emscripten_longjmp, + y: _emscripten_memcpy_big, + k: _emscripten_resize_heap, + A: _fd_close, + u: _fd_seek, + z: _fd_write, + b: _getTempRet0, + f: invoke_iii, + w: invoke_iiiii, + p: invoke_viiii, + x: invoke_viiiiiii, + c: _setTempRet0, + } + var asm = createWasm() + var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () { + return (___wasm_call_ctors = Module['___wasm_call_ctors'] = + Module['asm']['D']).apply(null, arguments) + }) + var _malloc = (Module['_malloc'] = function () { + return (_malloc = Module['_malloc'] = Module['asm']['E']).apply( + null, + arguments + ) + }) + var _free = (Module['_free'] = function () { + return (_free = Module['_free'] = Module['asm']['F']).apply( + null, + arguments + ) + }) + var ___getTypeName = (Module['___getTypeName'] = function () { + return (___getTypeName = Module['___getTypeName'] = + Module['asm']['G']).apply(null, arguments) + }) + var ___embind_register_native_and_builtin_types = (Module[ + '___embind_register_native_and_builtin_types' + ] = function () { + return (___embind_register_native_and_builtin_types = Module[ + '___embind_register_native_and_builtin_types' + ] = + Module['asm']['H']).apply(null, arguments) + }) + var stackSave = (Module['stackSave'] = function () { + return (stackSave = Module['stackSave'] = Module['asm']['I']).apply( + null, + arguments + ) + }) + var stackRestore = (Module['stackRestore'] = function () { + return (stackRestore = Module['stackRestore'] = Module['asm']['J']).apply( + null, + arguments + ) + }) + var _setThrew = (Module['_setThrew'] = function () { + return (_setThrew = Module['_setThrew'] = Module['asm']['K']).apply( + null, + arguments + ) + }) + var dynCall_iiijii = (Module['dynCall_iiijii'] = function () { + return (dynCall_iiijii = Module['dynCall_iiijii'] = + Module['asm']['M']).apply(null, arguments) + }) + var dynCall_jiji = (Module['dynCall_jiji'] = function () { + return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['N']).apply( + null, + arguments + ) + }) + function invoke_viiiiiii(index, a1, a2, a3, a4, a5, a6, a7) { + var sp = stackSave() + try { + wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_viiii(index, a1, a2, a3, a4) { + var sp = stackSave() + try { + wasmTable.get(index)(a1, a2, a3, a4) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_iii(index, a1, a2) { + var sp = stackSave() + try { + return wasmTable.get(index)(a1, a2) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_iiiii(index, a1, a2, a3, a4) { + var sp = stackSave() + try { + return wasmTable.get(index)(a1, a2, a3, a4) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + var calledRun + dependenciesFulfilled = function runCaller() { + if (!calledRun) run() + if (!calledRun) dependenciesFulfilled = runCaller + } + function run(args) { + args = args || arguments_ + if (runDependencies > 0) { + return + } + preRun() + if (runDependencies > 0) { + return + } + function doRun() { + if (calledRun) return + calledRun = true + Module['calledRun'] = true + if (ABORT) return + initRuntime() + readyPromiseResolve(Module) + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() + postRun() + } + if (Module['setStatus']) { + Module['setStatus']('Running...') + setTimeout(function () { + setTimeout(function () { + Module['setStatus']('') + }, 1) + doRun() + }, 1) + } else { + doRun() + } + } + Module['run'] = run + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') + Module['preInit'] = [Module['preInit']] + while (Module['preInit'].length > 0) { + Module['preInit'].pop()() + } + } + run() + + return Module.ready + } +})() +export default Module diff --git a/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_dec.wasm b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_dec.wasm new file mode 100644 index 000000000000..1cd4e1b034e1 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_dec.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_enc.ts b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_enc.ts new file mode 100644 index 000000000000..933d1a7c90b7 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_enc.ts @@ -0,0 +1,2032 @@ +/* eslint-disable */ +// @ts-nocheck +import { createRequire } from 'module'; +import { dirname, getModuleURL } from '../emscripten-utils.js'; +const require = createRequire(getModuleURL(import.meta.url)); + +var Module = (function () { + return function (Module) { + Module = Module || {} + + var Module = typeof Module !== 'undefined' ? Module : {} + var readyPromiseResolve, readyPromiseReject + Module['ready'] = new Promise(function (resolve, reject) { + readyPromiseResolve = resolve + readyPromiseReject = reject + }) + var moduleOverrides = {} + var key + for (key in Module) { + if (Module.hasOwnProperty(key)) { + moduleOverrides[key] = Module[key] + } + } + var arguments_ = [] + var thisProgram = './this.program' + var quit_ = function (status, toThrow) { + throw toThrow + } + var ENVIRONMENT_IS_WEB = false + var ENVIRONMENT_IS_WORKER = false + var ENVIRONMENT_IS_NODE = true + var scriptDirectory = '' + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory) + } + return scriptDirectory + path + } + var read_, readBinary + var nodeFS + var nodePath + if (ENVIRONMENT_IS_NODE) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = require('path').dirname(scriptDirectory) + '/' + } else { + scriptDirectory = dirname(getModuleURL(import.meta.url)) + '/' + } + read_ = function shell_read(filename, binary) { + if (!nodeFS) nodeFS = require('fs') + if (!nodePath) nodePath = require('path') + filename = nodePath['normalize'](filename) + return nodeFS['readFileSync'](filename, binary ? null : 'utf8') + } + readBinary = function readBinary(filename) { + var ret = read_(filename, true) + if (!ret.buffer) { + ret = new Uint8Array(ret) + } + assert(ret.buffer) + return ret + } + if (process['argv'].length > 1) { + thisProgram = process['argv'][1].replace(/\\/g, '/') + } + arguments_ = process['argv'].slice(2) + quit_ = function (status) { + process['exit'](status) + } + Module['inspect'] = function () { + return '[Emscripten Module object]' + } + } else { + } + var out = Module['print'] || console.log.bind(console) + var err = Module['printErr'] || console.warn.bind(console) + for (key in moduleOverrides) { + if (moduleOverrides.hasOwnProperty(key)) { + Module[key] = moduleOverrides[key] + } + } + moduleOverrides = null + if (Module['arguments']) arguments_ = Module['arguments'] + if (Module['thisProgram']) thisProgram = Module['thisProgram'] + if (Module['quit']) quit_ = Module['quit'] + var tempRet0 = 0 + var setTempRet0 = function (value) { + tempRet0 = value + } + var getTempRet0 = function () { + return tempRet0 + } + var wasmBinary + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'] + var noExitRuntime = Module['noExitRuntime'] || true + if (typeof WebAssembly !== 'object') { + abort('no native wasm support detected') + } + var wasmMemory + var ABORT = false + var EXITSTATUS + function assert(condition, text) { + if (!condition) { + abort('Assertion failed: ' + text) + } + } + var UTF8Decoder = new TextDecoder('utf8') + function UTF8ArrayToString(heap, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead + var endPtr = idx + while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr + return UTF8Decoder.decode( + heap.subarray + ? heap.subarray(idx, endPtr) + : new Uint8Array(heap.slice(idx, endPtr)) + ) + } + function UTF8ToString(ptr, maxBytesToRead) { + if (!ptr) return '' + var maxPtr = ptr + maxBytesToRead + for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)) + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) return 0 + var startIdx = outIdx + var endIdx = outIdx + maxBytesToWrite - 1 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i) + u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) + } + if (u <= 127) { + if (outIdx >= endIdx) break + heap[outIdx++] = u + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break + heap[outIdx++] = 192 | (u >> 6) + heap[outIdx++] = 128 | (u & 63) + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break + heap[outIdx++] = 224 | (u >> 12) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } else { + if (outIdx + 3 >= endIdx) break + heap[outIdx++] = 240 | (u >> 18) + heap[outIdx++] = 128 | ((u >> 12) & 63) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } + } + heap[outIdx] = 0 + return outIdx - startIdx + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) + } + function lengthBytesUTF8(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) + u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) + if (u <= 127) ++len + else if (u <= 2047) len += 2 + else if (u <= 65535) len += 3 + else len += 4 + } + return len + } + var UTF16Decoder = new TextDecoder('utf-16le') + function UTF16ToString(ptr, maxBytesToRead) { + var endPtr = ptr + var idx = endPtr >> 1 + var maxIdx = idx + maxBytesToRead / 2 + while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx + endPtr = idx << 1 + return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)) + var str = '' + for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { + var codeUnit = HEAP16[(ptr + i * 2) >> 1] + if (codeUnit == 0) break + str += String.fromCharCode(codeUnit) + } + return str + } + function stringToUTF16(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 2) return 0 + maxBytesToWrite -= 2 + var startPtr = outPtr + var numCharsToWrite = + maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i) + HEAP16[outPtr >> 1] = codeUnit + outPtr += 2 + } + HEAP16[outPtr >> 1] = 0 + return outPtr - startPtr + } + function lengthBytesUTF16(str) { + return str.length * 2 + } + function UTF32ToString(ptr, maxBytesToRead) { + var i = 0 + var str = '' + while (!(i >= maxBytesToRead / 4)) { + var utf32 = HEAP32[(ptr + i * 4) >> 2] + if (utf32 == 0) break + ++i + if (utf32 >= 65536) { + var ch = utf32 - 65536 + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) + } else { + str += String.fromCharCode(utf32) + } + } + return str + } + function stringToUTF32(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 4) return 0 + var startPtr = outPtr + var endPtr = startPtr + maxBytesToWrite - 4 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) { + var trailSurrogate = str.charCodeAt(++i) + codeUnit = + (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023) + } + HEAP32[outPtr >> 2] = codeUnit + outPtr += 4 + if (outPtr + 4 > endPtr) break + } + HEAP32[outPtr >> 2] = 0 + return outPtr - startPtr + } + function lengthBytesUTF32(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) ++i + len += 4 + } + return len + } + function alignUp(x, multiple) { + if (x % multiple > 0) { + x += multiple - (x % multiple) + } + return x + } + var buffer, + HEAP8, + HEAPU8, + HEAP16, + HEAPU16, + HEAP32, + HEAPU32, + HEAPF32, + HEAPF64 + function updateGlobalBufferAndViews(buf) { + buffer = buf + Module['HEAP8'] = HEAP8 = new Int8Array(buf) + Module['HEAP16'] = HEAP16 = new Int16Array(buf) + Module['HEAP32'] = HEAP32 = new Int32Array(buf) + Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf) + Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf) + Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf) + Module['HEAPF32'] = HEAPF32 = new Float32Array(buf) + Module['HEAPF64'] = HEAPF64 = new Float64Array(buf) + } + var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 + var wasmTable + var __ATPRERUN__ = [] + var __ATINIT__ = [] + var __ATPOSTRUN__ = [] + var runtimeInitialized = false + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') + Module['preRun'] = [Module['preRun']] + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()) + } + } + callRuntimeCallbacks(__ATPRERUN__) + } + function initRuntime() { + runtimeInitialized = true + callRuntimeCallbacks(__ATINIT__) + } + function postRun() { + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') + Module['postRun'] = [Module['postRun']] + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()) + } + } + callRuntimeCallbacks(__ATPOSTRUN__) + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb) + } + function addOnInit(cb) { + __ATINIT__.unshift(cb) + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb) + } + var runDependencies = 0 + var runDependencyWatcher = null + var dependenciesFulfilled = null + function addRunDependency(id) { + runDependencies++ + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + } + function removeRunDependency(id) { + runDependencies-- + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher) + runDependencyWatcher = null + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled + dependenciesFulfilled = null + callback() + } + } + } + Module['preloadedImages'] = {} + Module['preloadedAudios'] = {} + function abort(what) { + if (Module['onAbort']) { + Module['onAbort'](what) + } + what += '' + err(what) + ABORT = true + EXITSTATUS = 1 + what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' + var e = new WebAssembly.RuntimeError(what) + readyPromiseReject(e) + throw e + } + var dataURIPrefix = 'data:application/octet-stream;base64,' + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix) + } + if (Module['locateFile']) { + var wasmBinaryFile = 'avif_node_enc.wasm' + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile) + } + } else { + throw new Error('invariant') + } + function getBinary(file) { + try { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary) + } + if (readBinary) { + return readBinary(file) + } else { + throw 'both async and sync fetching of the wasm failed' + } + } catch (err) { + abort(err) + } + } + function getBinaryPromise() { + return Promise.resolve().then(function () { + return getBinary(wasmBinaryFile) + }) + } + function createWasm() { + var info = { a: asmLibraryArg } + function receiveInstance(instance, module) { + var exports = instance.exports + Module['asm'] = exports + wasmMemory = Module['asm']['P'] + updateGlobalBufferAndViews(wasmMemory.buffer) + wasmTable = Module['asm']['Y'] + addOnInit(Module['asm']['Q']) + removeRunDependency('wasm-instantiate') + } + addRunDependency('wasm-instantiate') + function receiveInstantiationResult(result) { + receiveInstance(result['instance']) + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise() + .then(function (binary) { + var result = WebAssembly.instantiate(binary, info) + return result + }) + .then(receiver, function (reason) { + err('failed to asynchronously prepare wasm: ' + reason) + abort(reason) + }) + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult) + } + if (Module['instantiateWasm']) { + try { + var exports = Module['instantiateWasm'](info, receiveInstance) + return exports + } catch (e) { + err('Module.instantiateWasm callback failed with error: ' + e) + return false + } + } + instantiateAsync().catch(readyPromiseReject) + return {} + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + var callback = callbacks.shift() + if (typeof callback == 'function') { + callback(Module) + continue + } + var func = callback.func + if (typeof func === 'number') { + if (callback.arg === undefined) { + wasmTable.get(func)() + } else { + wasmTable.get(func)(callback.arg) + } + } else { + func(callback.arg === undefined ? null : callback.arg) + } + } + } + function _atexit(func, arg) {} + function ___cxa_thread_atexit(a0, a1) { + return _atexit(a0, a1) + } + var SYSCALLS = { + mappings: {}, + buffers: [null, [], []], + printChar: function (stream, curr) { + var buffer = SYSCALLS.buffers[stream] + if (curr === 0 || curr === 10) { + ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)) + buffer.length = 0 + } else { + buffer.push(curr) + } + }, + varargs: undefined, + get: function () { + SYSCALLS.varargs += 4 + var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2] + return ret + }, + getStr: function (ptr) { + var ret = UTF8ToString(ptr) + return ret + }, + get64: function (low, high) { + return low + }, + } + function ___sys_fcntl64(fd, cmd, varargs) { + SYSCALLS.varargs = varargs + return 0 + } + function ___sys_ioctl(fd, op, varargs) { + SYSCALLS.varargs = varargs + return 0 + } + function ___sys_open(path, flags, varargs) { + SYSCALLS.varargs = varargs + } + var structRegistrations = {} + function runDestructors(destructors) { + while (destructors.length) { + var ptr = destructors.pop() + var del = destructors.pop() + del(ptr) + } + } + function simpleReadValueFromPointer(pointer) { + return this['fromWireType'](HEAPU32[pointer >> 2]) + } + var awaitingDependencies = {} + var registeredTypes = {} + var typeDependencies = {} + var char_0 = 48 + var char_9 = 57 + function makeLegalFunctionName(name) { + if (undefined === name) { + return '_unknown' + } + name = name.replace(/[^a-zA-Z0-9_]/g, '$') + var f = name.charCodeAt(0) + if (f >= char_0 && f <= char_9) { + return '_' + name + } else { + return name + } + } + function createNamedFunction(name, body) { + name = makeLegalFunctionName(name) + return new Function( + 'body', + 'return function ' + + name + + '() {\n' + + ' "use strict";' + + ' return body.apply(this, arguments);\n' + + '};\n' + )(body) + } + function extendError(baseErrorType, errorName) { + var errorClass = createNamedFunction(errorName, function (message) { + this.name = errorName + this.message = message + var stack = new Error(message).stack + if (stack !== undefined) { + this.stack = + this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '') + } + }) + errorClass.prototype = Object.create(baseErrorType.prototype) + errorClass.prototype.constructor = errorClass + errorClass.prototype.toString = function () { + if (this.message === undefined) { + return this.name + } else { + return this.name + ': ' + this.message + } + } + return errorClass + } + var InternalError = undefined + function throwInternalError(message) { + throw new InternalError(message) + } + function whenDependentTypesAreResolved( + myTypes, + dependentTypes, + getTypeConverters + ) { + myTypes.forEach(function (type) { + typeDependencies[type] = dependentTypes + }) + function onComplete(typeConverters) { + var myTypeConverters = getTypeConverters(typeConverters) + if (myTypeConverters.length !== myTypes.length) { + throwInternalError('Mismatched type converter count') + } + for (var i = 0; i < myTypes.length; ++i) { + registerType(myTypes[i], myTypeConverters[i]) + } + } + var typeConverters = new Array(dependentTypes.length) + var unregisteredTypes = [] + var registered = 0 + dependentTypes.forEach(function (dt, i) { + if (registeredTypes.hasOwnProperty(dt)) { + typeConverters[i] = registeredTypes[dt] + } else { + unregisteredTypes.push(dt) + if (!awaitingDependencies.hasOwnProperty(dt)) { + awaitingDependencies[dt] = [] + } + awaitingDependencies[dt].push(function () { + typeConverters[i] = registeredTypes[dt] + ++registered + if (registered === unregisteredTypes.length) { + onComplete(typeConverters) + } + }) + } + }) + if (0 === unregisteredTypes.length) { + onComplete(typeConverters) + } + } + function __embind_finalize_value_object(structType) { + var reg = structRegistrations[structType] + delete structRegistrations[structType] + var rawConstructor = reg.rawConstructor + var rawDestructor = reg.rawDestructor + var fieldRecords = reg.fields + var fieldTypes = fieldRecords + .map(function (field) { + return field.getterReturnType + }) + .concat( + fieldRecords.map(function (field) { + return field.setterArgumentType + }) + ) + whenDependentTypesAreResolved( + [structType], + fieldTypes, + function (fieldTypes) { + var fields = {} + fieldRecords.forEach(function (field, i) { + var fieldName = field.fieldName + var getterReturnType = fieldTypes[i] + var getter = field.getter + var getterContext = field.getterContext + var setterArgumentType = fieldTypes[i + fieldRecords.length] + var setter = field.setter + var setterContext = field.setterContext + fields[fieldName] = { + read: function (ptr) { + return getterReturnType['fromWireType']( + getter(getterContext, ptr) + ) + }, + write: function (ptr, o) { + var destructors = [] + setter( + setterContext, + ptr, + setterArgumentType['toWireType'](destructors, o) + ) + runDestructors(destructors) + }, + } + }) + return [ + { + name: reg.name, + fromWireType: function (ptr) { + var rv = {} + for (var i in fields) { + rv[i] = fields[i].read(ptr) + } + rawDestructor(ptr) + return rv + }, + toWireType: function (destructors, o) { + for (var fieldName in fields) { + if (!(fieldName in o)) { + throw new TypeError('Missing field: "' + fieldName + '"') + } + } + var ptr = rawConstructor() + for (fieldName in fields) { + fields[fieldName].write(ptr, o[fieldName]) + } + if (destructors !== null) { + destructors.push(rawDestructor, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: rawDestructor, + }, + ] + } + ) + } + function __embind_register_bigint( + primitiveType, + name, + size, + minRange, + maxRange + ) {} + function getShiftFromSize(size) { + switch (size) { + case 1: + return 0 + case 2: + return 1 + case 4: + return 2 + case 8: + return 3 + default: + throw new TypeError('Unknown type size: ' + size) + } + } + function embind_init_charCodes() { + var codes = new Array(256) + for (var i = 0; i < 256; ++i) { + codes[i] = String.fromCharCode(i) + } + embind_charCodes = codes + } + var embind_charCodes = undefined + function readLatin1String(ptr) { + var ret = '' + var c = ptr + while (HEAPU8[c]) { + ret += embind_charCodes[HEAPU8[c++]] + } + return ret + } + var BindingError = undefined + function throwBindingError(message) { + throw new BindingError(message) + } + function registerType(rawType, registeredInstance, options) { + options = options || {} + if (!('argPackAdvance' in registeredInstance)) { + throw new TypeError( + 'registerType registeredInstance requires argPackAdvance' + ) + } + var name = registeredInstance.name + if (!rawType) { + throwBindingError( + 'type "' + name + '" must have a positive integer typeid pointer' + ) + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return + } else { + throwBindingError("Cannot register type '" + name + "' twice") + } + } + registeredTypes[rawType] = registeredInstance + delete typeDependencies[rawType] + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType] + delete awaitingDependencies[rawType] + callbacks.forEach(function (cb) { + cb() + }) + } + } + function __embind_register_bool( + rawType, + name, + size, + trueValue, + falseValue + ) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (wt) { + return !!wt + }, + toWireType: function (destructors, o) { + return o ? trueValue : falseValue + }, + argPackAdvance: 8, + readValueFromPointer: function (pointer) { + var heap + if (size === 1) { + heap = HEAP8 + } else if (size === 2) { + heap = HEAP16 + } else if (size === 4) { + heap = HEAP32 + } else { + throw new TypeError('Unknown boolean type size: ' + name) + } + return this['fromWireType'](heap[pointer >> shift]) + }, + destructorFunction: null, + }) + } + var emval_free_list = [] + var emval_handle_array = [ + {}, + { value: undefined }, + { value: null }, + { value: true }, + { value: false }, + ] + function __emval_decref(handle) { + if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { + emval_handle_array[handle] = undefined + emval_free_list.push(handle) + } + } + function count_emval_handles() { + var count = 0 + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + ++count + } + } + return count + } + function get_first_emval() { + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + return emval_handle_array[i] + } + } + return null + } + function init_emval() { + Module['count_emval_handles'] = count_emval_handles + Module['get_first_emval'] = get_first_emval + } + function __emval_register(value) { + switch (value) { + case undefined: { + return 1 + } + case null: { + return 2 + } + case true: { + return 3 + } + case false: { + return 4 + } + default: { + var handle = emval_free_list.length + ? emval_free_list.pop() + : emval_handle_array.length + emval_handle_array[handle] = { refcount: 1, value: value } + return handle + } + } + } + function __embind_register_emval(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (handle) { + var rv = emval_handle_array[handle].value + __emval_decref(handle) + return rv + }, + toWireType: function (destructors, value) { + return __emval_register(value) + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: null, + }) + } + function _embind_repr(v) { + if (v === null) { + return 'null' + } + var t = typeof v + if (t === 'object' || t === 'array' || t === 'function') { + return v.toString() + } else { + return '' + v + } + } + function floatReadValueFromPointer(name, shift) { + switch (shift) { + case 2: + return function (pointer) { + return this['fromWireType'](HEAPF32[pointer >> 2]) + } + case 3: + return function (pointer) { + return this['fromWireType'](HEAPF64[pointer >> 3]) + } + default: + throw new TypeError('Unknown float type: ' + name) + } + } + function __embind_register_float(rawType, name, size) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (value) { + return value + }, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + return value + }, + argPackAdvance: 8, + readValueFromPointer: floatReadValueFromPointer(name, shift), + destructorFunction: null, + }) + } + function new_(constructor, argumentList) { + if (!(constructor instanceof Function)) { + throw new TypeError( + 'new_ called with constructor type ' + + typeof constructor + + ' which is not a function' + ) + } + var dummy = createNamedFunction( + constructor.name || 'unknownFunctionName', + function () {} + ) + dummy.prototype = constructor.prototype + var obj = new dummy() + var r = constructor.apply(obj, argumentList) + return r instanceof Object ? r : obj + } + function craftInvokerFunction( + humanName, + argTypes, + classType, + cppInvokerFunc, + cppTargetFunc + ) { + var argCount = argTypes.length + if (argCount < 2) { + throwBindingError( + "argTypes array size mismatch! Must at least get return value and 'this' types!" + ) + } + var isClassMethodFunc = argTypes[1] !== null && classType !== null + var needsDestructorStack = false + for (var i = 1; i < argTypes.length; ++i) { + if ( + argTypes[i] !== null && + argTypes[i].destructorFunction === undefined + ) { + needsDestructorStack = true + break + } + } + var returns = argTypes[0].name !== 'void' + var argsList = '' + var argsListWired = '' + for (var i = 0; i < argCount - 2; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired' + } + var invokerFnBody = + 'return function ' + + makeLegalFunctionName(humanName) + + '(' + + argsList + + ') {\n' + + 'if (arguments.length !== ' + + (argCount - 2) + + ') {\n' + + "throwBindingError('function " + + humanName + + " called with ' + arguments.length + ' arguments, expected " + + (argCount - 2) + + " args!');\n" + + '}\n' + if (needsDestructorStack) { + invokerFnBody += 'var destructors = [];\n' + } + var dtorStack = needsDestructorStack ? 'destructors' : 'null' + var args1 = [ + 'throwBindingError', + 'invoker', + 'fn', + 'runDestructors', + 'retType', + 'classParam', + ] + var args2 = [ + throwBindingError, + cppInvokerFunc, + cppTargetFunc, + runDestructors, + argTypes[0], + argTypes[1], + ] + if (isClassMethodFunc) { + invokerFnBody += + 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n' + } + for (var i = 0; i < argCount - 2; ++i) { + invokerFnBody += + 'var arg' + + i + + 'Wired = argType' + + i + + '.toWireType(' + + dtorStack + + ', arg' + + i + + '); // ' + + argTypes[i + 2].name + + '\n' + args1.push('argType' + i) + args2.push(argTypes[i + 2]) + } + if (isClassMethodFunc) { + argsListWired = + 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired + } + invokerFnBody += + (returns ? 'var rv = ' : '') + + 'invoker(fn' + + (argsListWired.length > 0 ? ', ' : '') + + argsListWired + + ');\n' + if (needsDestructorStack) { + invokerFnBody += 'runDestructors(destructors);\n' + } else { + for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { + var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired' + if (argTypes[i].destructorFunction !== null) { + invokerFnBody += + paramName + + '_dtor(' + + paramName + + '); // ' + + argTypes[i].name + + '\n' + args1.push(paramName + '_dtor') + args2.push(argTypes[i].destructorFunction) + } + } + } + if (returns) { + invokerFnBody += + 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n' + } else { + } + invokerFnBody += '}\n' + args1.push(invokerFnBody) + var invokerFunction = new_(Function, args1).apply(null, args2) + return invokerFunction + } + function ensureOverloadTable(proto, methodName, humanName) { + if (undefined === proto[methodName].overloadTable) { + var prevFunc = proto[methodName] + proto[methodName] = function () { + if ( + !proto[methodName].overloadTable.hasOwnProperty(arguments.length) + ) { + throwBindingError( + "Function '" + + humanName + + "' called with an invalid number of arguments (" + + arguments.length + + ') - expects one of (' + + proto[methodName].overloadTable + + ')!' + ) + } + return proto[methodName].overloadTable[arguments.length].apply( + this, + arguments + ) + } + proto[methodName].overloadTable = [] + proto[methodName].overloadTable[prevFunc.argCount] = prevFunc + } + } + function exposePublicSymbol(name, value, numArguments) { + if (Module.hasOwnProperty(name)) { + if ( + undefined === numArguments || + (undefined !== Module[name].overloadTable && + undefined !== Module[name].overloadTable[numArguments]) + ) { + throwBindingError("Cannot register public name '" + name + "' twice") + } + ensureOverloadTable(Module, name, name) + if (Module.hasOwnProperty(numArguments)) { + throwBindingError( + 'Cannot register multiple overloads of a function with the same number of arguments (' + + numArguments + + ')!' + ) + } + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + if (undefined !== numArguments) { + Module[name].numArguments = numArguments + } + } + } + function heap32VectorToArray(count, firstElement) { + var array = [] + for (var i = 0; i < count; i++) { + array.push(HEAP32[(firstElement >> 2) + i]) + } + return array + } + function replacePublicSymbol(name, value, numArguments) { + if (!Module.hasOwnProperty(name)) { + throwInternalError('Replacing nonexistent public symbol') + } + if ( + undefined !== Module[name].overloadTable && + undefined !== numArguments + ) { + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + Module[name].argCount = numArguments + } + } + function dynCallLegacy(sig, ptr, args) { + var f = Module['dynCall_' + sig] + return args && args.length + ? f.apply(null, [ptr].concat(args)) + : f.call(null, ptr) + } + function dynCall(sig, ptr, args) { + if (sig.includes('j')) { + return dynCallLegacy(sig, ptr, args) + } + return wasmTable.get(ptr).apply(null, args) + } + function getDynCaller(sig, ptr) { + var argCache = [] + return function () { + argCache.length = arguments.length + for (var i = 0; i < arguments.length; i++) { + argCache[i] = arguments[i] + } + return dynCall(sig, ptr, argCache) + } + } + function embind__requireFunction(signature, rawFunction) { + signature = readLatin1String(signature) + function makeDynCaller() { + if (signature.includes('j')) { + return getDynCaller(signature, rawFunction) + } + return wasmTable.get(rawFunction) + } + var fp = makeDynCaller() + if (typeof fp !== 'function') { + throwBindingError( + 'unknown function pointer with signature ' + + signature + + ': ' + + rawFunction + ) + } + return fp + } + var UnboundTypeError = undefined + function getTypeName(type) { + var ptr = ___getTypeName(type) + var rv = readLatin1String(ptr) + _free(ptr) + return rv + } + function throwUnboundTypeError(message, types) { + var unboundTypes = [] + var seen = {} + function visit(type) { + if (seen[type]) { + return + } + if (registeredTypes[type]) { + return + } + if (typeDependencies[type]) { + typeDependencies[type].forEach(visit) + return + } + unboundTypes.push(type) + seen[type] = true + } + types.forEach(visit) + throw new UnboundTypeError( + message + ': ' + unboundTypes.map(getTypeName).join([', ']) + ) + } + function __embind_register_function( + name, + argCount, + rawArgTypesAddr, + signature, + rawInvoker, + fn + ) { + var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr) + name = readLatin1String(name) + rawInvoker = embind__requireFunction(signature, rawInvoker) + exposePublicSymbol( + name, + function () { + throwUnboundTypeError( + 'Cannot call ' + name + ' due to unbound types', + argTypes + ) + }, + argCount - 1 + ) + whenDependentTypesAreResolved([], argTypes, function (argTypes) { + var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1)) + replacePublicSymbol( + name, + craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn), + argCount - 1 + ) + return [] + }) + } + function integerReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return signed + ? function readS8FromPointer(pointer) { + return HEAP8[pointer] + } + : function readU8FromPointer(pointer) { + return HEAPU8[pointer] + } + case 1: + return signed + ? function readS16FromPointer(pointer) { + return HEAP16[pointer >> 1] + } + : function readU16FromPointer(pointer) { + return HEAPU16[pointer >> 1] + } + case 2: + return signed + ? function readS32FromPointer(pointer) { + return HEAP32[pointer >> 2] + } + : function readU32FromPointer(pointer) { + return HEAPU32[pointer >> 2] + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_integer( + primitiveType, + name, + size, + minRange, + maxRange + ) { + name = readLatin1String(name) + if (maxRange === -1) { + maxRange = 4294967295 + } + var shift = getShiftFromSize(size) + var fromWireType = function (value) { + return value + } + if (minRange === 0) { + var bitshift = 32 - 8 * size + fromWireType = function (value) { + return (value << bitshift) >>> bitshift + } + } + var isUnsignedType = name.includes('unsigned') + registerType(primitiveType, { + name: name, + fromWireType: fromWireType, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + if (value < minRange || value > maxRange) { + throw new TypeError( + 'Passing a number "' + + _embind_repr(value) + + '" from JS side to C/C++ side to an argument of type "' + + name + + '", which is outside the valid range [' + + minRange + + ', ' + + maxRange + + ']!' + ) + } + return isUnsignedType ? value >>> 0 : value | 0 + }, + argPackAdvance: 8, + readValueFromPointer: integerReadValueFromPointer( + name, + shift, + minRange !== 0 + ), + destructorFunction: null, + }) + } + function __embind_register_memory_view(rawType, dataTypeIndex, name) { + var typeMapping = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + ] + var TA = typeMapping[dataTypeIndex] + function decodeMemoryView(handle) { + handle = handle >> 2 + var heap = HEAPU32 + var size = heap[handle] + var data = heap[handle + 1] + return new TA(buffer, data, size) + } + name = readLatin1String(name) + registerType( + rawType, + { + name: name, + fromWireType: decodeMemoryView, + argPackAdvance: 8, + readValueFromPointer: decodeMemoryView, + }, + { ignoreDuplicateRegistrations: true } + ) + } + function __embind_register_std_string(rawType, name) { + name = readLatin1String(name) + var stdStringIsUTF8 = name === 'std::string' + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var str + if (stdStringIsUTF8) { + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i + if (i == length || HEAPU8[currentBytePtr] == 0) { + var maxRead = currentBytePtr - decodeStartPtr + var stringSegment = UTF8ToString(decodeStartPtr, maxRead) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + 1 + } + } + } else { + var a = new Array(length) + for (var i = 0; i < length; ++i) { + a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) + } + str = a.join('') + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value) + } + var getLength + var valueIsOfTypeString = typeof value === 'string' + if ( + !( + valueIsOfTypeString || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int8Array + ) + ) { + throwBindingError('Cannot pass non-string to std::string') + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + getLength = function () { + return lengthBytesUTF8(value) + } + } else { + getLength = function () { + return value.length + } + } + var length = getLength() + var ptr = _malloc(4 + length + 1) + HEAPU32[ptr >> 2] = length + if (stdStringIsUTF8 && valueIsOfTypeString) { + stringToUTF8(value, ptr + 4, length + 1) + } else { + if (valueIsOfTypeString) { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i) + if (charCode > 255) { + _free(ptr) + throwBindingError( + 'String has UTF-16 code units that do not fit in 8 bits' + ) + } + HEAPU8[ptr + 4 + i] = charCode + } + } else { + for (var i = 0; i < length; ++i) { + HEAPU8[ptr + 4 + i] = value[i] + } + } + } + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_std_wstring(rawType, charSize, name) { + name = readLatin1String(name) + var decodeString, encodeString, getHeap, lengthBytesUTF, shift + if (charSize === 2) { + decodeString = UTF16ToString + encodeString = stringToUTF16 + lengthBytesUTF = lengthBytesUTF16 + getHeap = function () { + return HEAPU16 + } + shift = 1 + } else if (charSize === 4) { + decodeString = UTF32ToString + encodeString = stringToUTF32 + lengthBytesUTF = lengthBytesUTF32 + getHeap = function () { + return HEAPU32 + } + shift = 2 + } + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var HEAP = getHeap() + var str + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i * charSize + if (i == length || HEAP[currentBytePtr >> shift] == 0) { + var maxReadBytes = currentBytePtr - decodeStartPtr + var stringSegment = decodeString(decodeStartPtr, maxReadBytes) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + charSize + } + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (!(typeof value === 'string')) { + throwBindingError( + 'Cannot pass non-string to C++ string type ' + name + ) + } + var length = lengthBytesUTF(value) + var ptr = _malloc(4 + length + charSize) + HEAPU32[ptr >> 2] = length >> shift + encodeString(value, ptr + 4, length + charSize) + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_value_object( + rawType, + name, + constructorSignature, + rawConstructor, + destructorSignature, + rawDestructor + ) { + structRegistrations[rawType] = { + name: readLatin1String(name), + rawConstructor: embind__requireFunction( + constructorSignature, + rawConstructor + ), + rawDestructor: embind__requireFunction( + destructorSignature, + rawDestructor + ), + fields: [], + } + } + function __embind_register_value_object_field( + structType, + fieldName, + getterReturnType, + getterSignature, + getter, + getterContext, + setterArgumentType, + setterSignature, + setter, + setterContext + ) { + structRegistrations[structType].fields.push({ + fieldName: readLatin1String(fieldName), + getterReturnType: getterReturnType, + getter: embind__requireFunction(getterSignature, getter), + getterContext: getterContext, + setterArgumentType: setterArgumentType, + setter: embind__requireFunction(setterSignature, setter), + setterContext: setterContext, + }) + } + function __embind_register_void(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + isVoid: true, + name: name, + argPackAdvance: 0, + fromWireType: function () { + return undefined + }, + toWireType: function (destructors, o) { + return undefined + }, + }) + } + var emval_symbols = {} + function getStringOrSymbol(address) { + var symbol = emval_symbols[address] + if (symbol === undefined) { + return readLatin1String(address) + } else { + return symbol + } + } + function emval_get_global() { + if (typeof globalThis === 'object') { + return globalThis + } + return (function () { + return Function + })()('return this')() + } + function __emval_get_global(name) { + if (name === 0) { + return __emval_register(emval_get_global()) + } else { + name = getStringOrSymbol(name) + return __emval_register(emval_get_global()[name]) + } + } + function __emval_incref(handle) { + if (handle > 4) { + emval_handle_array[handle].refcount += 1 + } + } + function requireRegisteredType(rawType, humanName) { + var impl = registeredTypes[rawType] + if (undefined === impl) { + throwBindingError( + humanName + ' has unknown type ' + getTypeName(rawType) + ) + } + return impl + } + function craftEmvalAllocator(argCount) { + var argsList = '' + for (var i = 0; i < argCount; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + } + var functionBody = + 'return function emval_allocator_' + + argCount + + '(constructor, argTypes, args) {\n' + for (var i = 0; i < argCount; ++i) { + functionBody += + 'var argType' + + i + + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + + i + + '], "parameter ' + + i + + '");\n' + + 'var arg' + + i + + ' = argType' + + i + + '.readValueFromPointer(args);\n' + + 'args += argType' + + i + + "['argPackAdvance'];\n" + } + functionBody += + 'var obj = new constructor(' + + argsList + + ');\n' + + 'return __emval_register(obj);\n' + + '}\n' + return new Function( + 'requireRegisteredType', + 'Module', + '__emval_register', + functionBody + )(requireRegisteredType, Module, __emval_register) + } + var emval_newers = {} + function requireHandle(handle) { + if (!handle) { + throwBindingError('Cannot use deleted val. handle = ' + handle) + } + return emval_handle_array[handle].value + } + function __emval_new(handle, argCount, argTypes, args) { + handle = requireHandle(handle) + var newer = emval_newers[argCount] + if (!newer) { + newer = craftEmvalAllocator(argCount) + emval_newers[argCount] = newer + } + return newer(handle, argTypes, args) + } + function _abort() { + abort() + } + function _longjmp(env, value) { + _setThrew(env, value || 1) + throw 'longjmp' + } + function _emscripten_longjmp(a0, a1) { + return _longjmp(a0, a1) + } + function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.copyWithin(dest, src, src + num) + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16) + updateGlobalBufferAndViews(wasmMemory.buffer) + return 1 + } catch (e) {} + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length + requestedSize = requestedSize >>> 0 + var maxHeapSize = 2147483648 + if (requestedSize > maxHeapSize) { + return false + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown) + overGrownHeapSize = Math.min( + overGrownHeapSize, + requestedSize + 100663296 + ) + var newSize = Math.min( + maxHeapSize, + alignUp(Math.max(requestedSize, overGrownHeapSize), 65536) + ) + var replacement = emscripten_realloc_buffer(newSize) + if (replacement) { + return true + } + } + return false + } + function _fd_close(fd) { + return 0 + } + function _fd_read(fd, iov, iovcnt, pnum) { + var stream = SYSCALLS.getStreamFromFD(fd) + var num = SYSCALLS.doReadv(stream, iov, iovcnt) + HEAP32[pnum >> 2] = num + return 0 + } + function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {} + function _fd_write(fd, iov, iovcnt, pnum) { + var num = 0 + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAP32[(iov + i * 8) >> 2] + var len = HEAP32[(iov + (i * 8 + 4)) >> 2] + for (var j = 0; j < len; j++) { + SYSCALLS.printChar(fd, HEAPU8[ptr + j]) + } + num += len + } + HEAP32[pnum >> 2] = num + return 0 + } + function _getTempRet0() { + return getTempRet0() + } + function _setTempRet0(val) { + setTempRet0(val) + } + function _time(ptr) { + var ret = (Date.now() / 1e3) | 0 + if (ptr) { + HEAP32[ptr >> 2] = ret + } + return ret + } + InternalError = Module['InternalError'] = extendError( + Error, + 'InternalError' + ) + embind_init_charCodes() + BindingError = Module['BindingError'] = extendError(Error, 'BindingError') + init_emval() + UnboundTypeError = Module['UnboundTypeError'] = extendError( + Error, + 'UnboundTypeError' + ) + var asmLibraryArg = { + O: ___cxa_thread_atexit, + r: ___sys_fcntl64, + G: ___sys_ioctl, + H: ___sys_open, + x: __embind_finalize_value_object, + B: __embind_register_bigint, + K: __embind_register_bool, + J: __embind_register_emval, + t: __embind_register_float, + w: __embind_register_function, + i: __embind_register_integer, + e: __embind_register_memory_view, + u: __embind_register_std_string, + o: __embind_register_std_wstring, + z: __embind_register_value_object, + g: __embind_register_value_object_field, + L: __embind_register_void, + j: __emval_decref, + N: __emval_get_global, + v: __emval_incref, + D: __emval_new, + f: _abort, + d: _emscripten_longjmp, + E: _emscripten_memcpy_big, + n: _emscripten_resize_heap, + s: _fd_close, + F: _fd_read, + A: _fd_seek, + I: _fd_write, + b: _getTempRet0, + l: invoke_iiiii, + p: invoke_iiiiiiiii, + q: invoke_iiiiiiiiii, + C: invoke_iiiiiiiiiiii, + y: invoke_ijiii, + m: invoke_vi, + h: invoke_vii, + c: invoke_viiii, + k: invoke_viiiiiiiiii, + a: _setTempRet0, + M: _time, + } + var asm = createWasm() + var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () { + return (___wasm_call_ctors = Module['___wasm_call_ctors'] = + Module['asm']['Q']).apply(null, arguments) + }) + var _malloc = (Module['_malloc'] = function () { + return (_malloc = Module['_malloc'] = Module['asm']['R']).apply( + null, + arguments + ) + }) + var _free = (Module['_free'] = function () { + return (_free = Module['_free'] = Module['asm']['S']).apply( + null, + arguments + ) + }) + var ___getTypeName = (Module['___getTypeName'] = function () { + return (___getTypeName = Module['___getTypeName'] = + Module['asm']['T']).apply(null, arguments) + }) + var ___embind_register_native_and_builtin_types = (Module[ + '___embind_register_native_and_builtin_types' + ] = function () { + return (___embind_register_native_and_builtin_types = Module[ + '___embind_register_native_and_builtin_types' + ] = + Module['asm']['U']).apply(null, arguments) + }) + var stackSave = (Module['stackSave'] = function () { + return (stackSave = Module['stackSave'] = Module['asm']['V']).apply( + null, + arguments + ) + }) + var stackRestore = (Module['stackRestore'] = function () { + return (stackRestore = Module['stackRestore'] = Module['asm']['W']).apply( + null, + arguments + ) + }) + var _setThrew = (Module['_setThrew'] = function () { + return (_setThrew = Module['_setThrew'] = Module['asm']['X']).apply( + null, + arguments + ) + }) + var dynCall_jiiiiiiiii = (Module['dynCall_jiiiiiiiii'] = function () { + return (dynCall_jiiiiiiiii = Module['dynCall_jiiiiiiiii'] = + Module['asm']['Z']).apply(null, arguments) + }) + var dynCall_ijiii = (Module['dynCall_ijiii'] = function () { + return (dynCall_ijiii = Module['dynCall_ijiii'] = + Module['asm']['_']).apply(null, arguments) + }) + var dynCall_jiji = (Module['dynCall_jiji'] = function () { + return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['$']).apply( + null, + arguments + ) + }) + var dynCall_jiiiiiiii = (Module['dynCall_jiiiiiiii'] = function () { + return (dynCall_jiiiiiiii = Module['dynCall_jiiiiiiii'] = + Module['asm']['aa']).apply(null, arguments) + }) + var dynCall_jiiiiii = (Module['dynCall_jiiiiii'] = function () { + return (dynCall_jiiiiii = Module['dynCall_jiiiiii'] = + Module['asm']['ba']).apply(null, arguments) + }) + var dynCall_jiiiii = (Module['dynCall_jiiiii'] = function () { + return (dynCall_jiiiii = Module['dynCall_jiiiii'] = + Module['asm']['ca']).apply(null, arguments) + }) + var dynCall_iiijii = (Module['dynCall_iiijii'] = function () { + return (dynCall_iiijii = Module['dynCall_iiijii'] = + Module['asm']['da']).apply(null, arguments) + }) + function invoke_vi(index, a1) { + var sp = stackSave() + try { + wasmTable.get(index)(a1) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_viiii(index, a1, a2, a3, a4) { + var sp = stackSave() + try { + wasmTable.get(index)(a1, a2, a3, a4) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_vii(index, a1, a2) { + var sp = stackSave() + try { + wasmTable.get(index)(a1, a2) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_iiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + var sp = stackSave() + try { + return wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_iiiiiiiiiiii( + index, + a1, + a2, + a3, + a4, + a5, + a6, + a7, + a8, + a9, + a10, + a11 + ) { + var sp = stackSave() + try { + return wasmTable.get(index)( + a1, + a2, + a3, + a4, + a5, + a6, + a7, + a8, + a9, + a10, + a11 + ) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_iiiii(index, a1, a2, a3, a4) { + var sp = stackSave() + try { + return wasmTable.get(index)(a1, a2, a3, a4) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_viiiiiiiiii( + index, + a1, + a2, + a3, + a4, + a5, + a6, + a7, + a8, + a9, + a10 + ) { + var sp = stackSave() + try { + wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_iiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8) { + var sp = stackSave() + try { + return wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7, a8) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + function invoke_ijiii(index, a1, a2, a3, a4, a5) { + var sp = stackSave() + try { + return dynCall_ijiii(index, a1, a2, a3, a4, a5) + } catch (e) { + stackRestore(sp) + if (e !== e + 0 && e !== 'longjmp') throw e + _setThrew(1, 0) + } + } + var calledRun + dependenciesFulfilled = function runCaller() { + if (!calledRun) run() + if (!calledRun) dependenciesFulfilled = runCaller + } + function run(args) { + args = args || arguments_ + if (runDependencies > 0) { + return + } + preRun() + if (runDependencies > 0) { + return + } + function doRun() { + if (calledRun) return + calledRun = true + Module['calledRun'] = true + if (ABORT) return + initRuntime() + readyPromiseResolve(Module) + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() + postRun() + } + if (Module['setStatus']) { + Module['setStatus']('Running...') + setTimeout(function () { + setTimeout(function () { + Module['setStatus']('') + }, 1) + doRun() + }, 1) + } else { + doRun() + } + } + Module['run'] = run + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') + Module['preInit'] = [Module['preInit']] + while (Module['preInit'].length > 0) { + Module['preInit'].pop()() + } + } + run() + + return Module.ready + } +})() +export default Module diff --git a/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_enc.wasm b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_enc.wasm new file mode 100644 index 000000000000..6a19f18bf067 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/avif/avif_node_enc.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/codecs.ts b/packages/astro/src/assets/services/vendor/squoosh/codecs.ts new file mode 100644 index 000000000000..85ccb51a77d9 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/codecs.ts @@ -0,0 +1,373 @@ +import { promises as fsp } from 'node:fs' +import { getModuleURL, instantiateEmscriptenWasm, pathify } from './emscripten-utils.js' + +interface DecodeModule extends EmscriptenWasm.Module { + decode: (data: Uint8Array) => ImageData +} + +type DecodeModuleFactory = EmscriptenWasm.ModuleFactory + +interface RotateModuleInstance { + exports: { + memory: WebAssembly.Memory + rotate(width: number, height: number, rotate: number): void + } +} + +interface ResizeWithAspectParams { + input_width: number + input_height: number + target_width?: number + target_height?: number +} + +export interface ResizeOptions { + width?: number + height?: number + method: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3' + premultiply: boolean + linearRGB: boolean +} + +export interface RotateOptions { + numRotations: number +} + +// MozJPEG +import type { MozJPEGModule as MozJPEGEncodeModule } from './mozjpeg/mozjpeg_enc' +// @ts-ignore +import mozEnc from './mozjpeg/mozjpeg_node_enc.js' +const mozEncWasm = new URL('./mozjpeg/mozjpeg_node_enc.wasm', getModuleURL(import.meta.url)) +// @ts-ignore +import mozDec from './mozjpeg/mozjpeg_node_dec.js' +const mozDecWasm = new URL('./mozjpeg/mozjpeg_node_dec.wasm', getModuleURL(import.meta.url)) + +// WebP +import type { WebPModule as WebPEncodeModule } from './webp/webp_enc' +// @ts-ignore +import webpEnc from './webp/webp_node_enc.js' +const webpEncWasm = new URL('./webp/webp_node_enc.wasm', getModuleURL(import.meta.url)) +// @ts-ignore +import webpDec from './webp/webp_node_dec.js' +const webpDecWasm = new URL('./webp/webp_node_dec.wasm', getModuleURL(import.meta.url)) + +// AVIF +import type { AVIFModule as AVIFEncodeModule } from './avif/avif_enc' +// @ts-ignore +import avifEnc from './avif/avif_node_enc.js' +const avifEncWasm = new URL('./avif/avif_node_enc.wasm', getModuleURL(import.meta.url)) +// @ts-ignore +import avifDec from './avif/avif_node_dec.js' +const avifDecWasm = new URL('./avif/avif_node_dec.wasm', getModuleURL(import.meta.url)) + +// PNG +// @ts-ignore +import * as pngEncDec from './png/squoosh_png.js' +const pngEncDecWasm = new URL('./png/squoosh_png_bg.wasm', getModuleURL(import.meta.url)) +const pngEncDecInit = () => + pngEncDec.default(fsp.readFile(pathify(pngEncDecWasm.toString()))) + +// OxiPNG +// @ts-ignore +import * as oxipng from './png/squoosh_oxipng.js' +const oxipngWasm = new URL('./png/squoosh_oxipng_bg.wasm', getModuleURL(import.meta.url)) +const oxipngInit = () => oxipng.default(fsp.readFile(pathify(oxipngWasm.toString()))) + +// Resize +// @ts-ignore +import * as resize from './resize/squoosh_resize.js' +const resizeWasm = new URL('./resize/squoosh_resize_bg.wasm', getModuleURL(import.meta.url)) +const resizeInit = () => resize.default(fsp.readFile(pathify(resizeWasm.toString()))) + +// rotate +const rotateWasm = new URL('./rotate/rotate.wasm', getModuleURL(import.meta.url)) + +// Our decoders currently rely on a `ImageData` global. +import ImageData from './image_data.js' +(global as any).ImageData = ImageData + +function resizeNameToIndex( + name: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3' +) { + 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, +}: ResizeWithAspectParams): { width: number; height: number } { + 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: Uint8Array, + input_width: number, + input_height: number, + { width, height, method, premultiply, linearRGB }: ResizeOptions + ) => { + ;({ 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: Uint8Array, + width: number, + height: number, + { numRotations }: RotateOptions + ) => { + 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.toString()))) + ).instance as RotateModuleInstance + 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, + }, + }, +} as const + +export const codecs = { + mozjpeg: { + name: 'MozJPEG', + extension: 'jpg', + detectors: [/^\xFF\xD8\xFF/], + dec: () => + instantiateEmscriptenWasm(mozDec as DecodeModuleFactory, mozDecWasm.toString()), + enc: () => + instantiateEmscriptenWasm( + mozEnc as EmscriptenWasm.ModuleFactory, + mozEncWasm.toString() + ), + 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 as DecodeModuleFactory, webpDecWasm.toString()), + enc: () => + instantiateEmscriptenWasm( + webpEnc as EmscriptenWasm.ModuleFactory, + webpEncWasm.toString() + ), + 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 as DecodeModuleFactory, avifDecWasm.toString()), + enc: async () => { + return instantiateEmscriptenWasm( + avifEnc as EmscriptenWasm.ModuleFactory, + avifEncWasm.toString() + ) + }, + 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: Buffer | Uint8Array) => { + const imageData = pngEncDec.decode(buffer) + pngEncDec.cleanup() + return imageData + }, + } + }, + enc: async () => { + await pngEncDecInit() + await oxipngInit() + return { + encode: ( + buffer: Uint8ClampedArray | ArrayBuffer, + width: number, + height: number, + opts: { level: number } + ) => { + 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, + }, + }, +} as const diff --git a/packages/astro/src/assets/services/vendor/squoosh/copy-wasm.ts b/packages/astro/src/assets/services/vendor/squoosh/copy-wasm.ts new file mode 100644 index 000000000000..1c742f3eac1e --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/copy-wasm.ts @@ -0,0 +1,24 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export async function copyWasmFiles(dir: URL) { + const src = new URL('./', import.meta.url); + await copyDir(fileURLToPath(src), fileURLToPath(dir)); +} + +async function copyDir(src: string, dest: string) { + const itemNames = await fs.readdir(src); + await Promise.all(itemNames.map(async (srcName) => { + const srcPath = path.join(src, srcName); + const destPath = path.join(dest, srcName); + const s = await fs.stat(srcPath); + if (s.isFile() && /.wasm$/.test(srcPath)) { + await fs.mkdir(path.dirname(destPath), { recursive: true }); + await fs.copyFile(srcPath, destPath); + } + else if (s.isDirectory()) { + await copyDir(srcPath, destPath); + } + })); +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/emscripten-types.d.ts b/packages/astro/src/assets/services/vendor/squoosh/emscripten-types.d.ts new file mode 100644 index 000000000000..6397872299c5 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/emscripten-types.d.ts @@ -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 = ( + moduleOverrides?: ModuleOpts + ) => Promise + + 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 + } +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/emscripten-utils.ts b/packages/astro/src/assets/services/vendor/squoosh/emscripten-utils.ts new file mode 100644 index 000000000000..e661fae9253d --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/emscripten-utils.ts @@ -0,0 +1,44 @@ +// +import { fileURLToPath, pathToFileURL } from 'node:url' + +export function pathify(path: string): string { + if (path.startsWith('file://')) { + path = fileURLToPath(path) + } + return path +} + +export function instantiateEmscriptenWasm( + factory: EmscriptenWasm.ModuleFactory, + path: string, + workerJS = '' +): Promise { + 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 + }, + }) +} + +export function dirname(url: string) { + return url.substring(0, url.lastIndexOf('/')) +} + +/** + * On certain serverless hosts, our ESM bundle is transpiled to CJS before being run, which means + * import.meta.url is undefined, so we'll fall back to __dirname in those cases + * We should be able to remove this once https://github.com/netlify/zip-it-and-ship-it/issues/750 is fixed + */ +export function getModuleURL(url: string | undefined): string { + if (!url) { + return pathToFileURL(__dirname).toString(); + } + + return url +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/image-pool.ts b/packages/astro/src/assets/services/vendor/squoosh/image-pool.ts new file mode 100644 index 000000000000..d1e57b629960 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/image-pool.ts @@ -0,0 +1,150 @@ +import { isMainThread } from 'node:worker_threads'; +import { cpus } from 'os'; +import { fileURLToPath } from 'url'; +import type { OutputFormat } from '../../../types.js'; +import execOnce from './utils/execOnce.js'; +import WorkerPool from './utils/workerPool.js'; +import { getModuleURL } from './emscripten-utils.js'; +import type { Operation } from './image.js'; +import * as impl from './impl.js'; + +const getWorker = execOnce(() => { + return new WorkerPool( + // There will be at most 7 workers needed since each worker will take + // at least 1 operation type. + Math.max(1, Math.min(cpus().length - 1, 7)), + fileURLToPath(getModuleURL(import.meta.url)) + ); +}); + +type DecodeParams = { + operation: 'decode'; + buffer: Buffer; +}; +type ResizeParams = { + operation: 'resize'; + imageData: ImageData; + height?: number; + width?: number; +}; +type RotateParams = { + operation: 'rotate'; + imageData: ImageData; + numRotations: number; +}; +type EncodeAvifParams = { + operation: 'encodeavif'; + imageData: ImageData; + quality: number; +}; +type EncodeJpegParams = { + operation: 'encodejpeg'; + imageData: ImageData; + quality: number; +}; +type EncodePngParams = { + operation: 'encodepng'; + imageData: ImageData; +}; +type EncodeWebpParams = { + operation: 'encodewebp'; + imageData: ImageData; + quality: number; +}; +type JobMessage = + | DecodeParams + | ResizeParams + | RotateParams + | EncodeAvifParams + | EncodeJpegParams + | EncodePngParams + | EncodeWebpParams; + +function handleJob(params: JobMessage) { + switch (params.operation) { + case 'decode': + return impl.decodeBuffer(params.buffer); + case 'resize': + return impl.resize({ + image: params.imageData as any, + width: params.width, + height: params.height, + }); + case 'rotate': + return impl.rotate(params.imageData as any, params.numRotations); + case 'encodeavif': + return impl.encodeAvif(params.imageData as any, { quality: params.quality }); + case 'encodejpeg': + return impl.encodeJpeg(params.imageData as any, { quality: params.quality }); + case 'encodepng': + return impl.encodePng(params.imageData as any); + case 'encodewebp': + return impl.encodeWebp(params.imageData as any, { quality: params.quality }); + default: + throw Error(`Invalid job "${(params as any).operation}"`); + } +} + +export async function processBuffer( + buffer: Buffer, + operations: Operation[], + encoding: OutputFormat, + quality?: number +): Promise { + // @ts-ignore + const worker = await getWorker(); + + let imageData = await worker.dispatchJob({ + operation: 'decode', + buffer, + }); + for (const operation of operations) { + if (operation.type === 'rotate') { + imageData = await worker.dispatchJob({ + operation: 'rotate', + imageData, + numRotations: operation.numRotations, + }); + } else if (operation.type === 'resize') { + imageData = await worker.dispatchJob({ + operation: 'resize', + imageData, + height: operation.height, + width: operation.width, + }); + } + } + + switch (encoding) { + case 'avif': + return (await worker.dispatchJob({ + operation: 'encodeavif', + imageData, + quality, + })) as Uint8Array; + case 'jpeg': + case 'jpg': + return (await worker.dispatchJob({ + operation: 'encodejpeg', + imageData, + quality, + })) as Uint8Array; + case 'png': + return (await worker.dispatchJob({ + operation: 'encodepng', + imageData, + })) as Uint8Array; + case 'webp': + return (await worker.dispatchJob({ + operation: 'encodewebp', + imageData, + quality, + })) as Uint8Array; + default: + throw Error(`Unsupported encoding format`); + } +} + +if (!isMainThread) { + WorkerPool.useThisThreadAsWorker(handleJob); +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/image.ts b/packages/astro/src/assets/services/vendor/squoosh/image.ts new file mode 100644 index 000000000000..0b19c5091fe0 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/image.ts @@ -0,0 +1,43 @@ +import type { OutputFormat } from '../../../types.js'; +import * as impl from './impl.js'; + +type RotateOperation = { + type: 'rotate' + numRotations: number +} +type ResizeOperation = { + type: 'resize' + width?: number + height?: number +} +export type Operation = RotateOperation | ResizeOperation + +export async function processBuffer( + buffer: Buffer, + operations: Operation[], + encoding: OutputFormat, + quality?: number +): Promise { + let imageData = await impl.decodeBuffer(buffer) + for (const operation of operations) { + if (operation.type === 'rotate') { + imageData = await impl.rotate(imageData, operation.numRotations); + } else if (operation.type === 'resize') { + imageData = await impl.resize({ image: imageData, width: operation.width, height: operation.height }) + } + } + + switch (encoding) { + case 'avif': + return await impl.encodeAvif(imageData, { quality }) as Uint8Array; + case 'jpeg': + case 'jpg': + return await impl.encodeJpeg(imageData, { quality }) as Uint8Array; + case 'png': + return await impl.encodePng(imageData) as Uint8Array; + case 'webp': + return await impl.encodeWebp(imageData, { quality }) as Uint8Array; + default: + throw Error(`Unsupported encoding format`) + } +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/image_data.ts b/packages/astro/src/assets/services/vendor/squoosh/image_data.ts new file mode 100644 index 000000000000..16936b60e872 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/image_data.ts @@ -0,0 +1,33 @@ +export default class ImageData { + static from(input: ImageData): ImageData { + return new ImageData(input.data || input._data, input.width, input.height) + } + + private _data: Buffer | Uint8Array | Uint8ClampedArray + width: number + height: number + + get data(): Buffer { + 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: Buffer | Uint8Array | Uint8ClampedArray, + width: number, + height: number + ) { + this._data = data + this.width = width + this.height = height + } +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/impl.ts b/packages/astro/src/assets/services/vendor/squoosh/impl.ts new file mode 100644 index 000000000000..3d01141d3e76 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/impl.ts @@ -0,0 +1,143 @@ +import { codecs as supportedFormats, preprocessors } from './codecs.js' +import ImageData from './image_data.js' + +type EncoderKey = keyof typeof supportedFormats + +const DELAY_MS = 1000 +let _promise: Promise | undefined + +function delayOnce(ms: number): Promise { + if (!_promise) { + _promise = new Promise((resolve) => { + setTimeout(resolve, ms) + }) + } + return _promise +} + +function maybeDelay(): Promise { + const isAppleM1 = process.arch === 'arm64' && process.platform === 'darwin' + if (isAppleM1) { + return delayOnce(DELAY_MS) + } + return Promise.resolve() +} + +export async function decodeBuffer( + _buffer: Buffer | Uint8Array +): Promise { + const buffer = Buffer.from(_buffer) + const firstChunk = buffer.slice(0, 16) + const firstChunkString = Array.from(firstChunk) + .map((v) => String.fromCodePoint(v)) + .join('') + // TODO (future PR): support more formats + if (firstChunkString.includes('GIF')) { + throw Error(`GIF images are not supported, please install the @astrojs/image/sharp plugin`) + } + const key = Object.entries(supportedFormats).find(([, { detectors }]) => + detectors.some((detector) => detector.exec(firstChunkString)) + )?.[0] as EncoderKey | undefined + 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)) + // @ts-ignore + return rgba +} + +export async function rotate( + image: ImageData, + numRotations: number +): Promise { + image = ImageData.from(image) + + const m = await preprocessors['rotate'].instantiate() + return await m(image.data, image.width, image.height, { numRotations }) +} + +type ResizeOpts = { image: ImageData } & { width?: number; height?: number } + +export async function resize({ image, width, height }: ResizeOpts) { + 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: ImageData, + opts: { quality?: number } +): Promise { + image = ImageData.from(image) + + const e = supportedFormats['mozjpeg'] + const m = await e.enc() + await maybeDelay() + const quality = opts.quality || e.defaultEncoderOptions.quality + const r = await m.encode(image.data, image.width, image.height, { + ...e.defaultEncoderOptions, + quality, + }) + return r +} + +export async function encodeWebp( + image: ImageData, + opts: { quality?: number } +): Promise { + image = ImageData.from(image) + + const e = supportedFormats['webp'] + const m = await e.enc() + await maybeDelay() + const quality = opts.quality || e.defaultEncoderOptions.quality + const r = await m.encode(image.data, image.width, image.height, { + ...e.defaultEncoderOptions, + quality, + }) + return r +} + +export async function encodeAvif( + image: ImageData, + opts: { quality?: number } +): Promise { + image = ImageData.from(image) + + const e = supportedFormats['avif'] + const m = await e.enc() + await maybeDelay() + const val = e.autoOptimize.min + // AVIF doesn't use a 0-100 quality, default to 75 and convert to cqLevel below + const quality = opts.quality || 75 + 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: quality === 0 ? val : Math.round(val - (quality / 100) * val), + }) + return r +} + +export async function encodePng( + image: ImageData +): Promise { + 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 r +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_enc.d.ts b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_enc.d.ts new file mode 100644 index 000000000000..87b697a11a50 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_enc.d.ts @@ -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 + +export default moduleFactory diff --git a/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.ts b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.ts new file mode 100644 index 000000000000..720508a42e0b --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.ts @@ -0,0 +1,1775 @@ +/* eslint-disable */ +// @ts-nocheck +import { createRequire } from 'module'; +import { dirname, getModuleURL } from '../emscripten-utils.js'; +const require = createRequire(getModuleURL(import.meta.url)); + +var Module = (function () { + return function (Module) { + Module = Module || {} + + var Module = typeof Module !== 'undefined' ? Module : {} + var readyPromiseResolve, readyPromiseReject + Module['ready'] = new Promise(function (resolve, reject) { + readyPromiseResolve = resolve + readyPromiseReject = reject + }) + var moduleOverrides = {} + var key + for (key in Module) { + if (Module.hasOwnProperty(key)) { + moduleOverrides[key] = Module[key] + } + } + var arguments_ = [] + var thisProgram = './this.program' + var quit_ = function (status, toThrow) { + throw toThrow + } + var ENVIRONMENT_IS_WEB = false + var ENVIRONMENT_IS_WORKER = false + var ENVIRONMENT_IS_NODE = true + var scriptDirectory = '' + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory) + } + return scriptDirectory + path + } + var read_, readBinary + var nodeFS + var nodePath + if (ENVIRONMENT_IS_NODE) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = require('path').dirname(scriptDirectory) + '/' + } else { + scriptDirectory = dirname(getModuleURL(import.meta.url)) + '/' + } + read_ = function shell_read(filename, binary) { + if (!nodeFS) nodeFS = require('fs') + if (!nodePath) nodePath = require('path') + filename = nodePath['normalize'](filename) + return nodeFS['readFileSync'](filename, binary ? null : 'utf8') + } + readBinary = function readBinary(filename) { + var ret = read_(filename, true) + if (!ret.buffer) { + ret = new Uint8Array(ret) + } + assert(ret.buffer) + return ret + } + if (process['argv'].length > 1) { + thisProgram = process['argv'][1].replace(/\\/g, '/') + } + arguments_ = process['argv'].slice(2) + quit_ = function (status) { + process['exit'](status) + } + Module['inspect'] = function () { + return '[Emscripten Module object]' + } + } else { + } + var out = Module['print'] || console.log.bind(console) + var err = Module['printErr'] || console.warn.bind(console) + for (key in moduleOverrides) { + if (moduleOverrides.hasOwnProperty(key)) { + Module[key] = moduleOverrides[key] + } + } + moduleOverrides = null + if (Module['arguments']) arguments_ = Module['arguments'] + if (Module['thisProgram']) thisProgram = Module['thisProgram'] + if (Module['quit']) quit_ = Module['quit'] + var tempRet0 = 0 + var setTempRet0 = function (value) { + tempRet0 = value + } + var wasmBinary + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'] + var noExitRuntime = Module['noExitRuntime'] || true + if (typeof WebAssembly !== 'object') { + abort('no native wasm support detected') + } + var wasmMemory + var ABORT = false + var EXITSTATUS + function assert(condition, text) { + if (!condition) { + abort('Assertion failed: ' + text) + } + } + var UTF8Decoder = new TextDecoder('utf8') + function UTF8ArrayToString(heap, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead + var endPtr = idx + while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr + return UTF8Decoder.decode( + heap.subarray + ? heap.subarray(idx, endPtr) + : new Uint8Array(heap.slice(idx, endPtr)) + ) + } + function UTF8ToString(ptr, maxBytesToRead) { + if (!ptr) return '' + var maxPtr = ptr + maxBytesToRead + for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)) + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) return 0 + var startIdx = outIdx + var endIdx = outIdx + maxBytesToWrite - 1 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i) + u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) + } + if (u <= 127) { + if (outIdx >= endIdx) break + heap[outIdx++] = u + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break + heap[outIdx++] = 192 | (u >> 6) + heap[outIdx++] = 128 | (u & 63) + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break + heap[outIdx++] = 224 | (u >> 12) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } else { + if (outIdx + 3 >= endIdx) break + heap[outIdx++] = 240 | (u >> 18) + heap[outIdx++] = 128 | ((u >> 12) & 63) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } + } + heap[outIdx] = 0 + return outIdx - startIdx + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) + } + function lengthBytesUTF8(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) + u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) + if (u <= 127) ++len + else if (u <= 2047) len += 2 + else if (u <= 65535) len += 3 + else len += 4 + } + return len + } + var UTF16Decoder = new TextDecoder('utf-16le') + function UTF16ToString(ptr, maxBytesToRead) { + var endPtr = ptr + var idx = endPtr >> 1 + var maxIdx = idx + maxBytesToRead / 2 + while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx + endPtr = idx << 1 + return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)) + var str = '' + for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { + var codeUnit = HEAP16[(ptr + i * 2) >> 1] + if (codeUnit == 0) break + str += String.fromCharCode(codeUnit) + } + return str + } + function stringToUTF16(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 2) return 0 + maxBytesToWrite -= 2 + var startPtr = outPtr + var numCharsToWrite = + maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i) + HEAP16[outPtr >> 1] = codeUnit + outPtr += 2 + } + HEAP16[outPtr >> 1] = 0 + return outPtr - startPtr + } + function lengthBytesUTF16(str) { + return str.length * 2 + } + function UTF32ToString(ptr, maxBytesToRead) { + var i = 0 + var str = '' + while (!(i >= maxBytesToRead / 4)) { + var utf32 = HEAP32[(ptr + i * 4) >> 2] + if (utf32 == 0) break + ++i + if (utf32 >= 65536) { + var ch = utf32 - 65536 + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) + } else { + str += String.fromCharCode(utf32) + } + } + return str + } + function stringToUTF32(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 4) return 0 + var startPtr = outPtr + var endPtr = startPtr + maxBytesToWrite - 4 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) { + var trailSurrogate = str.charCodeAt(++i) + codeUnit = + (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023) + } + HEAP32[outPtr >> 2] = codeUnit + outPtr += 4 + if (outPtr + 4 > endPtr) break + } + HEAP32[outPtr >> 2] = 0 + return outPtr - startPtr + } + function lengthBytesUTF32(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) ++i + len += 4 + } + return len + } + function writeAsciiToMemory(str, buffer, dontAddNull) { + for (var i = 0; i < str.length; ++i) { + HEAP8[buffer++ >> 0] = str.charCodeAt(i) + } + if (!dontAddNull) HEAP8[buffer >> 0] = 0 + } + function alignUp(x, multiple) { + if (x % multiple > 0) { + x += multiple - (x % multiple) + } + return x + } + var buffer, + HEAP8, + HEAPU8, + HEAP16, + HEAPU16, + HEAP32, + HEAPU32, + HEAPF32, + HEAPF64 + function updateGlobalBufferAndViews(buf) { + buffer = buf + Module['HEAP8'] = HEAP8 = new Int8Array(buf) + Module['HEAP16'] = HEAP16 = new Int16Array(buf) + Module['HEAP32'] = HEAP32 = new Int32Array(buf) + Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf) + Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf) + Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf) + Module['HEAPF32'] = HEAPF32 = new Float32Array(buf) + Module['HEAPF64'] = HEAPF64 = new Float64Array(buf) + } + var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 + var wasmTable + var __ATPRERUN__ = [] + var __ATINIT__ = [] + var __ATPOSTRUN__ = [] + var runtimeInitialized = false + var runtimeExited = false + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') + Module['preRun'] = [Module['preRun']] + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()) + } + } + callRuntimeCallbacks(__ATPRERUN__) + } + function initRuntime() { + runtimeInitialized = true + callRuntimeCallbacks(__ATINIT__) + } + function exitRuntime() { + runtimeExited = true + } + function postRun() { + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') + Module['postRun'] = [Module['postRun']] + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()) + } + } + callRuntimeCallbacks(__ATPOSTRUN__) + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb) + } + function addOnInit(cb) { + __ATINIT__.unshift(cb) + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb) + } + var runDependencies = 0 + var runDependencyWatcher = null + var dependenciesFulfilled = null + function addRunDependency(id) { + runDependencies++ + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + } + function removeRunDependency(id) { + runDependencies-- + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher) + runDependencyWatcher = null + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled + dependenciesFulfilled = null + callback() + } + } + } + Module['preloadedImages'] = {} + Module['preloadedAudios'] = {} + function abort(what) { + if (Module['onAbort']) { + Module['onAbort'](what) + } + what += '' + err(what) + ABORT = true + EXITSTATUS = 1 + what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' + var e = new WebAssembly.RuntimeError(what) + readyPromiseReject(e) + throw e + } + var dataURIPrefix = 'data:application/octet-stream;base64,' + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix) + } + if (Module['locateFile']) { + var wasmBinaryFile = 'mozjpeg_node_dec.wasm' + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile) + } + } else { + throw new Error('invariant') + } + function getBinary(file) { + try { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary) + } + if (readBinary) { + return readBinary(file) + } else { + throw 'both async and sync fetching of the wasm failed' + } + } catch (err) { + abort(err) + } + } + function getBinaryPromise() { + return Promise.resolve().then(function () { + return getBinary(wasmBinaryFile) + }) + } + function createWasm() { + var info = { a: asmLibraryArg } + function receiveInstance(instance, module) { + var exports = instance.exports + Module['asm'] = exports + wasmMemory = Module['asm']['z'] + updateGlobalBufferAndViews(wasmMemory.buffer) + wasmTable = Module['asm']['F'] + addOnInit(Module['asm']['A']) + removeRunDependency('wasm-instantiate') + } + addRunDependency('wasm-instantiate') + function receiveInstantiationResult(result) { + receiveInstance(result['instance']) + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise() + .then(function (binary) { + var result = WebAssembly.instantiate(binary, info) + return result + }) + .then(receiver, function (reason) { + err('failed to asynchronously prepare wasm: ' + reason) + abort(reason) + }) + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult) + } + if (Module['instantiateWasm']) { + try { + var exports = Module['instantiateWasm'](info, receiveInstance) + return exports + } catch (e) { + err('Module.instantiateWasm callback failed with error: ' + e) + return false + } + } + instantiateAsync().catch(readyPromiseReject) + return {} + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + var callback = callbacks.shift() + if (typeof callback == 'function') { + callback(Module) + continue + } + var func = callback.func + if (typeof func === 'number') { + if (callback.arg === undefined) { + wasmTable.get(func)() + } else { + wasmTable.get(func)(callback.arg) + } + } else { + func(callback.arg === undefined ? null : callback.arg) + } + } + } + var runtimeKeepaliveCounter = 0 + function keepRuntimeAlive() { + return noExitRuntime || runtimeKeepaliveCounter > 0 + } + function _atexit(func, arg) {} + function ___cxa_thread_atexit(a0, a1) { + return _atexit(a0, a1) + } + function __embind_register_bigint( + primitiveType, + name, + size, + minRange, + maxRange + ) {} + function getShiftFromSize(size) { + switch (size) { + case 1: + return 0 + case 2: + return 1 + case 4: + return 2 + case 8: + return 3 + default: + throw new TypeError('Unknown type size: ' + size) + } + } + function embind_init_charCodes() { + var codes = new Array(256) + for (var i = 0; i < 256; ++i) { + codes[i] = String.fromCharCode(i) + } + embind_charCodes = codes + } + var embind_charCodes = undefined + function readLatin1String(ptr) { + var ret = '' + var c = ptr + while (HEAPU8[c]) { + ret += embind_charCodes[HEAPU8[c++]] + } + return ret + } + var awaitingDependencies = {} + var registeredTypes = {} + var typeDependencies = {} + var char_0 = 48 + var char_9 = 57 + function makeLegalFunctionName(name) { + if (undefined === name) { + return '_unknown' + } + name = name.replace(/[^a-zA-Z0-9_]/g, '$') + var f = name.charCodeAt(0) + if (f >= char_0 && f <= char_9) { + return '_' + name + } else { + return name + } + } + function createNamedFunction(name, body) { + name = makeLegalFunctionName(name) + return new Function( + 'body', + 'return function ' + + name + + '() {\n' + + ' "use strict";' + + ' return body.apply(this, arguments);\n' + + '};\n' + )(body) + } + function extendError(baseErrorType, errorName) { + var errorClass = createNamedFunction(errorName, function (message) { + this.name = errorName + this.message = message + var stack = new Error(message).stack + if (stack !== undefined) { + this.stack = + this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '') + } + }) + errorClass.prototype = Object.create(baseErrorType.prototype) + errorClass.prototype.constructor = errorClass + errorClass.prototype.toString = function () { + if (this.message === undefined) { + return this.name + } else { + return this.name + ': ' + this.message + } + } + return errorClass + } + var BindingError = undefined + function throwBindingError(message) { + throw new BindingError(message) + } + var InternalError = undefined + function throwInternalError(message) { + throw new InternalError(message) + } + function whenDependentTypesAreResolved( + myTypes, + dependentTypes, + getTypeConverters + ) { + myTypes.forEach(function (type) { + typeDependencies[type] = dependentTypes + }) + function onComplete(typeConverters) { + var myTypeConverters = getTypeConverters(typeConverters) + if (myTypeConverters.length !== myTypes.length) { + throwInternalError('Mismatched type converter count') + } + for (var i = 0; i < myTypes.length; ++i) { + registerType(myTypes[i], myTypeConverters[i]) + } + } + var typeConverters = new Array(dependentTypes.length) + var unregisteredTypes = [] + var registered = 0 + dependentTypes.forEach(function (dt, i) { + if (registeredTypes.hasOwnProperty(dt)) { + typeConverters[i] = registeredTypes[dt] + } else { + unregisteredTypes.push(dt) + if (!awaitingDependencies.hasOwnProperty(dt)) { + awaitingDependencies[dt] = [] + } + awaitingDependencies[dt].push(function () { + typeConverters[i] = registeredTypes[dt] + ++registered + if (registered === unregisteredTypes.length) { + onComplete(typeConverters) + } + }) + } + }) + if (0 === unregisteredTypes.length) { + onComplete(typeConverters) + } + } + function registerType(rawType, registeredInstance, options) { + options = options || {} + if (!('argPackAdvance' in registeredInstance)) { + throw new TypeError( + 'registerType registeredInstance requires argPackAdvance' + ) + } + var name = registeredInstance.name + if (!rawType) { + throwBindingError( + 'type "' + name + '" must have a positive integer typeid pointer' + ) + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return + } else { + throwBindingError("Cannot register type '" + name + "' twice") + } + } + registeredTypes[rawType] = registeredInstance + delete typeDependencies[rawType] + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType] + delete awaitingDependencies[rawType] + callbacks.forEach(function (cb) { + cb() + }) + } + } + function __embind_register_bool( + rawType, + name, + size, + trueValue, + falseValue + ) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (wt) { + return !!wt + }, + toWireType: function (destructors, o) { + return o ? trueValue : falseValue + }, + argPackAdvance: 8, + readValueFromPointer: function (pointer) { + var heap + if (size === 1) { + heap = HEAP8 + } else if (size === 2) { + heap = HEAP16 + } else if (size === 4) { + heap = HEAP32 + } else { + throw new TypeError('Unknown boolean type size: ' + name) + } + return this['fromWireType'](heap[pointer >> shift]) + }, + destructorFunction: null, + }) + } + var emval_free_list = [] + var emval_handle_array = [ + {}, + { value: undefined }, + { value: null }, + { value: true }, + { value: false }, + ] + function __emval_decref(handle) { + if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { + emval_handle_array[handle] = undefined + emval_free_list.push(handle) + } + } + function count_emval_handles() { + var count = 0 + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + ++count + } + } + return count + } + function get_first_emval() { + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + return emval_handle_array[i] + } + } + return null + } + function init_emval() { + Module['count_emval_handles'] = count_emval_handles + Module['get_first_emval'] = get_first_emval + } + function __emval_register(value) { + switch (value) { + case undefined: { + return 1 + } + case null: { + return 2 + } + case true: { + return 3 + } + case false: { + return 4 + } + default: { + var handle = emval_free_list.length + ? emval_free_list.pop() + : emval_handle_array.length + emval_handle_array[handle] = { refcount: 1, value: value } + return handle + } + } + } + function simpleReadValueFromPointer(pointer) { + return this['fromWireType'](HEAPU32[pointer >> 2]) + } + function __embind_register_emval(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (handle) { + var rv = emval_handle_array[handle].value + __emval_decref(handle) + return rv + }, + toWireType: function (destructors, value) { + return __emval_register(value) + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: null, + }) + } + function _embind_repr(v) { + if (v === null) { + return 'null' + } + var t = typeof v + if (t === 'object' || t === 'array' || t === 'function') { + return v.toString() + } else { + return '' + v + } + } + function floatReadValueFromPointer(name, shift) { + switch (shift) { + case 2: + return function (pointer) { + return this['fromWireType'](HEAPF32[pointer >> 2]) + } + case 3: + return function (pointer) { + return this['fromWireType'](HEAPF64[pointer >> 3]) + } + default: + throw new TypeError('Unknown float type: ' + name) + } + } + function __embind_register_float(rawType, name, size) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (value) { + return value + }, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + return value + }, + argPackAdvance: 8, + readValueFromPointer: floatReadValueFromPointer(name, shift), + destructorFunction: null, + }) + } + function new_(constructor, argumentList) { + if (!(constructor instanceof Function)) { + throw new TypeError( + 'new_ called with constructor type ' + + typeof constructor + + ' which is not a function' + ) + } + var dummy = createNamedFunction( + constructor.name || 'unknownFunctionName', + function () {} + ) + dummy.prototype = constructor.prototype + var obj = new dummy() + var r = constructor.apply(obj, argumentList) + return r instanceof Object ? r : obj + } + function runDestructors(destructors) { + while (destructors.length) { + var ptr = destructors.pop() + var del = destructors.pop() + del(ptr) + } + } + function craftInvokerFunction( + humanName, + argTypes, + classType, + cppInvokerFunc, + cppTargetFunc + ) { + var argCount = argTypes.length + if (argCount < 2) { + throwBindingError( + "argTypes array size mismatch! Must at least get return value and 'this' types!" + ) + } + var isClassMethodFunc = argTypes[1] !== null && classType !== null + var needsDestructorStack = false + for (var i = 1; i < argTypes.length; ++i) { + if ( + argTypes[i] !== null && + argTypes[i].destructorFunction === undefined + ) { + needsDestructorStack = true + break + } + } + var returns = argTypes[0].name !== 'void' + var argsList = '' + var argsListWired = '' + for (var i = 0; i < argCount - 2; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired' + } + var invokerFnBody = + 'return function ' + + makeLegalFunctionName(humanName) + + '(' + + argsList + + ') {\n' + + 'if (arguments.length !== ' + + (argCount - 2) + + ') {\n' + + "throwBindingError('function " + + humanName + + " called with ' + arguments.length + ' arguments, expected " + + (argCount - 2) + + " args!');\n" + + '}\n' + if (needsDestructorStack) { + invokerFnBody += 'var destructors = [];\n' + } + var dtorStack = needsDestructorStack ? 'destructors' : 'null' + var args1 = [ + 'throwBindingError', + 'invoker', + 'fn', + 'runDestructors', + 'retType', + 'classParam', + ] + var args2 = [ + throwBindingError, + cppInvokerFunc, + cppTargetFunc, + runDestructors, + argTypes[0], + argTypes[1], + ] + if (isClassMethodFunc) { + invokerFnBody += + 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n' + } + for (var i = 0; i < argCount - 2; ++i) { + invokerFnBody += + 'var arg' + + i + + 'Wired = argType' + + i + + '.toWireType(' + + dtorStack + + ', arg' + + i + + '); // ' + + argTypes[i + 2].name + + '\n' + args1.push('argType' + i) + args2.push(argTypes[i + 2]) + } + if (isClassMethodFunc) { + argsListWired = + 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired + } + invokerFnBody += + (returns ? 'var rv = ' : '') + + 'invoker(fn' + + (argsListWired.length > 0 ? ', ' : '') + + argsListWired + + ');\n' + if (needsDestructorStack) { + invokerFnBody += 'runDestructors(destructors);\n' + } else { + for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { + var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired' + if (argTypes[i].destructorFunction !== null) { + invokerFnBody += + paramName + + '_dtor(' + + paramName + + '); // ' + + argTypes[i].name + + '\n' + args1.push(paramName + '_dtor') + args2.push(argTypes[i].destructorFunction) + } + } + } + if (returns) { + invokerFnBody += + 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n' + } else { + } + invokerFnBody += '}\n' + args1.push(invokerFnBody) + var invokerFunction = new_(Function, args1).apply(null, args2) + return invokerFunction + } + function ensureOverloadTable(proto, methodName, humanName) { + if (undefined === proto[methodName].overloadTable) { + var prevFunc = proto[methodName] + proto[methodName] = function () { + if ( + !proto[methodName].overloadTable.hasOwnProperty(arguments.length) + ) { + throwBindingError( + "Function '" + + humanName + + "' called with an invalid number of arguments (" + + arguments.length + + ') - expects one of (' + + proto[methodName].overloadTable + + ')!' + ) + } + return proto[methodName].overloadTable[arguments.length].apply( + this, + arguments + ) + } + proto[methodName].overloadTable = [] + proto[methodName].overloadTable[prevFunc.argCount] = prevFunc + } + } + function exposePublicSymbol(name, value, numArguments) { + if (Module.hasOwnProperty(name)) { + if ( + undefined === numArguments || + (undefined !== Module[name].overloadTable && + undefined !== Module[name].overloadTable[numArguments]) + ) { + throwBindingError("Cannot register public name '" + name + "' twice") + } + ensureOverloadTable(Module, name, name) + if (Module.hasOwnProperty(numArguments)) { + throwBindingError( + 'Cannot register multiple overloads of a function with the same number of arguments (' + + numArguments + + ')!' + ) + } + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + if (undefined !== numArguments) { + Module[name].numArguments = numArguments + } + } + } + function heap32VectorToArray(count, firstElement) { + var array = [] + for (var i = 0; i < count; i++) { + array.push(HEAP32[(firstElement >> 2) + i]) + } + return array + } + function replacePublicSymbol(name, value, numArguments) { + if (!Module.hasOwnProperty(name)) { + throwInternalError('Replacing nonexistent public symbol') + } + if ( + undefined !== Module[name].overloadTable && + undefined !== numArguments + ) { + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + Module[name].argCount = numArguments + } + } + function dynCallLegacy(sig, ptr, args) { + var f = Module['dynCall_' + sig] + return args && args.length + ? f.apply(null, [ptr].concat(args)) + : f.call(null, ptr) + } + function dynCall(sig, ptr, args) { + if (sig.includes('j')) { + return dynCallLegacy(sig, ptr, args) + } + return wasmTable.get(ptr).apply(null, args) + } + function getDynCaller(sig, ptr) { + var argCache = [] + return function () { + argCache.length = arguments.length + for (var i = 0; i < arguments.length; i++) { + argCache[i] = arguments[i] + } + return dynCall(sig, ptr, argCache) + } + } + function embind__requireFunction(signature, rawFunction) { + signature = readLatin1String(signature) + function makeDynCaller() { + if (signature.includes('j')) { + return getDynCaller(signature, rawFunction) + } + return wasmTable.get(rawFunction) + } + var fp = makeDynCaller() + if (typeof fp !== 'function') { + throwBindingError( + 'unknown function pointer with signature ' + + signature + + ': ' + + rawFunction + ) + } + return fp + } + var UnboundTypeError = undefined + function getTypeName(type) { + var ptr = ___getTypeName(type) + var rv = readLatin1String(ptr) + _free(ptr) + return rv + } + function throwUnboundTypeError(message, types) { + var unboundTypes = [] + var seen = {} + function visit(type) { + if (seen[type]) { + return + } + if (registeredTypes[type]) { + return + } + if (typeDependencies[type]) { + typeDependencies[type].forEach(visit) + return + } + unboundTypes.push(type) + seen[type] = true + } + types.forEach(visit) + throw new UnboundTypeError( + message + ': ' + unboundTypes.map(getTypeName).join([', ']) + ) + } + function __embind_register_function( + name, + argCount, + rawArgTypesAddr, + signature, + rawInvoker, + fn + ) { + var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr) + name = readLatin1String(name) + rawInvoker = embind__requireFunction(signature, rawInvoker) + exposePublicSymbol( + name, + function () { + throwUnboundTypeError( + 'Cannot call ' + name + ' due to unbound types', + argTypes + ) + }, + argCount - 1 + ) + whenDependentTypesAreResolved([], argTypes, function (argTypes) { + var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1)) + replacePublicSymbol( + name, + craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn), + argCount - 1 + ) + return [] + }) + } + function integerReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return signed + ? function readS8FromPointer(pointer) { + return HEAP8[pointer] + } + : function readU8FromPointer(pointer) { + return HEAPU8[pointer] + } + case 1: + return signed + ? function readS16FromPointer(pointer) { + return HEAP16[pointer >> 1] + } + : function readU16FromPointer(pointer) { + return HEAPU16[pointer >> 1] + } + case 2: + return signed + ? function readS32FromPointer(pointer) { + return HEAP32[pointer >> 2] + } + : function readU32FromPointer(pointer) { + return HEAPU32[pointer >> 2] + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_integer( + primitiveType, + name, + size, + minRange, + maxRange + ) { + name = readLatin1String(name) + if (maxRange === -1) { + maxRange = 4294967295 + } + var shift = getShiftFromSize(size) + var fromWireType = function (value) { + return value + } + if (minRange === 0) { + var bitshift = 32 - 8 * size + fromWireType = function (value) { + return (value << bitshift) >>> bitshift + } + } + var isUnsignedType = name.includes('unsigned') + registerType(primitiveType, { + name: name, + fromWireType: fromWireType, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + if (value < minRange || value > maxRange) { + throw new TypeError( + 'Passing a number "' + + _embind_repr(value) + + '" from JS side to C/C++ side to an argument of type "' + + name + + '", which is outside the valid range [' + + minRange + + ', ' + + maxRange + + ']!' + ) + } + return isUnsignedType ? value >>> 0 : value | 0 + }, + argPackAdvance: 8, + readValueFromPointer: integerReadValueFromPointer( + name, + shift, + minRange !== 0 + ), + destructorFunction: null, + }) + } + function __embind_register_memory_view(rawType, dataTypeIndex, name) { + var typeMapping = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + ] + var TA = typeMapping[dataTypeIndex] + function decodeMemoryView(handle) { + handle = handle >> 2 + var heap = HEAPU32 + var size = heap[handle] + var data = heap[handle + 1] + return new TA(buffer, data, size) + } + name = readLatin1String(name) + registerType( + rawType, + { + name: name, + fromWireType: decodeMemoryView, + argPackAdvance: 8, + readValueFromPointer: decodeMemoryView, + }, + { ignoreDuplicateRegistrations: true } + ) + } + function __embind_register_std_string(rawType, name) { + name = readLatin1String(name) + var stdStringIsUTF8 = name === 'std::string' + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var str + if (stdStringIsUTF8) { + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i + if (i == length || HEAPU8[currentBytePtr] == 0) { + var maxRead = currentBytePtr - decodeStartPtr + var stringSegment = UTF8ToString(decodeStartPtr, maxRead) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + 1 + } + } + } else { + var a = new Array(length) + for (var i = 0; i < length; ++i) { + a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) + } + str = a.join('') + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value) + } + var getLength + var valueIsOfTypeString = typeof value === 'string' + if ( + !( + valueIsOfTypeString || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int8Array + ) + ) { + throwBindingError('Cannot pass non-string to std::string') + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + getLength = function () { + return lengthBytesUTF8(value) + } + } else { + getLength = function () { + return value.length + } + } + var length = getLength() + var ptr = _malloc(4 + length + 1) + HEAPU32[ptr >> 2] = length + if (stdStringIsUTF8 && valueIsOfTypeString) { + stringToUTF8(value, ptr + 4, length + 1) + } else { + if (valueIsOfTypeString) { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i) + if (charCode > 255) { + _free(ptr) + throwBindingError( + 'String has UTF-16 code units that do not fit in 8 bits' + ) + } + HEAPU8[ptr + 4 + i] = charCode + } + } else { + for (var i = 0; i < length; ++i) { + HEAPU8[ptr + 4 + i] = value[i] + } + } + } + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_std_wstring(rawType, charSize, name) { + name = readLatin1String(name) + var decodeString, encodeString, getHeap, lengthBytesUTF, shift + if (charSize === 2) { + decodeString = UTF16ToString + encodeString = stringToUTF16 + lengthBytesUTF = lengthBytesUTF16 + getHeap = function () { + return HEAPU16 + } + shift = 1 + } else if (charSize === 4) { + decodeString = UTF32ToString + encodeString = stringToUTF32 + lengthBytesUTF = lengthBytesUTF32 + getHeap = function () { + return HEAPU32 + } + shift = 2 + } + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var HEAP = getHeap() + var str + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i * charSize + if (i == length || HEAP[currentBytePtr >> shift] == 0) { + var maxReadBytes = currentBytePtr - decodeStartPtr + var stringSegment = decodeString(decodeStartPtr, maxReadBytes) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + charSize + } + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (!(typeof value === 'string')) { + throwBindingError( + 'Cannot pass non-string to C++ string type ' + name + ) + } + var length = lengthBytesUTF(value) + var ptr = _malloc(4 + length + charSize) + HEAPU32[ptr >> 2] = length >> shift + encodeString(value, ptr + 4, length + charSize) + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_void(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + isVoid: true, + name: name, + argPackAdvance: 0, + fromWireType: function () { + return undefined + }, + toWireType: function (destructors, o) { + return undefined + }, + }) + } + var emval_symbols = {} + function getStringOrSymbol(address) { + var symbol = emval_symbols[address] + if (symbol === undefined) { + return readLatin1String(address) + } else { + return symbol + } + } + function emval_get_global() { + if (typeof globalThis === 'object') { + return globalThis + } + return (function () { + return Function + })()('return this')() + } + function __emval_get_global(name) { + if (name === 0) { + return __emval_register(emval_get_global()) + } else { + name = getStringOrSymbol(name) + return __emval_register(emval_get_global()[name]) + } + } + function __emval_incref(handle) { + if (handle > 4) { + emval_handle_array[handle].refcount += 1 + } + } + function requireRegisteredType(rawType, humanName) { + var impl = registeredTypes[rawType] + if (undefined === impl) { + throwBindingError( + humanName + ' has unknown type ' + getTypeName(rawType) + ) + } + return impl + } + function craftEmvalAllocator(argCount) { + var argsList = '' + for (var i = 0; i < argCount; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + } + var functionBody = + 'return function emval_allocator_' + + argCount + + '(constructor, argTypes, args) {\n' + for (var i = 0; i < argCount; ++i) { + functionBody += + 'var argType' + + i + + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + + i + + '], "parameter ' + + i + + '");\n' + + 'var arg' + + i + + ' = argType' + + i + + '.readValueFromPointer(args);\n' + + 'args += argType' + + i + + "['argPackAdvance'];\n" + } + functionBody += + 'var obj = new constructor(' + + argsList + + ');\n' + + 'return __emval_register(obj);\n' + + '}\n' + return new Function( + 'requireRegisteredType', + 'Module', + '__emval_register', + functionBody + )(requireRegisteredType, Module, __emval_register) + } + var emval_newers = {} + function requireHandle(handle) { + if (!handle) { + throwBindingError('Cannot use deleted val. handle = ' + handle) + } + return emval_handle_array[handle].value + } + function __emval_new(handle, argCount, argTypes, args) { + handle = requireHandle(handle) + var newer = emval_newers[argCount] + if (!newer) { + newer = craftEmvalAllocator(argCount) + emval_newers[argCount] = newer + } + return newer(handle, argTypes, args) + } + function _abort() { + abort() + } + function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.copyWithin(dest, src, src + num) + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16) + updateGlobalBufferAndViews(wasmMemory.buffer) + return 1 + } catch (e) {} + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length + requestedSize = requestedSize >>> 0 + var maxHeapSize = 2147483648 + if (requestedSize > maxHeapSize) { + return false + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown) + overGrownHeapSize = Math.min( + overGrownHeapSize, + requestedSize + 100663296 + ) + var newSize = Math.min( + maxHeapSize, + alignUp(Math.max(requestedSize, overGrownHeapSize), 65536) + ) + var replacement = emscripten_realloc_buffer(newSize) + if (replacement) { + return true + } + } + return false + } + var ENV = {} + function getExecutableName() { + return thisProgram || './this.program' + } + function getEnvStrings() { + if (!getEnvStrings.strings) { + var lang = + ( + (typeof navigator === 'object' && + navigator.languages && + navigator.languages[0]) || + 'C' + ).replace('-', '_') + '.UTF-8' + var env = { + USER: 'web_user', + LOGNAME: 'web_user', + PATH: '/', + PWD: '/', + HOME: '/home/web_user', + LANG: lang, + _: getExecutableName(), + } + for (var x in ENV) { + env[x] = ENV[x] + } + var strings = [] + for (var x in env) { + strings.push(x + '=' + env[x]) + } + getEnvStrings.strings = strings + } + return getEnvStrings.strings + } + var SYSCALLS = { + mappings: {}, + buffers: [null, [], []], + printChar: function (stream, curr) { + var buffer = SYSCALLS.buffers[stream] + if (curr === 0 || curr === 10) { + ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)) + buffer.length = 0 + } else { + buffer.push(curr) + } + }, + varargs: undefined, + get: function () { + SYSCALLS.varargs += 4 + var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2] + return ret + }, + getStr: function (ptr) { + var ret = UTF8ToString(ptr) + return ret + }, + get64: function (low, high) { + return low + }, + } + function _environ_get(__environ, environ_buf) { + var bufSize = 0 + getEnvStrings().forEach(function (string, i) { + var ptr = environ_buf + bufSize + HEAP32[(__environ + i * 4) >> 2] = ptr + writeAsciiToMemory(string, ptr) + bufSize += string.length + 1 + }) + return 0 + } + function _environ_sizes_get(penviron_count, penviron_buf_size) { + var strings = getEnvStrings() + HEAP32[penviron_count >> 2] = strings.length + var bufSize = 0 + strings.forEach(function (string) { + bufSize += string.length + 1 + }) + HEAP32[penviron_buf_size >> 2] = bufSize + return 0 + } + function _exit(status) { + exit(status) + } + function _fd_close(fd) { + return 0 + } + function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {} + function _fd_write(fd, iov, iovcnt, pnum) { + var num = 0 + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAP32[(iov + i * 8) >> 2] + var len = HEAP32[(iov + (i * 8 + 4)) >> 2] + for (var j = 0; j < len; j++) { + SYSCALLS.printChar(fd, HEAPU8[ptr + j]) + } + num += len + } + HEAP32[pnum >> 2] = num + return 0 + } + function _setTempRet0(val) { + setTempRet0(val) + } + embind_init_charCodes() + BindingError = Module['BindingError'] = extendError(Error, 'BindingError') + InternalError = Module['InternalError'] = extendError( + Error, + 'InternalError' + ) + init_emval() + UnboundTypeError = Module['UnboundTypeError'] = extendError( + Error, + 'UnboundTypeError' + ) + var asmLibraryArg = { + e: ___cxa_thread_atexit, + q: __embind_register_bigint, + m: __embind_register_bool, + x: __embind_register_emval, + l: __embind_register_float, + o: __embind_register_function, + b: __embind_register_integer, + a: __embind_register_memory_view, + h: __embind_register_std_string, + g: __embind_register_std_wstring, + n: __embind_register_void, + c: __emval_decref, + d: __emval_get_global, + i: __emval_incref, + j: __emval_new, + k: _abort, + s: _emscripten_memcpy_big, + f: _emscripten_resize_heap, + t: _environ_get, + u: _environ_sizes_get, + y: _exit, + w: _fd_close, + p: _fd_seek, + v: _fd_write, + r: _setTempRet0, + } + var asm = createWasm() + var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () { + return (___wasm_call_ctors = Module['___wasm_call_ctors'] = + Module['asm']['A']).apply(null, arguments) + }) + var _malloc = (Module['_malloc'] = function () { + return (_malloc = Module['_malloc'] = Module['asm']['B']).apply( + null, + arguments + ) + }) + var _free = (Module['_free'] = function () { + return (_free = Module['_free'] = Module['asm']['C']).apply( + null, + arguments + ) + }) + var ___getTypeName = (Module['___getTypeName'] = function () { + return (___getTypeName = Module['___getTypeName'] = + Module['asm']['D']).apply(null, arguments) + }) + var ___embind_register_native_and_builtin_types = (Module[ + '___embind_register_native_and_builtin_types' + ] = function () { + return (___embind_register_native_and_builtin_types = Module[ + '___embind_register_native_and_builtin_types' + ] = + Module['asm']['E']).apply(null, arguments) + }) + var dynCall_jiji = (Module['dynCall_jiji'] = function () { + return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['G']).apply( + null, + arguments + ) + }) + var calledRun + function ExitStatus(status) { + this.name = 'ExitStatus' + this.message = 'Program terminated with exit(' + status + ')' + this.status = status + } + dependenciesFulfilled = function runCaller() { + if (!calledRun) run() + if (!calledRun) dependenciesFulfilled = runCaller + } + function run(args) { + args = args || arguments_ + if (runDependencies > 0) { + return + } + preRun() + if (runDependencies > 0) { + return + } + function doRun() { + if (calledRun) return + calledRun = true + Module['calledRun'] = true + if (ABORT) return + initRuntime() + readyPromiseResolve(Module) + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() + postRun() + } + if (Module['setStatus']) { + Module['setStatus']('Running...') + setTimeout(function () { + setTimeout(function () { + Module['setStatus']('') + }, 1) + doRun() + }, 1) + } else { + doRun() + } + } + Module['run'] = run + function exit(status, implicit) { + EXITSTATUS = status + if (implicit && keepRuntimeAlive() && status === 0) { + return + } + if (keepRuntimeAlive()) { + } else { + exitRuntime() + if (Module['onExit']) Module['onExit'](status) + ABORT = true + } + quit_(status, new ExitStatus(status)) + } + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') + Module['preInit'] = [Module['preInit']] + while (Module['preInit'].length > 0) { + Module['preInit'].pop()() + } + } + run() + + return Module.ready + } +})() +export default Module diff --git a/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.wasm b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.wasm new file mode 100644 index 000000000000..abf13d75f271 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.ts b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.ts new file mode 100644 index 000000000000..b5fee7365cca --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.ts @@ -0,0 +1,1901 @@ +/* eslint-disable */ +// @ts-nocheck +import { createRequire } from 'module'; +import { dirname, getModuleURL } from '../emscripten-utils.js'; +const require = createRequire(getModuleURL(import.meta.url)); + +var Module = (function () { + return function (Module) { + Module = Module || {} + + var Module = typeof Module !== 'undefined' ? Module : {} + var readyPromiseResolve, readyPromiseReject + Module['ready'] = new Promise(function (resolve, reject) { + readyPromiseResolve = resolve + readyPromiseReject = reject + }) + var moduleOverrides = {} + var key + for (key in Module) { + if (Module.hasOwnProperty(key)) { + moduleOverrides[key] = Module[key] + } + } + var arguments_ = [] + var thisProgram = './this.program' + var quit_ = function (status, toThrow) { + throw toThrow + } + var ENVIRONMENT_IS_WEB = false + var ENVIRONMENT_IS_WORKER = false + var ENVIRONMENT_IS_NODE = true + var scriptDirectory = '' + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory) + } + return scriptDirectory + path + } + var read_, readBinary + var nodeFS + var nodePath + if (ENVIRONMENT_IS_NODE) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = require('path').dirname(scriptDirectory) + '/' + } else { + scriptDirectory = dirname(getModuleURL(import.meta.url)) + '/' + } + read_ = function shell_read(filename, binary) { + if (!nodeFS) nodeFS = require('fs') + if (!nodePath) nodePath = require('path') + filename = nodePath['normalize'](filename) + return nodeFS['readFileSync'](filename, binary ? null : 'utf8') + } + readBinary = function readBinary(filename) { + var ret = read_(filename, true) + if (!ret.buffer) { + ret = new Uint8Array(ret) + } + assert(ret.buffer) + return ret + } + if (process['argv'].length > 1) { + thisProgram = process['argv'][1].replace(/\\/g, '/') + } + arguments_ = process['argv'].slice(2) + quit_ = function (status) { + process['exit'](status) + } + Module['inspect'] = function () { + return '[Emscripten Module object]' + } + } else { + } + var out = Module['print'] || console.log.bind(console) + var err = Module['printErr'] || console.warn.bind(console) + for (key in moduleOverrides) { + if (moduleOverrides.hasOwnProperty(key)) { + Module[key] = moduleOverrides[key] + } + } + moduleOverrides = null + if (Module['arguments']) arguments_ = Module['arguments'] + if (Module['thisProgram']) thisProgram = Module['thisProgram'] + if (Module['quit']) quit_ = Module['quit'] + var tempRet0 = 0 + var setTempRet0 = function (value) { + tempRet0 = value + } + var wasmBinary + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'] + var noExitRuntime = Module['noExitRuntime'] || true + if (typeof WebAssembly !== 'object') { + abort('no native wasm support detected') + } + var wasmMemory + var ABORT = false + var EXITSTATUS + function assert(condition, text) { + if (!condition) { + abort('Assertion failed: ' + text) + } + } + var UTF8Decoder = new TextDecoder('utf8') + function UTF8ArrayToString(heap, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead + var endPtr = idx + while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr + return UTF8Decoder.decode( + heap.subarray + ? heap.subarray(idx, endPtr) + : new Uint8Array(heap.slice(idx, endPtr)) + ) + } + function UTF8ToString(ptr, maxBytesToRead) { + if (!ptr) return '' + var maxPtr = ptr + maxBytesToRead + for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)) + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) return 0 + var startIdx = outIdx + var endIdx = outIdx + maxBytesToWrite - 1 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i) + u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) + } + if (u <= 127) { + if (outIdx >= endIdx) break + heap[outIdx++] = u + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break + heap[outIdx++] = 192 | (u >> 6) + heap[outIdx++] = 128 | (u & 63) + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break + heap[outIdx++] = 224 | (u >> 12) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } else { + if (outIdx + 3 >= endIdx) break + heap[outIdx++] = 240 | (u >> 18) + heap[outIdx++] = 128 | ((u >> 12) & 63) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } + } + heap[outIdx] = 0 + return outIdx - startIdx + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) + } + function lengthBytesUTF8(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) + u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) + if (u <= 127) ++len + else if (u <= 2047) len += 2 + else if (u <= 65535) len += 3 + else len += 4 + } + return len + } + var UTF16Decoder = new TextDecoder('utf-16le') + function UTF16ToString(ptr, maxBytesToRead) { + var endPtr = ptr + var idx = endPtr >> 1 + var maxIdx = idx + maxBytesToRead / 2 + while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx + endPtr = idx << 1 + return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)) + var str = '' + for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { + var codeUnit = HEAP16[(ptr + i * 2) >> 1] + if (codeUnit == 0) break + str += String.fromCharCode(codeUnit) + } + return str + } + function stringToUTF16(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 2) return 0 + maxBytesToWrite -= 2 + var startPtr = outPtr + var numCharsToWrite = + maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i) + HEAP16[outPtr >> 1] = codeUnit + outPtr += 2 + } + HEAP16[outPtr >> 1] = 0 + return outPtr - startPtr + } + function lengthBytesUTF16(str) { + return str.length * 2 + } + function UTF32ToString(ptr, maxBytesToRead) { + var i = 0 + var str = '' + while (!(i >= maxBytesToRead / 4)) { + var utf32 = HEAP32[(ptr + i * 4) >> 2] + if (utf32 == 0) break + ++i + if (utf32 >= 65536) { + var ch = utf32 - 65536 + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) + } else { + str += String.fromCharCode(utf32) + } + } + return str + } + function stringToUTF32(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 4) return 0 + var startPtr = outPtr + var endPtr = startPtr + maxBytesToWrite - 4 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) { + var trailSurrogate = str.charCodeAt(++i) + codeUnit = + (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023) + } + HEAP32[outPtr >> 2] = codeUnit + outPtr += 4 + if (outPtr + 4 > endPtr) break + } + HEAP32[outPtr >> 2] = 0 + return outPtr - startPtr + } + function lengthBytesUTF32(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) ++i + len += 4 + } + return len + } + function writeAsciiToMemory(str, buffer, dontAddNull) { + for (var i = 0; i < str.length; ++i) { + HEAP8[buffer++ >> 0] = str.charCodeAt(i) + } + if (!dontAddNull) HEAP8[buffer >> 0] = 0 + } + function alignUp(x, multiple) { + if (x % multiple > 0) { + x += multiple - (x % multiple) + } + return x + } + var buffer, + HEAP8, + HEAPU8, + HEAP16, + HEAPU16, + HEAP32, + HEAPU32, + HEAPF32, + HEAPF64 + function updateGlobalBufferAndViews(buf) { + buffer = buf + Module['HEAP8'] = HEAP8 = new Int8Array(buf) + Module['HEAP16'] = HEAP16 = new Int16Array(buf) + Module['HEAP32'] = HEAP32 = new Int32Array(buf) + Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf) + Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf) + Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf) + Module['HEAPF32'] = HEAPF32 = new Float32Array(buf) + Module['HEAPF64'] = HEAPF64 = new Float64Array(buf) + } + var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 + var wasmTable + var __ATPRERUN__ = [] + var __ATINIT__ = [] + var __ATPOSTRUN__ = [] + var runtimeInitialized = false + var runtimeExited = false + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') + Module['preRun'] = [Module['preRun']] + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()) + } + } + callRuntimeCallbacks(__ATPRERUN__) + } + function initRuntime() { + runtimeInitialized = true + callRuntimeCallbacks(__ATINIT__) + } + function exitRuntime() { + runtimeExited = true + } + function postRun() { + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') + Module['postRun'] = [Module['postRun']] + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()) + } + } + callRuntimeCallbacks(__ATPOSTRUN__) + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb) + } + function addOnInit(cb) { + __ATINIT__.unshift(cb) + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb) + } + var runDependencies = 0 + var runDependencyWatcher = null + var dependenciesFulfilled = null + function addRunDependency(id) { + runDependencies++ + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + } + function removeRunDependency(id) { + runDependencies-- + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher) + runDependencyWatcher = null + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled + dependenciesFulfilled = null + callback() + } + } + } + Module['preloadedImages'] = {} + Module['preloadedAudios'] = {} + function abort(what) { + if (Module['onAbort']) { + Module['onAbort'](what) + } + what += '' + err(what) + ABORT = true + EXITSTATUS = 1 + what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' + var e = new WebAssembly.RuntimeError(what) + readyPromiseReject(e) + throw e + } + var dataURIPrefix = 'data:application/octet-stream;base64,' + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix) + } + if (Module['locateFile']) { + var wasmBinaryFile = 'mozjpeg_node_enc.wasm' + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile) + } + } else { + throw new Error('invariant') + } + function getBinary(file) { + try { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary) + } + if (readBinary) { + return readBinary(file) + } else { + throw 'both async and sync fetching of the wasm failed' + } + } catch (err) { + abort(err) + } + } + function getBinaryPromise() { + return Promise.resolve().then(function () { + return getBinary(wasmBinaryFile) + }) + } + function createWasm() { + var info = { a: asmLibraryArg } + function receiveInstance(instance, module) { + var exports = instance.exports + Module['asm'] = exports + wasmMemory = Module['asm']['C'] + updateGlobalBufferAndViews(wasmMemory.buffer) + wasmTable = Module['asm']['I'] + addOnInit(Module['asm']['D']) + removeRunDependency('wasm-instantiate') + } + addRunDependency('wasm-instantiate') + function receiveInstantiationResult(result) { + receiveInstance(result['instance']) + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise() + .then(function (binary) { + var result = WebAssembly.instantiate(binary, info) + return result + }) + .then(receiver, function (reason) { + err('failed to asynchronously prepare wasm: ' + reason) + abort(reason) + }) + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult) + } + if (Module['instantiateWasm']) { + try { + var exports = Module['instantiateWasm'](info, receiveInstance) + return exports + } catch (e) { + err('Module.instantiateWasm callback failed with error: ' + e) + return false + } + } + instantiateAsync().catch(readyPromiseReject) + return {} + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + var callback = callbacks.shift() + if (typeof callback == 'function') { + callback(Module) + continue + } + var func = callback.func + if (typeof func === 'number') { + if (callback.arg === undefined) { + wasmTable.get(func)() + } else { + wasmTable.get(func)(callback.arg) + } + } else { + func(callback.arg === undefined ? null : callback.arg) + } + } + } + var runtimeKeepaliveCounter = 0 + function keepRuntimeAlive() { + return noExitRuntime || runtimeKeepaliveCounter > 0 + } + function _atexit(func, arg) {} + function ___cxa_thread_atexit(a0, a1) { + return _atexit(a0, a1) + } + var structRegistrations = {} + function runDestructors(destructors) { + while (destructors.length) { + var ptr = destructors.pop() + var del = destructors.pop() + del(ptr) + } + } + function simpleReadValueFromPointer(pointer) { + return this['fromWireType'](HEAPU32[pointer >> 2]) + } + var awaitingDependencies = {} + var registeredTypes = {} + var typeDependencies = {} + var char_0 = 48 + var char_9 = 57 + function makeLegalFunctionName(name) { + if (undefined === name) { + return '_unknown' + } + name = name.replace(/[^a-zA-Z0-9_]/g, '$') + var f = name.charCodeAt(0) + if (f >= char_0 && f <= char_9) { + return '_' + name + } else { + return name + } + } + function createNamedFunction(name, body) { + name = makeLegalFunctionName(name) + return new Function( + 'body', + 'return function ' + + name + + '() {\n' + + ' "use strict";' + + ' return body.apply(this, arguments);\n' + + '};\n' + )(body) + } + function extendError(baseErrorType, errorName) { + var errorClass = createNamedFunction(errorName, function (message) { + this.name = errorName + this.message = message + var stack = new Error(message).stack + if (stack !== undefined) { + this.stack = + this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '') + } + }) + errorClass.prototype = Object.create(baseErrorType.prototype) + errorClass.prototype.constructor = errorClass + errorClass.prototype.toString = function () { + if (this.message === undefined) { + return this.name + } else { + return this.name + ': ' + this.message + } + } + return errorClass + } + var InternalError = undefined + function throwInternalError(message) { + throw new InternalError(message) + } + function whenDependentTypesAreResolved( + myTypes, + dependentTypes, + getTypeConverters + ) { + myTypes.forEach(function (type) { + typeDependencies[type] = dependentTypes + }) + function onComplete(typeConverters) { + var myTypeConverters = getTypeConverters(typeConverters) + if (myTypeConverters.length !== myTypes.length) { + throwInternalError('Mismatched type converter count') + } + for (var i = 0; i < myTypes.length; ++i) { + registerType(myTypes[i], myTypeConverters[i]) + } + } + var typeConverters = new Array(dependentTypes.length) + var unregisteredTypes = [] + var registered = 0 + dependentTypes.forEach(function (dt, i) { + if (registeredTypes.hasOwnProperty(dt)) { + typeConverters[i] = registeredTypes[dt] + } else { + unregisteredTypes.push(dt) + if (!awaitingDependencies.hasOwnProperty(dt)) { + awaitingDependencies[dt] = [] + } + awaitingDependencies[dt].push(function () { + typeConverters[i] = registeredTypes[dt] + ++registered + if (registered === unregisteredTypes.length) { + onComplete(typeConverters) + } + }) + } + }) + if (0 === unregisteredTypes.length) { + onComplete(typeConverters) + } + } + function __embind_finalize_value_object(structType) { + var reg = structRegistrations[structType] + delete structRegistrations[structType] + var rawConstructor = reg.rawConstructor + var rawDestructor = reg.rawDestructor + var fieldRecords = reg.fields + var fieldTypes = fieldRecords + .map(function (field) { + return field.getterReturnType + }) + .concat( + fieldRecords.map(function (field) { + return field.setterArgumentType + }) + ) + whenDependentTypesAreResolved( + [structType], + fieldTypes, + function (fieldTypes) { + var fields = {} + fieldRecords.forEach(function (field, i) { + var fieldName = field.fieldName + var getterReturnType = fieldTypes[i] + var getter = field.getter + var getterContext = field.getterContext + var setterArgumentType = fieldTypes[i + fieldRecords.length] + var setter = field.setter + var setterContext = field.setterContext + fields[fieldName] = { + read: function (ptr) { + return getterReturnType['fromWireType']( + getter(getterContext, ptr) + ) + }, + write: function (ptr, o) { + var destructors = [] + setter( + setterContext, + ptr, + setterArgumentType['toWireType'](destructors, o) + ) + runDestructors(destructors) + }, + } + }) + return [ + { + name: reg.name, + fromWireType: function (ptr) { + var rv = {} + for (var i in fields) { + rv[i] = fields[i].read(ptr) + } + rawDestructor(ptr) + return rv + }, + toWireType: function (destructors, o) { + for (var fieldName in fields) { + if (!(fieldName in o)) { + throw new TypeError('Missing field: "' + fieldName + '"') + } + } + var ptr = rawConstructor() + for (fieldName in fields) { + fields[fieldName].write(ptr, o[fieldName]) + } + if (destructors !== null) { + destructors.push(rawDestructor, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: rawDestructor, + }, + ] + } + ) + } + function __embind_register_bigint( + primitiveType, + name, + size, + minRange, + maxRange + ) {} + function getShiftFromSize(size) { + switch (size) { + case 1: + return 0 + case 2: + return 1 + case 4: + return 2 + case 8: + return 3 + default: + throw new TypeError('Unknown type size: ' + size) + } + } + function embind_init_charCodes() { + var codes = new Array(256) + for (var i = 0; i < 256; ++i) { + codes[i] = String.fromCharCode(i) + } + embind_charCodes = codes + } + var embind_charCodes = undefined + function readLatin1String(ptr) { + var ret = '' + var c = ptr + while (HEAPU8[c]) { + ret += embind_charCodes[HEAPU8[c++]] + } + return ret + } + var BindingError = undefined + function throwBindingError(message) { + throw new BindingError(message) + } + function registerType(rawType, registeredInstance, options) { + options = options || {} + if (!('argPackAdvance' in registeredInstance)) { + throw new TypeError( + 'registerType registeredInstance requires argPackAdvance' + ) + } + var name = registeredInstance.name + if (!rawType) { + throwBindingError( + 'type "' + name + '" must have a positive integer typeid pointer' + ) + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return + } else { + throwBindingError("Cannot register type '" + name + "' twice") + } + } + registeredTypes[rawType] = registeredInstance + delete typeDependencies[rawType] + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType] + delete awaitingDependencies[rawType] + callbacks.forEach(function (cb) { + cb() + }) + } + } + function __embind_register_bool( + rawType, + name, + size, + trueValue, + falseValue + ) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (wt) { + return !!wt + }, + toWireType: function (destructors, o) { + return o ? trueValue : falseValue + }, + argPackAdvance: 8, + readValueFromPointer: function (pointer) { + var heap + if (size === 1) { + heap = HEAP8 + } else if (size === 2) { + heap = HEAP16 + } else if (size === 4) { + heap = HEAP32 + } else { + throw new TypeError('Unknown boolean type size: ' + name) + } + return this['fromWireType'](heap[pointer >> shift]) + }, + destructorFunction: null, + }) + } + var emval_free_list = [] + var emval_handle_array = [ + {}, + { value: undefined }, + { value: null }, + { value: true }, + { value: false }, + ] + function __emval_decref(handle) { + if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { + emval_handle_array[handle] = undefined + emval_free_list.push(handle) + } + } + function count_emval_handles() { + var count = 0 + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + ++count + } + } + return count + } + function get_first_emval() { + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + return emval_handle_array[i] + } + } + return null + } + function init_emval() { + Module['count_emval_handles'] = count_emval_handles + Module['get_first_emval'] = get_first_emval + } + function __emval_register(value) { + switch (value) { + case undefined: { + return 1 + } + case null: { + return 2 + } + case true: { + return 3 + } + case false: { + return 4 + } + default: { + var handle = emval_free_list.length + ? emval_free_list.pop() + : emval_handle_array.length + emval_handle_array[handle] = { refcount: 1, value: value } + return handle + } + } + } + function __embind_register_emval(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (handle) { + var rv = emval_handle_array[handle].value + __emval_decref(handle) + return rv + }, + toWireType: function (destructors, value) { + return __emval_register(value) + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: null, + }) + } + function _embind_repr(v) { + if (v === null) { + return 'null' + } + var t = typeof v + if (t === 'object' || t === 'array' || t === 'function') { + return v.toString() + } else { + return '' + v + } + } + function floatReadValueFromPointer(name, shift) { + switch (shift) { + case 2: + return function (pointer) { + return this['fromWireType'](HEAPF32[pointer >> 2]) + } + case 3: + return function (pointer) { + return this['fromWireType'](HEAPF64[pointer >> 3]) + } + default: + throw new TypeError('Unknown float type: ' + name) + } + } + function __embind_register_float(rawType, name, size) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (value) { + return value + }, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + return value + }, + argPackAdvance: 8, + readValueFromPointer: floatReadValueFromPointer(name, shift), + destructorFunction: null, + }) + } + function new_(constructor, argumentList) { + if (!(constructor instanceof Function)) { + throw new TypeError( + 'new_ called with constructor type ' + + typeof constructor + + ' which is not a function' + ) + } + var dummy = createNamedFunction( + constructor.name || 'unknownFunctionName', + function () {} + ) + dummy.prototype = constructor.prototype + var obj = new dummy() + var r = constructor.apply(obj, argumentList) + return r instanceof Object ? r : obj + } + function craftInvokerFunction( + humanName, + argTypes, + classType, + cppInvokerFunc, + cppTargetFunc + ) { + var argCount = argTypes.length + if (argCount < 2) { + throwBindingError( + "argTypes array size mismatch! Must at least get return value and 'this' types!" + ) + } + var isClassMethodFunc = argTypes[1] !== null && classType !== null + var needsDestructorStack = false + for (var i = 1; i < argTypes.length; ++i) { + if ( + argTypes[i] !== null && + argTypes[i].destructorFunction === undefined + ) { + needsDestructorStack = true + break + } + } + var returns = argTypes[0].name !== 'void' + var argsList = '' + var argsListWired = '' + for (var i = 0; i < argCount - 2; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired' + } + var invokerFnBody = + 'return function ' + + makeLegalFunctionName(humanName) + + '(' + + argsList + + ') {\n' + + 'if (arguments.length !== ' + + (argCount - 2) + + ') {\n' + + "throwBindingError('function " + + humanName + + " called with ' + arguments.length + ' arguments, expected " + + (argCount - 2) + + " args!');\n" + + '}\n' + if (needsDestructorStack) { + invokerFnBody += 'var destructors = [];\n' + } + var dtorStack = needsDestructorStack ? 'destructors' : 'null' + var args1 = [ + 'throwBindingError', + 'invoker', + 'fn', + 'runDestructors', + 'retType', + 'classParam', + ] + var args2 = [ + throwBindingError, + cppInvokerFunc, + cppTargetFunc, + runDestructors, + argTypes[0], + argTypes[1], + ] + if (isClassMethodFunc) { + invokerFnBody += + 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n' + } + for (var i = 0; i < argCount - 2; ++i) { + invokerFnBody += + 'var arg' + + i + + 'Wired = argType' + + i + + '.toWireType(' + + dtorStack + + ', arg' + + i + + '); // ' + + argTypes[i + 2].name + + '\n' + args1.push('argType' + i) + args2.push(argTypes[i + 2]) + } + if (isClassMethodFunc) { + argsListWired = + 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired + } + invokerFnBody += + (returns ? 'var rv = ' : '') + + 'invoker(fn' + + (argsListWired.length > 0 ? ', ' : '') + + argsListWired + + ');\n' + if (needsDestructorStack) { + invokerFnBody += 'runDestructors(destructors);\n' + } else { + for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { + var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired' + if (argTypes[i].destructorFunction !== null) { + invokerFnBody += + paramName + + '_dtor(' + + paramName + + '); // ' + + argTypes[i].name + + '\n' + args1.push(paramName + '_dtor') + args2.push(argTypes[i].destructorFunction) + } + } + } + if (returns) { + invokerFnBody += + 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n' + } else { + } + invokerFnBody += '}\n' + args1.push(invokerFnBody) + var invokerFunction = new_(Function, args1).apply(null, args2) + return invokerFunction + } + function ensureOverloadTable(proto, methodName, humanName) { + if (undefined === proto[methodName].overloadTable) { + var prevFunc = proto[methodName] + proto[methodName] = function () { + if ( + !proto[methodName].overloadTable.hasOwnProperty(arguments.length) + ) { + throwBindingError( + "Function '" + + humanName + + "' called with an invalid number of arguments (" + + arguments.length + + ') - expects one of (' + + proto[methodName].overloadTable + + ')!' + ) + } + return proto[methodName].overloadTable[arguments.length].apply( + this, + arguments + ) + } + proto[methodName].overloadTable = [] + proto[methodName].overloadTable[prevFunc.argCount] = prevFunc + } + } + function exposePublicSymbol(name, value, numArguments) { + if (Module.hasOwnProperty(name)) { + if ( + undefined === numArguments || + (undefined !== Module[name].overloadTable && + undefined !== Module[name].overloadTable[numArguments]) + ) { + throwBindingError("Cannot register public name '" + name + "' twice") + } + ensureOverloadTable(Module, name, name) + if (Module.hasOwnProperty(numArguments)) { + throwBindingError( + 'Cannot register multiple overloads of a function with the same number of arguments (' + + numArguments + + ')!' + ) + } + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + if (undefined !== numArguments) { + Module[name].numArguments = numArguments + } + } + } + function heap32VectorToArray(count, firstElement) { + var array = [] + for (var i = 0; i < count; i++) { + array.push(HEAP32[(firstElement >> 2) + i]) + } + return array + } + function replacePublicSymbol(name, value, numArguments) { + if (!Module.hasOwnProperty(name)) { + throwInternalError('Replacing nonexistent public symbol') + } + if ( + undefined !== Module[name].overloadTable && + undefined !== numArguments + ) { + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + Module[name].argCount = numArguments + } + } + function dynCallLegacy(sig, ptr, args) { + var f = Module['dynCall_' + sig] + return args && args.length + ? f.apply(null, [ptr].concat(args)) + : f.call(null, ptr) + } + function dynCall(sig, ptr, args) { + if (sig.includes('j')) { + return dynCallLegacy(sig, ptr, args) + } + return wasmTable.get(ptr).apply(null, args) + } + function getDynCaller(sig, ptr) { + var argCache = [] + return function () { + argCache.length = arguments.length + for (var i = 0; i < arguments.length; i++) { + argCache[i] = arguments[i] + } + return dynCall(sig, ptr, argCache) + } + } + function embind__requireFunction(signature, rawFunction) { + signature = readLatin1String(signature) + function makeDynCaller() { + if (signature.includes('j')) { + return getDynCaller(signature, rawFunction) + } + return wasmTable.get(rawFunction) + } + var fp = makeDynCaller() + if (typeof fp !== 'function') { + throwBindingError( + 'unknown function pointer with signature ' + + signature + + ': ' + + rawFunction + ) + } + return fp + } + var UnboundTypeError = undefined + function getTypeName(type) { + var ptr = ___getTypeName(type) + var rv = readLatin1String(ptr) + _free(ptr) + return rv + } + function throwUnboundTypeError(message, types) { + var unboundTypes = [] + var seen = {} + function visit(type) { + if (seen[type]) { + return + } + if (registeredTypes[type]) { + return + } + if (typeDependencies[type]) { + typeDependencies[type].forEach(visit) + return + } + unboundTypes.push(type) + seen[type] = true + } + types.forEach(visit) + throw new UnboundTypeError( + message + ': ' + unboundTypes.map(getTypeName).join([', ']) + ) + } + function __embind_register_function( + name, + argCount, + rawArgTypesAddr, + signature, + rawInvoker, + fn + ) { + var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr) + name = readLatin1String(name) + rawInvoker = embind__requireFunction(signature, rawInvoker) + exposePublicSymbol( + name, + function () { + throwUnboundTypeError( + 'Cannot call ' + name + ' due to unbound types', + argTypes + ) + }, + argCount - 1 + ) + whenDependentTypesAreResolved([], argTypes, function (argTypes) { + var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1)) + replacePublicSymbol( + name, + craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn), + argCount - 1 + ) + return [] + }) + } + function integerReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return signed + ? function readS8FromPointer(pointer) { + return HEAP8[pointer] + } + : function readU8FromPointer(pointer) { + return HEAPU8[pointer] + } + case 1: + return signed + ? function readS16FromPointer(pointer) { + return HEAP16[pointer >> 1] + } + : function readU16FromPointer(pointer) { + return HEAPU16[pointer >> 1] + } + case 2: + return signed + ? function readS32FromPointer(pointer) { + return HEAP32[pointer >> 2] + } + : function readU32FromPointer(pointer) { + return HEAPU32[pointer >> 2] + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_integer( + primitiveType, + name, + size, + minRange, + maxRange + ) { + name = readLatin1String(name) + if (maxRange === -1) { + maxRange = 4294967295 + } + var shift = getShiftFromSize(size) + var fromWireType = function (value) { + return value + } + if (minRange === 0) { + var bitshift = 32 - 8 * size + fromWireType = function (value) { + return (value << bitshift) >>> bitshift + } + } + var isUnsignedType = name.includes('unsigned') + registerType(primitiveType, { + name: name, + fromWireType: fromWireType, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + if (value < minRange || value > maxRange) { + throw new TypeError( + 'Passing a number "' + + _embind_repr(value) + + '" from JS side to C/C++ side to an argument of type "' + + name + + '", which is outside the valid range [' + + minRange + + ', ' + + maxRange + + ']!' + ) + } + return isUnsignedType ? value >>> 0 : value | 0 + }, + argPackAdvance: 8, + readValueFromPointer: integerReadValueFromPointer( + name, + shift, + minRange !== 0 + ), + destructorFunction: null, + }) + } + function __embind_register_memory_view(rawType, dataTypeIndex, name) { + var typeMapping = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + ] + var TA = typeMapping[dataTypeIndex] + function decodeMemoryView(handle) { + handle = handle >> 2 + var heap = HEAPU32 + var size = heap[handle] + var data = heap[handle + 1] + return new TA(buffer, data, size) + } + name = readLatin1String(name) + registerType( + rawType, + { + name: name, + fromWireType: decodeMemoryView, + argPackAdvance: 8, + readValueFromPointer: decodeMemoryView, + }, + { ignoreDuplicateRegistrations: true } + ) + } + function __embind_register_std_string(rawType, name) { + name = readLatin1String(name) + var stdStringIsUTF8 = name === 'std::string' + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var str + if (stdStringIsUTF8) { + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i + if (i == length || HEAPU8[currentBytePtr] == 0) { + var maxRead = currentBytePtr - decodeStartPtr + var stringSegment = UTF8ToString(decodeStartPtr, maxRead) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + 1 + } + } + } else { + var a = new Array(length) + for (var i = 0; i < length; ++i) { + a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) + } + str = a.join('') + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value) + } + var getLength + var valueIsOfTypeString = typeof value === 'string' + if ( + !( + valueIsOfTypeString || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int8Array + ) + ) { + throwBindingError('Cannot pass non-string to std::string') + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + getLength = function () { + return lengthBytesUTF8(value) + } + } else { + getLength = function () { + return value.length + } + } + var length = getLength() + var ptr = _malloc(4 + length + 1) + HEAPU32[ptr >> 2] = length + if (stdStringIsUTF8 && valueIsOfTypeString) { + stringToUTF8(value, ptr + 4, length + 1) + } else { + if (valueIsOfTypeString) { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i) + if (charCode > 255) { + _free(ptr) + throwBindingError( + 'String has UTF-16 code units that do not fit in 8 bits' + ) + } + HEAPU8[ptr + 4 + i] = charCode + } + } else { + for (var i = 0; i < length; ++i) { + HEAPU8[ptr + 4 + i] = value[i] + } + } + } + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_std_wstring(rawType, charSize, name) { + name = readLatin1String(name) + var decodeString, encodeString, getHeap, lengthBytesUTF, shift + if (charSize === 2) { + decodeString = UTF16ToString + encodeString = stringToUTF16 + lengthBytesUTF = lengthBytesUTF16 + getHeap = function () { + return HEAPU16 + } + shift = 1 + } else if (charSize === 4) { + decodeString = UTF32ToString + encodeString = stringToUTF32 + lengthBytesUTF = lengthBytesUTF32 + getHeap = function () { + return HEAPU32 + } + shift = 2 + } + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var HEAP = getHeap() + var str + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i * charSize + if (i == length || HEAP[currentBytePtr >> shift] == 0) { + var maxReadBytes = currentBytePtr - decodeStartPtr + var stringSegment = decodeString(decodeStartPtr, maxReadBytes) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + charSize + } + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (!(typeof value === 'string')) { + throwBindingError( + 'Cannot pass non-string to C++ string type ' + name + ) + } + var length = lengthBytesUTF(value) + var ptr = _malloc(4 + length + charSize) + HEAPU32[ptr >> 2] = length >> shift + encodeString(value, ptr + 4, length + charSize) + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_value_object( + rawType, + name, + constructorSignature, + rawConstructor, + destructorSignature, + rawDestructor + ) { + structRegistrations[rawType] = { + name: readLatin1String(name), + rawConstructor: embind__requireFunction( + constructorSignature, + rawConstructor + ), + rawDestructor: embind__requireFunction( + destructorSignature, + rawDestructor + ), + fields: [], + } + } + function __embind_register_value_object_field( + structType, + fieldName, + getterReturnType, + getterSignature, + getter, + getterContext, + setterArgumentType, + setterSignature, + setter, + setterContext + ) { + structRegistrations[structType].fields.push({ + fieldName: readLatin1String(fieldName), + getterReturnType: getterReturnType, + getter: embind__requireFunction(getterSignature, getter), + getterContext: getterContext, + setterArgumentType: setterArgumentType, + setter: embind__requireFunction(setterSignature, setter), + setterContext: setterContext, + }) + } + function __embind_register_void(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + isVoid: true, + name: name, + argPackAdvance: 0, + fromWireType: function () { + return undefined + }, + toWireType: function (destructors, o) { + return undefined + }, + }) + } + var emval_symbols = {} + function getStringOrSymbol(address) { + var symbol = emval_symbols[address] + if (symbol === undefined) { + return readLatin1String(address) + } else { + return symbol + } + } + function emval_get_global() { + if (typeof globalThis === 'object') { + return globalThis + } + return (function () { + return Function + })()('return this')() + } + function __emval_get_global(name) { + if (name === 0) { + return __emval_register(emval_get_global()) + } else { + name = getStringOrSymbol(name) + return __emval_register(emval_get_global()[name]) + } + } + function __emval_incref(handle) { + if (handle > 4) { + emval_handle_array[handle].refcount += 1 + } + } + function requireRegisteredType(rawType, humanName) { + var impl = registeredTypes[rawType] + if (undefined === impl) { + throwBindingError( + humanName + ' has unknown type ' + getTypeName(rawType) + ) + } + return impl + } + function craftEmvalAllocator(argCount) { + var argsList = '' + for (var i = 0; i < argCount; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + } + var functionBody = + 'return function emval_allocator_' + + argCount + + '(constructor, argTypes, args) {\n' + for (var i = 0; i < argCount; ++i) { + functionBody += + 'var argType' + + i + + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + + i + + '], "parameter ' + + i + + '");\n' + + 'var arg' + + i + + ' = argType' + + i + + '.readValueFromPointer(args);\n' + + 'args += argType' + + i + + "['argPackAdvance'];\n" + } + functionBody += + 'var obj = new constructor(' + + argsList + + ');\n' + + 'return __emval_register(obj);\n' + + '}\n' + return new Function( + 'requireRegisteredType', + 'Module', + '__emval_register', + functionBody + )(requireRegisteredType, Module, __emval_register) + } + var emval_newers = {} + function requireHandle(handle) { + if (!handle) { + throwBindingError('Cannot use deleted val. handle = ' + handle) + } + return emval_handle_array[handle].value + } + function __emval_new(handle, argCount, argTypes, args) { + handle = requireHandle(handle) + var newer = emval_newers[argCount] + if (!newer) { + newer = craftEmvalAllocator(argCount) + emval_newers[argCount] = newer + } + return newer(handle, argTypes, args) + } + function _abort() { + abort() + } + function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.copyWithin(dest, src, src + num) + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16) + updateGlobalBufferAndViews(wasmMemory.buffer) + return 1 + } catch (e) {} + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length + requestedSize = requestedSize >>> 0 + var maxHeapSize = 2147483648 + if (requestedSize > maxHeapSize) { + return false + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown) + overGrownHeapSize = Math.min( + overGrownHeapSize, + requestedSize + 100663296 + ) + var newSize = Math.min( + maxHeapSize, + alignUp(Math.max(requestedSize, overGrownHeapSize), 65536) + ) + var replacement = emscripten_realloc_buffer(newSize) + if (replacement) { + return true + } + } + return false + } + var ENV = {} + function getExecutableName() { + return thisProgram || './this.program' + } + function getEnvStrings() { + if (!getEnvStrings.strings) { + var lang = + ( + (typeof navigator === 'object' && + navigator.languages && + navigator.languages[0]) || + 'C' + ).replace('-', '_') + '.UTF-8' + var env = { + USER: 'web_user', + LOGNAME: 'web_user', + PATH: '/', + PWD: '/', + HOME: '/home/web_user', + LANG: lang, + _: getExecutableName(), + } + for (var x in ENV) { + env[x] = ENV[x] + } + var strings = [] + for (var x in env) { + strings.push(x + '=' + env[x]) + } + getEnvStrings.strings = strings + } + return getEnvStrings.strings + } + var SYSCALLS = { + mappings: {}, + buffers: [null, [], []], + printChar: function (stream, curr) { + var buffer = SYSCALLS.buffers[stream] + if (curr === 0 || curr === 10) { + ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)) + buffer.length = 0 + } else { + buffer.push(curr) + } + }, + varargs: undefined, + get: function () { + SYSCALLS.varargs += 4 + var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2] + return ret + }, + getStr: function (ptr) { + var ret = UTF8ToString(ptr) + return ret + }, + get64: function (low, high) { + return low + }, + } + function _environ_get(__environ, environ_buf) { + var bufSize = 0 + getEnvStrings().forEach(function (string, i) { + var ptr = environ_buf + bufSize + HEAP32[(__environ + i * 4) >> 2] = ptr + writeAsciiToMemory(string, ptr) + bufSize += string.length + 1 + }) + return 0 + } + function _environ_sizes_get(penviron_count, penviron_buf_size) { + var strings = getEnvStrings() + HEAP32[penviron_count >> 2] = strings.length + var bufSize = 0 + strings.forEach(function (string) { + bufSize += string.length + 1 + }) + HEAP32[penviron_buf_size >> 2] = bufSize + return 0 + } + function _exit(status) { + exit(status) + } + function _fd_close(fd) { + return 0 + } + function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {} + function _fd_write(fd, iov, iovcnt, pnum) { + var num = 0 + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAP32[(iov + i * 8) >> 2] + var len = HEAP32[(iov + (i * 8 + 4)) >> 2] + for (var j = 0; j < len; j++) { + SYSCALLS.printChar(fd, HEAPU8[ptr + j]) + } + num += len + } + HEAP32[pnum >> 2] = num + return 0 + } + function _setTempRet0(val) { + setTempRet0(val) + } + InternalError = Module['InternalError'] = extendError( + Error, + 'InternalError' + ) + embind_init_charCodes() + BindingError = Module['BindingError'] = extendError(Error, 'BindingError') + init_emval() + UnboundTypeError = Module['UnboundTypeError'] = extendError( + Error, + 'UnboundTypeError' + ) + var asmLibraryArg = { + B: ___cxa_thread_atexit, + l: __embind_finalize_value_object, + p: __embind_register_bigint, + y: __embind_register_bool, + x: __embind_register_emval, + i: __embind_register_float, + f: __embind_register_function, + c: __embind_register_integer, + b: __embind_register_memory_view, + j: __embind_register_std_string, + e: __embind_register_std_wstring, + m: __embind_register_value_object, + a: __embind_register_value_object_field, + z: __embind_register_void, + g: __emval_decref, + u: __emval_get_global, + k: __emval_incref, + n: __emval_new, + h: _abort, + r: _emscripten_memcpy_big, + d: _emscripten_resize_heap, + s: _environ_get, + t: _environ_sizes_get, + A: _exit, + w: _fd_close, + o: _fd_seek, + v: _fd_write, + q: _setTempRet0, + } + var asm = createWasm() + var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () { + return (___wasm_call_ctors = Module['___wasm_call_ctors'] = + Module['asm']['D']).apply(null, arguments) + }) + var _malloc = (Module['_malloc'] = function () { + return (_malloc = Module['_malloc'] = Module['asm']['E']).apply( + null, + arguments + ) + }) + var _free = (Module['_free'] = function () { + return (_free = Module['_free'] = Module['asm']['F']).apply( + null, + arguments + ) + }) + var ___getTypeName = (Module['___getTypeName'] = function () { + return (___getTypeName = Module['___getTypeName'] = + Module['asm']['G']).apply(null, arguments) + }) + var ___embind_register_native_and_builtin_types = (Module[ + '___embind_register_native_and_builtin_types' + ] = function () { + return (___embind_register_native_and_builtin_types = Module[ + '___embind_register_native_and_builtin_types' + ] = + Module['asm']['H']).apply(null, arguments) + }) + var dynCall_jiji = (Module['dynCall_jiji'] = function () { + return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['J']).apply( + null, + arguments + ) + }) + var calledRun + function ExitStatus(status) { + this.name = 'ExitStatus' + this.message = 'Program terminated with exit(' + status + ')' + this.status = status + } + dependenciesFulfilled = function runCaller() { + if (!calledRun) run() + if (!calledRun) dependenciesFulfilled = runCaller + } + function run(args) { + args = args || arguments_ + if (runDependencies > 0) { + return + } + preRun() + if (runDependencies > 0) { + return + } + function doRun() { + if (calledRun) return + calledRun = true + Module['calledRun'] = true + if (ABORT) return + initRuntime() + readyPromiseResolve(Module) + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() + postRun() + } + if (Module['setStatus']) { + Module['setStatus']('Running...') + setTimeout(function () { + setTimeout(function () { + Module['setStatus']('') + }, 1) + doRun() + }, 1) + } else { + doRun() + } + } + Module['run'] = run + function exit(status, implicit) { + EXITSTATUS = status + if (implicit && keepRuntimeAlive() && status === 0) { + return + } + if (keepRuntimeAlive()) { + } else { + exitRuntime() + if (Module['onExit']) Module['onExit'](status) + ABORT = true + } + quit_(status, new ExitStatus(status)) + } + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') + Module['preInit'] = [Module['preInit']] + while (Module['preInit'].length > 0) { + Module['preInit'].pop()() + } + } + run() + + return Module.ready + } +})() +export default Module diff --git a/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.wasm b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.wasm new file mode 100644 index 000000000000..4dc36264bcfd Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_oxipng.ts b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_oxipng.ts new file mode 100644 index 000000000000..90a12b3898fb --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_oxipng.ts @@ -0,0 +1,120 @@ +// @ts-nocheck +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) + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc) + const len0 = WASM_VECTOR_LEN + wasm.optimise(retptr, ptr0, len0, level, interlace) + const r0 = getInt32Memory0()[retptr / 4 + 0] + const r1 = getInt32Memory0()[retptr / 4 + 1] + const 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 +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_oxipng_bg.wasm b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_oxipng_bg.wasm new file mode 100644 index 000000000000..92ec1d8960bd Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_oxipng_bg.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_png.ts b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_png.ts new file mode 100644 index 000000000000..09cbed9ff3a5 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_png.ts @@ -0,0 +1,184 @@ +// @ts-nocheck +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) + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc) + const len0 = WASM_VECTOR_LEN + wasm.encode(retptr, ptr0, len0, width, height) + const r0 = getInt32Memory0()[retptr / 4 + 0] + const r1 = getInt32Memory0()[retptr / 4 + 1] + const 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) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc) + const len0 = WASM_VECTOR_LEN + const 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) { + const v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice() + wasm.__wbindgen_free(arg0, arg1 * 1) + const 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 +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_png_bg.wasm b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_png_bg.wasm new file mode 100644 index 000000000000..cc5cf3660e09 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/png/squoosh_png_bg.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/resize/squoosh_resize.ts b/packages/astro/src/assets/services/vendor/squoosh/resize/squoosh_resize.ts new file mode 100644 index 000000000000..1204db18fcce --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/resize/squoosh_resize.ts @@ -0,0 +1,141 @@ +// @ts-nocheck +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) + const ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc) + const len0 = WASM_VECTOR_LEN + wasm.resize( + retptr, + ptr0, + len0, + input_width, + input_height, + output_width, + output_height, + typ_idx, + premultiply, + color_space_conversion + ) + const r0 = getInt32Memory0()[retptr / 4 + 0] + const r1 = getInt32Memory0()[retptr / 4 + 1] + const 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 +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/resize/squoosh_resize_bg.wasm b/packages/astro/src/assets/services/vendor/squoosh/resize/squoosh_resize_bg.wasm new file mode 100644 index 000000000000..b910c97b050d Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/resize/squoosh_resize_bg.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/rotate/rotate.wasm b/packages/astro/src/assets/services/vendor/squoosh/rotate/rotate.wasm new file mode 100644 index 000000000000..8c7122c9f8b7 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/rotate/rotate.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/utils/execOnce.ts b/packages/astro/src/assets/services/vendor/squoosh/utils/execOnce.ts new file mode 100644 index 000000000000..97201e54f10c --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/utils/execOnce.ts @@ -0,0 +1,12 @@ +export default function execOnce ReturnType>(fn: T): T { + let used = false; + let result: ReturnType; + + return ((...args: any[]) => { + if (!used) { + used = true; + result = fn(...args); + } + return result; + }) as T; +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/utils/workerPool.ts b/packages/astro/src/assets/services/vendor/squoosh/utils/workerPool.ts new file mode 100644 index 000000000000..6f953998e260 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/utils/workerPool.ts @@ -0,0 +1,122 @@ +/* tslint-disable ban-types */ +import { parentPort, Worker } from 'worker_threads'; + +function uuid() { + return Array.from({ length: 16 }, () => Math.floor(Math.random() * 256).toString(16)).join(''); +} + +interface Job { + msg: I; + resolve: (result: any) => void; + reject: (reason: any) => void; +} + +export default class WorkerPool { + public numWorkers: number; + public jobQueue: TransformStream, Job>; + public workerQueue: TransformStream; + public done: Promise; + + constructor(numWorkers: number, workerFile: string) { + this.numWorkers = numWorkers; + this.jobQueue = new TransformStream(); + this.workerQueue = new TransformStream(); + + const writer = this.workerQueue.writable.getWriter(); + for (let i = 0; i < numWorkers; i++) { + writer.write(new Worker(workerFile)); + } + writer.releaseLock(); + + this.done = this._readLoop(); + } + + async _readLoop() { + const reader = this.jobQueue.readable.getReader(); + while (true) { + const { value, done } = await reader.read(); + if (done) { + await this._terminateAll(); + return; + } + + if (!value) { + throw new Error('Reader did not return any value'); + } + + const { msg, resolve, reject } = value; + const worker = await this._nextWorker(); + this.jobPromise(worker, msg) + .then((result) => resolve(result)) + .catch((reason) => reject(reason)) + .finally(() => { + // Return the worker to the pool + const writer = this.workerQueue.writable.getWriter(); + writer.write(worker); + writer.releaseLock(); + }); + } + } + + async _nextWorker() { + const reader = this.workerQueue.readable.getReader(); + const { value } = await reader.read(); + reader.releaseLock(); + if (!value) { + throw new Error('No worker left'); + } + + return value; + } + + async _terminateAll() { + for (let n = 0; n < this.numWorkers; n++) { + const worker = await this._nextWorker(); + worker.terminate(); + } + this.workerQueue.writable.close(); + } + + async join() { + this.jobQueue.writable.getWriter().close(); + await this.done; + } + + dispatchJob(msg: I): Promise { + return new Promise((resolve, reject) => { + const writer = this.jobQueue.writable.getWriter(); + writer.write({ msg, resolve, reject }); + writer.releaseLock(); + }); + } + + private jobPromise(worker: Worker, msg: I) { + return new Promise((resolve, reject) => { + const id = uuid(); + worker.postMessage({ msg, id }); + worker.on('message', function f({ error, result, id: rid }) { + if (rid !== id) { + return; + } + if (error) { + reject(error); + return; + } + worker.off('message', f); + resolve(result); + }); + }); + } + + static useThisThreadAsWorker(cb: (msg: I) => O) { + parentPort!.on('message', async (data) => { + const { msg, id } = data; + try { + const result = await cb(msg); + parentPort!.postMessage({ result, id }); + } catch (e: any) { + parentPort!.postMessage({ error: e.message, id }); + } + }); + } +} diff --git a/packages/astro/src/assets/services/vendor/squoosh/webp/webp_enc.d.ts b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_enc.d.ts new file mode 100644 index 000000000000..3c45068299a1 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_enc.d.ts @@ -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 + +export default moduleFactory diff --git a/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_dec.ts b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_dec.ts new file mode 100644 index 000000000000..cdb1a9837380 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_dec.ts @@ -0,0 +1,1614 @@ +/* eslint-disable */ +// @ts-nocheck +import { createRequire } from 'module'; +import { dirname, getModuleURL } from '../emscripten-utils.js'; +const require = createRequire(getModuleURL(import.meta.url)); + +var Module = (function () { + return function (Module) { + Module = Module || {} + + var Module = typeof Module !== 'undefined' ? Module : {} + var readyPromiseResolve, readyPromiseReject + Module['ready'] = new Promise(function (resolve, reject) { + readyPromiseResolve = resolve + readyPromiseReject = reject + }) + var moduleOverrides = {} + var key + for (key in Module) { + if (Module.hasOwnProperty(key)) { + moduleOverrides[key] = Module[key] + } + } + var arguments_ = [] + var thisProgram = './this.program' + var quit_ = function (status, toThrow) { + throw toThrow + } + var ENVIRONMENT_IS_WEB = false + var ENVIRONMENT_IS_WORKER = false + var ENVIRONMENT_IS_NODE = true + var scriptDirectory = '' + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory) + } + return scriptDirectory + path + } + var read_, readBinary + var nodeFS + var nodePath + if (ENVIRONMENT_IS_NODE) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = require('path').dirname(scriptDirectory) + '/' + } else { + scriptDirectory = dirname(getModuleURL(import.meta.url)) + '/' + } + read_ = function shell_read(filename, binary) { + if (!nodeFS) nodeFS = require('fs') + if (!nodePath) nodePath = require('path') + filename = nodePath['normalize'](filename) + return nodeFS['readFileSync'](filename, binary ? null : 'utf8') + } + readBinary = function readBinary(filename) { + var ret = read_(filename, true) + if (!ret.buffer) { + ret = new Uint8Array(ret) + } + assert(ret.buffer) + return ret + } + if (process['argv'].length > 1) { + thisProgram = process['argv'][1].replace(/\\/g, '/') + } + arguments_ = process['argv'].slice(2) + quit_ = function (status) { + process['exit'](status) + } + Module['inspect'] = function () { + return '[Emscripten Module object]' + } + } else { + } + var out = Module['print'] || console.log.bind(console) + var err = Module['printErr'] || console.warn.bind(console) + for (key in moduleOverrides) { + if (moduleOverrides.hasOwnProperty(key)) { + Module[key] = moduleOverrides[key] + } + } + moduleOverrides = null + if (Module['arguments']) arguments_ = Module['arguments'] + if (Module['thisProgram']) thisProgram = Module['thisProgram'] + if (Module['quit']) quit_ = Module['quit'] + var wasmBinary + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'] + var noExitRuntime = Module['noExitRuntime'] || true + if (typeof WebAssembly !== 'object') { + abort('no native wasm support detected') + } + var wasmMemory + var ABORT = false + var EXITSTATUS + function assert(condition, text) { + if (!condition) { + abort('Assertion failed: ' + text) + } + } + var UTF8Decoder = new TextDecoder('utf8') + function UTF8ToString(ptr, maxBytesToRead) { + if (!ptr) return '' + var maxPtr = ptr + maxBytesToRead + for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)) + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) return 0 + var startIdx = outIdx + var endIdx = outIdx + maxBytesToWrite - 1 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i) + u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) + } + if (u <= 127) { + if (outIdx >= endIdx) break + heap[outIdx++] = u + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break + heap[outIdx++] = 192 | (u >> 6) + heap[outIdx++] = 128 | (u & 63) + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break + heap[outIdx++] = 224 | (u >> 12) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } else { + if (outIdx + 3 >= endIdx) break + heap[outIdx++] = 240 | (u >> 18) + heap[outIdx++] = 128 | ((u >> 12) & 63) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } + } + heap[outIdx] = 0 + return outIdx - startIdx + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) + } + function lengthBytesUTF8(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) + u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) + if (u <= 127) ++len + else if (u <= 2047) len += 2 + else if (u <= 65535) len += 3 + else len += 4 + } + return len + } + var UTF16Decoder = new TextDecoder('utf-16le') + function UTF16ToString(ptr, maxBytesToRead) { + var endPtr = ptr + var idx = endPtr >> 1 + var maxIdx = idx + maxBytesToRead / 2 + while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx + endPtr = idx << 1 + return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)) + var str = '' + for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { + var codeUnit = HEAP16[(ptr + i * 2) >> 1] + if (codeUnit == 0) break + str += String.fromCharCode(codeUnit) + } + return str + } + function stringToUTF16(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 2) return 0 + maxBytesToWrite -= 2 + var startPtr = outPtr + var numCharsToWrite = + maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i) + HEAP16[outPtr >> 1] = codeUnit + outPtr += 2 + } + HEAP16[outPtr >> 1] = 0 + return outPtr - startPtr + } + function lengthBytesUTF16(str) { + return str.length * 2 + } + function UTF32ToString(ptr, maxBytesToRead) { + var i = 0 + var str = '' + while (!(i >= maxBytesToRead / 4)) { + var utf32 = HEAP32[(ptr + i * 4) >> 2] + if (utf32 == 0) break + ++i + if (utf32 >= 65536) { + var ch = utf32 - 65536 + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) + } else { + str += String.fromCharCode(utf32) + } + } + return str + } + function stringToUTF32(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 4) return 0 + var startPtr = outPtr + var endPtr = startPtr + maxBytesToWrite - 4 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) { + var trailSurrogate = str.charCodeAt(++i) + codeUnit = + (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023) + } + HEAP32[outPtr >> 2] = codeUnit + outPtr += 4 + if (outPtr + 4 > endPtr) break + } + HEAP32[outPtr >> 2] = 0 + return outPtr - startPtr + } + function lengthBytesUTF32(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) ++i + len += 4 + } + return len + } + function alignUp(x, multiple) { + if (x % multiple > 0) { + x += multiple - (x % multiple) + } + return x + } + var buffer, + HEAP8, + HEAPU8, + HEAP16, + HEAPU16, + HEAP32, + HEAPU32, + HEAPF32, + HEAPF64 + function updateGlobalBufferAndViews(buf) { + buffer = buf + Module['HEAP8'] = HEAP8 = new Int8Array(buf) + Module['HEAP16'] = HEAP16 = new Int16Array(buf) + Module['HEAP32'] = HEAP32 = new Int32Array(buf) + Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf) + Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf) + Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf) + Module['HEAPF32'] = HEAPF32 = new Float32Array(buf) + Module['HEAPF64'] = HEAPF64 = new Float64Array(buf) + } + var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 + var wasmTable + var __ATPRERUN__ = [] + var __ATINIT__ = [] + var __ATPOSTRUN__ = [] + var runtimeInitialized = false + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') + Module['preRun'] = [Module['preRun']] + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()) + } + } + callRuntimeCallbacks(__ATPRERUN__) + } + function initRuntime() { + runtimeInitialized = true + callRuntimeCallbacks(__ATINIT__) + } + function postRun() { + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') + Module['postRun'] = [Module['postRun']] + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()) + } + } + callRuntimeCallbacks(__ATPOSTRUN__) + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb) + } + function addOnInit(cb) { + __ATINIT__.unshift(cb) + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb) + } + var runDependencies = 0 + var runDependencyWatcher = null + var dependenciesFulfilled = null + function addRunDependency(id) { + runDependencies++ + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + } + function removeRunDependency(id) { + runDependencies-- + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher) + runDependencyWatcher = null + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled + dependenciesFulfilled = null + callback() + } + } + } + Module['preloadedImages'] = {} + Module['preloadedAudios'] = {} + function abort(what) { + if (Module['onAbort']) { + Module['onAbort'](what) + } + what += '' + err(what) + ABORT = true + EXITSTATUS = 1 + what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' + var e = new WebAssembly.RuntimeError(what) + readyPromiseReject(e) + throw e + } + var dataURIPrefix = 'data:application/octet-stream;base64,' + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix) + } + if (Module['locateFile']) { + var wasmBinaryFile = 'webp_node_dec.wasm' + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile) + } + } else { + throw new Error('invariant') + } + function getBinary(file) { + try { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary) + } + if (readBinary) { + return readBinary(file) + } else { + throw 'both async and sync fetching of the wasm failed' + } + } catch (err) { + abort(err) + } + } + function getBinaryPromise() { + return Promise.resolve().then(function () { + return getBinary(wasmBinaryFile) + }) + } + function createWasm() { + var info = { a: asmLibraryArg } + function receiveInstance(instance, module) { + var exports = instance.exports + Module['asm'] = exports + wasmMemory = Module['asm']['s'] + updateGlobalBufferAndViews(wasmMemory.buffer) + wasmTable = Module['asm']['y'] + addOnInit(Module['asm']['t']) + removeRunDependency('wasm-instantiate') + } + addRunDependency('wasm-instantiate') + function receiveInstantiationResult(result) { + receiveInstance(result['instance']) + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise() + .then(function (binary) { + var result = WebAssembly.instantiate(binary, info) + return result + }) + .then(receiver, function (reason) { + err('failed to asynchronously prepare wasm: ' + reason) + abort(reason) + }) + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult) + } + if (Module['instantiateWasm']) { + try { + var exports = Module['instantiateWasm'](info, receiveInstance) + return exports + } catch (e) { + err('Module.instantiateWasm callback failed with error: ' + e) + return false + } + } + instantiateAsync().catch(readyPromiseReject) + return {} + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + var callback = callbacks.shift() + if (typeof callback == 'function') { + callback(Module) + continue + } + var func = callback.func + if (typeof func === 'number') { + if (callback.arg === undefined) { + wasmTable.get(func)() + } else { + wasmTable.get(func)(callback.arg) + } + } else { + func(callback.arg === undefined ? null : callback.arg) + } + } + } + function _atexit(func, arg) {} + function ___cxa_thread_atexit(a0, a1) { + return _atexit(a0, a1) + } + function __embind_register_bigint( + primitiveType, + name, + size, + minRange, + maxRange + ) {} + function getShiftFromSize(size) { + switch (size) { + case 1: + return 0 + case 2: + return 1 + case 4: + return 2 + case 8: + return 3 + default: + throw new TypeError('Unknown type size: ' + size) + } + } + function embind_init_charCodes() { + var codes = new Array(256) + for (var i = 0; i < 256; ++i) { + codes[i] = String.fromCharCode(i) + } + embind_charCodes = codes + } + var embind_charCodes = undefined + function readLatin1String(ptr) { + var ret = '' + var c = ptr + while (HEAPU8[c]) { + ret += embind_charCodes[HEAPU8[c++]] + } + return ret + } + var awaitingDependencies = {} + var registeredTypes = {} + var typeDependencies = {} + var char_0 = 48 + var char_9 = 57 + function makeLegalFunctionName(name) { + if (undefined === name) { + return '_unknown' + } + name = name.replace(/[^a-zA-Z0-9_]/g, '$') + var f = name.charCodeAt(0) + if (f >= char_0 && f <= char_9) { + return '_' + name + } else { + return name + } + } + function createNamedFunction(name, body) { + name = makeLegalFunctionName(name) + return new Function( + 'body', + 'return function ' + + name + + '() {\n' + + ' "use strict";' + + ' return body.apply(this, arguments);\n' + + '};\n' + )(body) + } + function extendError(baseErrorType, errorName) { + var errorClass = createNamedFunction(errorName, function (message) { + this.name = errorName + this.message = message + var stack = new Error(message).stack + if (stack !== undefined) { + this.stack = + this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '') + } + }) + errorClass.prototype = Object.create(baseErrorType.prototype) + errorClass.prototype.constructor = errorClass + errorClass.prototype.toString = function () { + if (this.message === undefined) { + return this.name + } else { + return this.name + ': ' + this.message + } + } + return errorClass + } + var BindingError = undefined + function throwBindingError(message) { + throw new BindingError(message) + } + var InternalError = undefined + function throwInternalError(message) { + throw new InternalError(message) + } + function whenDependentTypesAreResolved( + myTypes, + dependentTypes, + getTypeConverters + ) { + myTypes.forEach(function (type) { + typeDependencies[type] = dependentTypes + }) + function onComplete(typeConverters) { + var myTypeConverters = getTypeConverters(typeConverters) + if (myTypeConverters.length !== myTypes.length) { + throwInternalError('Mismatched type converter count') + } + for (var i = 0; i < myTypes.length; ++i) { + registerType(myTypes[i], myTypeConverters[i]) + } + } + var typeConverters = new Array(dependentTypes.length) + var unregisteredTypes = [] + var registered = 0 + dependentTypes.forEach(function (dt, i) { + if (registeredTypes.hasOwnProperty(dt)) { + typeConverters[i] = registeredTypes[dt] + } else { + unregisteredTypes.push(dt) + if (!awaitingDependencies.hasOwnProperty(dt)) { + awaitingDependencies[dt] = [] + } + awaitingDependencies[dt].push(function () { + typeConverters[i] = registeredTypes[dt] + ++registered + if (registered === unregisteredTypes.length) { + onComplete(typeConverters) + } + }) + } + }) + if (0 === unregisteredTypes.length) { + onComplete(typeConverters) + } + } + function registerType(rawType, registeredInstance, options) { + options = options || {} + if (!('argPackAdvance' in registeredInstance)) { + throw new TypeError( + 'registerType registeredInstance requires argPackAdvance' + ) + } + var name = registeredInstance.name + if (!rawType) { + throwBindingError( + 'type "' + name + '" must have a positive integer typeid pointer' + ) + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return + } else { + throwBindingError("Cannot register type '" + name + "' twice") + } + } + registeredTypes[rawType] = registeredInstance + delete typeDependencies[rawType] + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType] + delete awaitingDependencies[rawType] + callbacks.forEach(function (cb) { + cb() + }) + } + } + function __embind_register_bool( + rawType, + name, + size, + trueValue, + falseValue + ) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (wt) { + return !!wt + }, + toWireType: function (destructors, o) { + return o ? trueValue : falseValue + }, + argPackAdvance: 8, + readValueFromPointer: function (pointer) { + var heap + if (size === 1) { + heap = HEAP8 + } else if (size === 2) { + heap = HEAP16 + } else if (size === 4) { + heap = HEAP32 + } else { + throw new TypeError('Unknown boolean type size: ' + name) + } + return this['fromWireType'](heap[pointer >> shift]) + }, + destructorFunction: null, + }) + } + var emval_free_list = [] + var emval_handle_array = [ + {}, + { value: undefined }, + { value: null }, + { value: true }, + { value: false }, + ] + function __emval_decref(handle) { + if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { + emval_handle_array[handle] = undefined + emval_free_list.push(handle) + } + } + function count_emval_handles() { + var count = 0 + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + ++count + } + } + return count + } + function get_first_emval() { + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + return emval_handle_array[i] + } + } + return null + } + function init_emval() { + Module['count_emval_handles'] = count_emval_handles + Module['get_first_emval'] = get_first_emval + } + function __emval_register(value) { + switch (value) { + case undefined: { + return 1 + } + case null: { + return 2 + } + case true: { + return 3 + } + case false: { + return 4 + } + default: { + var handle = emval_free_list.length + ? emval_free_list.pop() + : emval_handle_array.length + emval_handle_array[handle] = { refcount: 1, value: value } + return handle + } + } + } + function simpleReadValueFromPointer(pointer) { + return this['fromWireType'](HEAPU32[pointer >> 2]) + } + function __embind_register_emval(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (handle) { + var rv = emval_handle_array[handle].value + __emval_decref(handle) + return rv + }, + toWireType: function (destructors, value) { + return __emval_register(value) + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: null, + }) + } + function _embind_repr(v) { + if (v === null) { + return 'null' + } + var t = typeof v + if (t === 'object' || t === 'array' || t === 'function') { + return v.toString() + } else { + return '' + v + } + } + function floatReadValueFromPointer(name, shift) { + switch (shift) { + case 2: + return function (pointer) { + return this['fromWireType'](HEAPF32[pointer >> 2]) + } + case 3: + return function (pointer) { + return this['fromWireType'](HEAPF64[pointer >> 3]) + } + default: + throw new TypeError('Unknown float type: ' + name) + } + } + function __embind_register_float(rawType, name, size) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (value) { + return value + }, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + return value + }, + argPackAdvance: 8, + readValueFromPointer: floatReadValueFromPointer(name, shift), + destructorFunction: null, + }) + } + function new_(constructor, argumentList) { + if (!(constructor instanceof Function)) { + throw new TypeError( + 'new_ called with constructor type ' + + typeof constructor + + ' which is not a function' + ) + } + var dummy = createNamedFunction( + constructor.name || 'unknownFunctionName', + function () {} + ) + dummy.prototype = constructor.prototype + var obj = new dummy() + var r = constructor.apply(obj, argumentList) + return r instanceof Object ? r : obj + } + function runDestructors(destructors) { + while (destructors.length) { + var ptr = destructors.pop() + var del = destructors.pop() + del(ptr) + } + } + function craftInvokerFunction( + humanName, + argTypes, + classType, + cppInvokerFunc, + cppTargetFunc + ) { + var argCount = argTypes.length + if (argCount < 2) { + throwBindingError( + "argTypes array size mismatch! Must at least get return value and 'this' types!" + ) + } + var isClassMethodFunc = argTypes[1] !== null && classType !== null + var needsDestructorStack = false + for (var i = 1; i < argTypes.length; ++i) { + if ( + argTypes[i] !== null && + argTypes[i].destructorFunction === undefined + ) { + needsDestructorStack = true + break + } + } + var returns = argTypes[0].name !== 'void' + var argsList = '' + var argsListWired = '' + for (var i = 0; i < argCount - 2; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired' + } + var invokerFnBody = + 'return function ' + + makeLegalFunctionName(humanName) + + '(' + + argsList + + ') {\n' + + 'if (arguments.length !== ' + + (argCount - 2) + + ') {\n' + + "throwBindingError('function " + + humanName + + " called with ' + arguments.length + ' arguments, expected " + + (argCount - 2) + + " args!');\n" + + '}\n' + if (needsDestructorStack) { + invokerFnBody += 'var destructors = [];\n' + } + var dtorStack = needsDestructorStack ? 'destructors' : 'null' + var args1 = [ + 'throwBindingError', + 'invoker', + 'fn', + 'runDestructors', + 'retType', + 'classParam', + ] + var args2 = [ + throwBindingError, + cppInvokerFunc, + cppTargetFunc, + runDestructors, + argTypes[0], + argTypes[1], + ] + if (isClassMethodFunc) { + invokerFnBody += + 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n' + } + for (var i = 0; i < argCount - 2; ++i) { + invokerFnBody += + 'var arg' + + i + + 'Wired = argType' + + i + + '.toWireType(' + + dtorStack + + ', arg' + + i + + '); // ' + + argTypes[i + 2].name + + '\n' + args1.push('argType' + i) + args2.push(argTypes[i + 2]) + } + if (isClassMethodFunc) { + argsListWired = + 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired + } + invokerFnBody += + (returns ? 'var rv = ' : '') + + 'invoker(fn' + + (argsListWired.length > 0 ? ', ' : '') + + argsListWired + + ');\n' + if (needsDestructorStack) { + invokerFnBody += 'runDestructors(destructors);\n' + } else { + for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { + var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired' + if (argTypes[i].destructorFunction !== null) { + invokerFnBody += + paramName + + '_dtor(' + + paramName + + '); // ' + + argTypes[i].name + + '\n' + args1.push(paramName + '_dtor') + args2.push(argTypes[i].destructorFunction) + } + } + } + if (returns) { + invokerFnBody += + 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n' + } else { + } + invokerFnBody += '}\n' + args1.push(invokerFnBody) + var invokerFunction = new_(Function, args1).apply(null, args2) + return invokerFunction + } + function ensureOverloadTable(proto, methodName, humanName) { + if (undefined === proto[methodName].overloadTable) { + var prevFunc = proto[methodName] + proto[methodName] = function () { + if ( + !proto[methodName].overloadTable.hasOwnProperty(arguments.length) + ) { + throwBindingError( + "Function '" + + humanName + + "' called with an invalid number of arguments (" + + arguments.length + + ') - expects one of (' + + proto[methodName].overloadTable + + ')!' + ) + } + return proto[methodName].overloadTable[arguments.length].apply( + this, + arguments + ) + } + proto[methodName].overloadTable = [] + proto[methodName].overloadTable[prevFunc.argCount] = prevFunc + } + } + function exposePublicSymbol(name, value, numArguments) { + if (Module.hasOwnProperty(name)) { + if ( + undefined === numArguments || + (undefined !== Module[name].overloadTable && + undefined !== Module[name].overloadTable[numArguments]) + ) { + throwBindingError("Cannot register public name '" + name + "' twice") + } + ensureOverloadTable(Module, name, name) + if (Module.hasOwnProperty(numArguments)) { + throwBindingError( + 'Cannot register multiple overloads of a function with the same number of arguments (' + + numArguments + + ')!' + ) + } + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + if (undefined !== numArguments) { + Module[name].numArguments = numArguments + } + } + } + function heap32VectorToArray(count, firstElement) { + var array = [] + for (var i = 0; i < count; i++) { + array.push(HEAP32[(firstElement >> 2) + i]) + } + return array + } + function replacePublicSymbol(name, value, numArguments) { + if (!Module.hasOwnProperty(name)) { + throwInternalError('Replacing nonexistent public symbol') + } + if ( + undefined !== Module[name].overloadTable && + undefined !== numArguments + ) { + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + Module[name].argCount = numArguments + } + } + function dynCallLegacy(sig, ptr, args) { + var f = Module['dynCall_' + sig] + return args && args.length + ? f.apply(null, [ptr].concat(args)) + : f.call(null, ptr) + } + function dynCall(sig, ptr, args) { + if (sig.includes('j')) { + return dynCallLegacy(sig, ptr, args) + } + return wasmTable.get(ptr).apply(null, args) + } + function getDynCaller(sig, ptr) { + var argCache = [] + return function () { + argCache.length = arguments.length + for (var i = 0; i < arguments.length; i++) { + argCache[i] = arguments[i] + } + return dynCall(sig, ptr, argCache) + } + } + function embind__requireFunction(signature, rawFunction) { + signature = readLatin1String(signature) + function makeDynCaller() { + if (signature.includes('j')) { + return getDynCaller(signature, rawFunction) + } + return wasmTable.get(rawFunction) + } + var fp = makeDynCaller() + if (typeof fp !== 'function') { + throwBindingError( + 'unknown function pointer with signature ' + + signature + + ': ' + + rawFunction + ) + } + return fp + } + var UnboundTypeError = undefined + function getTypeName(type) { + var ptr = ___getTypeName(type) + var rv = readLatin1String(ptr) + _free(ptr) + return rv + } + function throwUnboundTypeError(message, types) { + var unboundTypes = [] + var seen = {} + function visit(type) { + if (seen[type]) { + return + } + if (registeredTypes[type]) { + return + } + if (typeDependencies[type]) { + typeDependencies[type].forEach(visit) + return + } + unboundTypes.push(type) + seen[type] = true + } + types.forEach(visit) + throw new UnboundTypeError( + message + ': ' + unboundTypes.map(getTypeName).join([', ']) + ) + } + function __embind_register_function( + name, + argCount, + rawArgTypesAddr, + signature, + rawInvoker, + fn + ) { + var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr) + name = readLatin1String(name) + rawInvoker = embind__requireFunction(signature, rawInvoker) + exposePublicSymbol( + name, + function () { + throwUnboundTypeError( + 'Cannot call ' + name + ' due to unbound types', + argTypes + ) + }, + argCount - 1 + ) + whenDependentTypesAreResolved([], argTypes, function (argTypes) { + var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1)) + replacePublicSymbol( + name, + craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn), + argCount - 1 + ) + return [] + }) + } + function integerReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return signed + ? function readS8FromPointer(pointer) { + return HEAP8[pointer] + } + : function readU8FromPointer(pointer) { + return HEAPU8[pointer] + } + case 1: + return signed + ? function readS16FromPointer(pointer) { + return HEAP16[pointer >> 1] + } + : function readU16FromPointer(pointer) { + return HEAPU16[pointer >> 1] + } + case 2: + return signed + ? function readS32FromPointer(pointer) { + return HEAP32[pointer >> 2] + } + : function readU32FromPointer(pointer) { + return HEAPU32[pointer >> 2] + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_integer( + primitiveType, + name, + size, + minRange, + maxRange + ) { + name = readLatin1String(name) + if (maxRange === -1) { + maxRange = 4294967295 + } + var shift = getShiftFromSize(size) + var fromWireType = function (value) { + return value + } + if (minRange === 0) { + var bitshift = 32 - 8 * size + fromWireType = function (value) { + return (value << bitshift) >>> bitshift + } + } + var isUnsignedType = name.includes('unsigned') + registerType(primitiveType, { + name: name, + fromWireType: fromWireType, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + if (value < minRange || value > maxRange) { + throw new TypeError( + 'Passing a number "' + + _embind_repr(value) + + '" from JS side to C/C++ side to an argument of type "' + + name + + '", which is outside the valid range [' + + minRange + + ', ' + + maxRange + + ']!' + ) + } + return isUnsignedType ? value >>> 0 : value | 0 + }, + argPackAdvance: 8, + readValueFromPointer: integerReadValueFromPointer( + name, + shift, + minRange !== 0 + ), + destructorFunction: null, + }) + } + function __embind_register_memory_view(rawType, dataTypeIndex, name) { + var typeMapping = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + ] + var TA = typeMapping[dataTypeIndex] + function decodeMemoryView(handle) { + handle = handle >> 2 + var heap = HEAPU32 + var size = heap[handle] + var data = heap[handle + 1] + return new TA(buffer, data, size) + } + name = readLatin1String(name) + registerType( + rawType, + { + name: name, + fromWireType: decodeMemoryView, + argPackAdvance: 8, + readValueFromPointer: decodeMemoryView, + }, + { ignoreDuplicateRegistrations: true } + ) + } + function __embind_register_std_string(rawType, name) { + name = readLatin1String(name) + var stdStringIsUTF8 = name === 'std::string' + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var str + if (stdStringIsUTF8) { + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i + if (i == length || HEAPU8[currentBytePtr] == 0) { + var maxRead = currentBytePtr - decodeStartPtr + var stringSegment = UTF8ToString(decodeStartPtr, maxRead) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + 1 + } + } + } else { + var a = new Array(length) + for (var i = 0; i < length; ++i) { + a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) + } + str = a.join('') + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value) + } + var getLength + var valueIsOfTypeString = typeof value === 'string' + if ( + !( + valueIsOfTypeString || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int8Array + ) + ) { + throwBindingError('Cannot pass non-string to std::string') + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + getLength = function () { + return lengthBytesUTF8(value) + } + } else { + getLength = function () { + return value.length + } + } + var length = getLength() + var ptr = _malloc(4 + length + 1) + HEAPU32[ptr >> 2] = length + if (stdStringIsUTF8 && valueIsOfTypeString) { + stringToUTF8(value, ptr + 4, length + 1) + } else { + if (valueIsOfTypeString) { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i) + if (charCode > 255) { + _free(ptr) + throwBindingError( + 'String has UTF-16 code units that do not fit in 8 bits' + ) + } + HEAPU8[ptr + 4 + i] = charCode + } + } else { + for (var i = 0; i < length; ++i) { + HEAPU8[ptr + 4 + i] = value[i] + } + } + } + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_std_wstring(rawType, charSize, name) { + name = readLatin1String(name) + var decodeString, encodeString, getHeap, lengthBytesUTF, shift + if (charSize === 2) { + decodeString = UTF16ToString + encodeString = stringToUTF16 + lengthBytesUTF = lengthBytesUTF16 + getHeap = function () { + return HEAPU16 + } + shift = 1 + } else if (charSize === 4) { + decodeString = UTF32ToString + encodeString = stringToUTF32 + lengthBytesUTF = lengthBytesUTF32 + getHeap = function () { + return HEAPU32 + } + shift = 2 + } + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var HEAP = getHeap() + var str + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i * charSize + if (i == length || HEAP[currentBytePtr >> shift] == 0) { + var maxReadBytes = currentBytePtr - decodeStartPtr + var stringSegment = decodeString(decodeStartPtr, maxReadBytes) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + charSize + } + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (!(typeof value === 'string')) { + throwBindingError( + 'Cannot pass non-string to C++ string type ' + name + ) + } + var length = lengthBytesUTF(value) + var ptr = _malloc(4 + length + charSize) + HEAPU32[ptr >> 2] = length >> shift + encodeString(value, ptr + 4, length + charSize) + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_void(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + isVoid: true, + name: name, + argPackAdvance: 0, + fromWireType: function () { + return undefined + }, + toWireType: function (destructors, o) { + return undefined + }, + }) + } + var emval_symbols = {} + function getStringOrSymbol(address) { + var symbol = emval_symbols[address] + if (symbol === undefined) { + return readLatin1String(address) + } else { + return symbol + } + } + function emval_get_global() { + if (typeof globalThis === 'object') { + return globalThis + } + return (function () { + return Function + })()('return this')() + } + function __emval_get_global(name) { + if (name === 0) { + return __emval_register(emval_get_global()) + } else { + name = getStringOrSymbol(name) + return __emval_register(emval_get_global()[name]) + } + } + function __emval_incref(handle) { + if (handle > 4) { + emval_handle_array[handle].refcount += 1 + } + } + function requireRegisteredType(rawType, humanName) { + var impl = registeredTypes[rawType] + if (undefined === impl) { + throwBindingError( + humanName + ' has unknown type ' + getTypeName(rawType) + ) + } + return impl + } + function craftEmvalAllocator(argCount) { + var argsList = '' + for (var i = 0; i < argCount; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + } + var functionBody = + 'return function emval_allocator_' + + argCount + + '(constructor, argTypes, args) {\n' + for (var i = 0; i < argCount; ++i) { + functionBody += + 'var argType' + + i + + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + + i + + '], "parameter ' + + i + + '");\n' + + 'var arg' + + i + + ' = argType' + + i + + '.readValueFromPointer(args);\n' + + 'args += argType' + + i + + "['argPackAdvance'];\n" + } + functionBody += + 'var obj = new constructor(' + + argsList + + ');\n' + + 'return __emval_register(obj);\n' + + '}\n' + return new Function( + 'requireRegisteredType', + 'Module', + '__emval_register', + functionBody + )(requireRegisteredType, Module, __emval_register) + } + var emval_newers = {} + function requireHandle(handle) { + if (!handle) { + throwBindingError('Cannot use deleted val. handle = ' + handle) + } + return emval_handle_array[handle].value + } + function __emval_new(handle, argCount, argTypes, args) { + handle = requireHandle(handle) + var newer = emval_newers[argCount] + if (!newer) { + newer = craftEmvalAllocator(argCount) + emval_newers[argCount] = newer + } + return newer(handle, argTypes, args) + } + function _abort() { + abort() + } + function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.copyWithin(dest, src, src + num) + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16) + updateGlobalBufferAndViews(wasmMemory.buffer) + return 1 + } catch (e) {} + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length + requestedSize = requestedSize >>> 0 + var maxHeapSize = 2147483648 + if (requestedSize > maxHeapSize) { + return false + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown) + overGrownHeapSize = Math.min( + overGrownHeapSize, + requestedSize + 100663296 + ) + var newSize = Math.min( + maxHeapSize, + alignUp(Math.max(requestedSize, overGrownHeapSize), 65536) + ) + var replacement = emscripten_realloc_buffer(newSize) + if (replacement) { + return true + } + } + return false + } + embind_init_charCodes() + BindingError = Module['BindingError'] = extendError(Error, 'BindingError') + InternalError = Module['InternalError'] = extendError( + Error, + 'InternalError' + ) + init_emval() + UnboundTypeError = Module['UnboundTypeError'] = extendError( + Error, + 'UnboundTypeError' + ) + var asmLibraryArg = { + e: ___cxa_thread_atexit, + p: __embind_register_bigint, + n: __embind_register_bool, + r: __embind_register_emval, + m: __embind_register_float, + i: __embind_register_function, + b: __embind_register_integer, + a: __embind_register_memory_view, + h: __embind_register_std_string, + f: __embind_register_std_wstring, + o: __embind_register_void, + c: __emval_decref, + d: __emval_get_global, + j: __emval_incref, + k: __emval_new, + l: _abort, + q: _emscripten_memcpy_big, + g: _emscripten_resize_heap, + } + var asm = createWasm() + var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () { + return (___wasm_call_ctors = Module['___wasm_call_ctors'] = + Module['asm']['t']).apply(null, arguments) + }) + var _malloc = (Module['_malloc'] = function () { + return (_malloc = Module['_malloc'] = Module['asm']['u']).apply( + null, + arguments + ) + }) + var _free = (Module['_free'] = function () { + return (_free = Module['_free'] = Module['asm']['v']).apply( + null, + arguments + ) + }) + var ___getTypeName = (Module['___getTypeName'] = function () { + return (___getTypeName = Module['___getTypeName'] = + Module['asm']['w']).apply(null, arguments) + }) + var ___embind_register_native_and_builtin_types = (Module[ + '___embind_register_native_and_builtin_types' + ] = function () { + return (___embind_register_native_and_builtin_types = Module[ + '___embind_register_native_and_builtin_types' + ] = + Module['asm']['x']).apply(null, arguments) + }) + var calledRun + dependenciesFulfilled = function runCaller() { + if (!calledRun) run() + if (!calledRun) dependenciesFulfilled = runCaller + } + function run(args) { + args = args || arguments_ + if (runDependencies > 0) { + return + } + preRun() + if (runDependencies > 0) { + return + } + function doRun() { + if (calledRun) return + calledRun = true + Module['calledRun'] = true + if (ABORT) return + initRuntime() + readyPromiseResolve(Module) + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() + postRun() + } + if (Module['setStatus']) { + Module['setStatus']('Running...') + setTimeout(function () { + setTimeout(function () { + Module['setStatus']('') + }, 1) + doRun() + }, 1) + } else { + doRun() + } + } + Module['run'] = run + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') + Module['preInit'] = [Module['preInit']] + while (Module['preInit'].length > 0) { + Module['preInit'].pop()() + } + } + run() + + return Module.ready + } +})() +export default Module diff --git a/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_dec.wasm b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_dec.wasm new file mode 100644 index 000000000000..5df324336ca6 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_dec.wasm differ diff --git a/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_enc.ts b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_enc.ts new file mode 100644 index 000000000000..d1c350d2b952 --- /dev/null +++ b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_enc.ts @@ -0,0 +1,1799 @@ +/* eslint-disable */ +// @ts-nocheck +import { createRequire } from 'module'; +import { dirname, getModuleURL } from '../emscripten-utils.js'; +const require = createRequire(getModuleURL(import.meta.url)); + +var Module = (function () { + return function (Module) { + Module = Module || {} + + var Module = typeof Module !== 'undefined' ? Module : {} + var readyPromiseResolve, readyPromiseReject + Module['ready'] = new Promise(function (resolve, reject) { + readyPromiseResolve = resolve + readyPromiseReject = reject + }) + var moduleOverrides = {} + var key + for (key in Module) { + if (Module.hasOwnProperty(key)) { + moduleOverrides[key] = Module[key] + } + } + var arguments_ = [] + var thisProgram = './this.program' + var quit_ = function (status, toThrow) { + throw toThrow + } + var ENVIRONMENT_IS_WEB = false + var ENVIRONMENT_IS_WORKER = false + var ENVIRONMENT_IS_NODE = true + var scriptDirectory = '' + function locateFile(path) { + if (Module['locateFile']) { + return Module['locateFile'](path, scriptDirectory) + } + return scriptDirectory + path + } + var read_, readBinary + var nodeFS + var nodePath + if (ENVIRONMENT_IS_NODE) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = require('path').dirname(scriptDirectory) + '/' + } else { + scriptDirectory = dirname(getModuleURL(import.meta.url)) + '/' + } + read_ = function shell_read(filename, binary) { + if (!nodeFS) nodeFS = require('fs') + if (!nodePath) nodePath = require('path') + filename = nodePath['normalize'](filename) + return nodeFS['readFileSync'](filename, binary ? null : 'utf8') + } + readBinary = function readBinary(filename) { + var ret = read_(filename, true) + if (!ret.buffer) { + ret = new Uint8Array(ret) + } + assert(ret.buffer) + return ret + } + if (process['argv'].length > 1) { + thisProgram = process['argv'][1].replace(/\\/g, '/') + } + arguments_ = process['argv'].slice(2) + quit_ = function (status) { + process['exit'](status) + } + Module['inspect'] = function () { + return '[Emscripten Module object]' + } + } else { + } + var out = Module['print'] || console.log.bind(console) + var err = Module['printErr'] || console.warn.bind(console) + for (key in moduleOverrides) { + if (moduleOverrides.hasOwnProperty(key)) { + Module[key] = moduleOverrides[key] + } + } + moduleOverrides = null + if (Module['arguments']) arguments_ = Module['arguments'] + if (Module['thisProgram']) thisProgram = Module['thisProgram'] + if (Module['quit']) quit_ = Module['quit'] + var wasmBinary + if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'] + var noExitRuntime = Module['noExitRuntime'] || true + if (typeof WebAssembly !== 'object') { + abort('no native wasm support detected') + } + var wasmMemory + var ABORT = false + var EXITSTATUS + function assert(condition, text) { + if (!condition) { + abort('Assertion failed: ' + text) + } + } + var UTF8Decoder = new TextDecoder('utf8') + function UTF8ToString(ptr, maxBytesToRead) { + if (!ptr) return '' + var maxPtr = ptr + maxBytesToRead + for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)) + } + function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { + if (!(maxBytesToWrite > 0)) return 0 + var startIdx = outIdx + var endIdx = outIdx + maxBytesToWrite - 1 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) { + var u1 = str.charCodeAt(++i) + u = (65536 + ((u & 1023) << 10)) | (u1 & 1023) + } + if (u <= 127) { + if (outIdx >= endIdx) break + heap[outIdx++] = u + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break + heap[outIdx++] = 192 | (u >> 6) + heap[outIdx++] = 128 | (u & 63) + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break + heap[outIdx++] = 224 | (u >> 12) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } else { + if (outIdx + 3 >= endIdx) break + heap[outIdx++] = 240 | (u >> 18) + heap[outIdx++] = 128 | ((u >> 12) & 63) + heap[outIdx++] = 128 | ((u >> 6) & 63) + heap[outIdx++] = 128 | (u & 63) + } + } + heap[outIdx] = 0 + return outIdx - startIdx + } + function stringToUTF8(str, outPtr, maxBytesToWrite) { + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) + } + function lengthBytesUTF8(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i) + if (u >= 55296 && u <= 57343) + u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023) + if (u <= 127) ++len + else if (u <= 2047) len += 2 + else if (u <= 65535) len += 3 + else len += 4 + } + return len + } + var UTF16Decoder = new TextDecoder('utf-16le') + function UTF16ToString(ptr, maxBytesToRead) { + var endPtr = ptr + var idx = endPtr >> 1 + var maxIdx = idx + maxBytesToRead / 2 + while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx + endPtr = idx << 1 + return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)) + var str = '' + for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { + var codeUnit = HEAP16[(ptr + i * 2) >> 1] + if (codeUnit == 0) break + str += String.fromCharCode(codeUnit) + } + return str + } + function stringToUTF16(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 2) return 0 + maxBytesToWrite -= 2 + var startPtr = outPtr + var numCharsToWrite = + maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i) + HEAP16[outPtr >> 1] = codeUnit + outPtr += 2 + } + HEAP16[outPtr >> 1] = 0 + return outPtr - startPtr + } + function lengthBytesUTF16(str) { + return str.length * 2 + } + function UTF32ToString(ptr, maxBytesToRead) { + var i = 0 + var str = '' + while (!(i >= maxBytesToRead / 4)) { + var utf32 = HEAP32[(ptr + i * 4) >> 2] + if (utf32 == 0) break + ++i + if (utf32 >= 65536) { + var ch = utf32 - 65536 + str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)) + } else { + str += String.fromCharCode(utf32) + } + } + return str + } + function stringToUTF32(str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 2147483647 + } + if (maxBytesToWrite < 4) return 0 + var startPtr = outPtr + var endPtr = startPtr + maxBytesToWrite - 4 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) { + var trailSurrogate = str.charCodeAt(++i) + codeUnit = + (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023) + } + HEAP32[outPtr >> 2] = codeUnit + outPtr += 4 + if (outPtr + 4 > endPtr) break + } + HEAP32[outPtr >> 2] = 0 + return outPtr - startPtr + } + function lengthBytesUTF32(str) { + var len = 0 + for (var i = 0; i < str.length; ++i) { + var codeUnit = str.charCodeAt(i) + if (codeUnit >= 55296 && codeUnit <= 57343) ++i + len += 4 + } + return len + } + function alignUp(x, multiple) { + if (x % multiple > 0) { + x += multiple - (x % multiple) + } + return x + } + var buffer, + HEAP8, + HEAPU8, + HEAP16, + HEAPU16, + HEAP32, + HEAPU32, + HEAPF32, + HEAPF64 + function updateGlobalBufferAndViews(buf) { + buffer = buf + Module['HEAP8'] = HEAP8 = new Int8Array(buf) + Module['HEAP16'] = HEAP16 = new Int16Array(buf) + Module['HEAP32'] = HEAP32 = new Int32Array(buf) + Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf) + Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf) + Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf) + Module['HEAPF32'] = HEAPF32 = new Float32Array(buf) + Module['HEAPF64'] = HEAPF64 = new Float64Array(buf) + } + var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 + var wasmTable + var __ATPRERUN__ = [] + var __ATINIT__ = [] + var __ATPOSTRUN__ = [] + var runtimeInitialized = false + function preRun() { + if (Module['preRun']) { + if (typeof Module['preRun'] == 'function') + Module['preRun'] = [Module['preRun']] + while (Module['preRun'].length) { + addOnPreRun(Module['preRun'].shift()) + } + } + callRuntimeCallbacks(__ATPRERUN__) + } + function initRuntime() { + runtimeInitialized = true + callRuntimeCallbacks(__ATINIT__) + } + function postRun() { + if (Module['postRun']) { + if (typeof Module['postRun'] == 'function') + Module['postRun'] = [Module['postRun']] + while (Module['postRun'].length) { + addOnPostRun(Module['postRun'].shift()) + } + } + callRuntimeCallbacks(__ATPOSTRUN__) + } + function addOnPreRun(cb) { + __ATPRERUN__.unshift(cb) + } + function addOnInit(cb) { + __ATINIT__.unshift(cb) + } + function addOnPostRun(cb) { + __ATPOSTRUN__.unshift(cb) + } + var runDependencies = 0 + var runDependencyWatcher = null + var dependenciesFulfilled = null + function addRunDependency(id) { + runDependencies++ + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + } + function removeRunDependency(id) { + runDependencies-- + if (Module['monitorRunDependencies']) { + Module['monitorRunDependencies'](runDependencies) + } + if (runDependencies == 0) { + if (runDependencyWatcher !== null) { + clearInterval(runDependencyWatcher) + runDependencyWatcher = null + } + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled + dependenciesFulfilled = null + callback() + } + } + } + Module['preloadedImages'] = {} + Module['preloadedAudios'] = {} + function abort(what) { + if (Module['onAbort']) { + Module['onAbort'](what) + } + what += '' + err(what) + ABORT = true + EXITSTATUS = 1 + what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.' + var e = new WebAssembly.RuntimeError(what) + readyPromiseReject(e) + throw e + } + var dataURIPrefix = 'data:application/octet-stream;base64,' + function isDataURI(filename) { + return filename.startsWith(dataURIPrefix) + } + if (Module['locateFile']) { + var wasmBinaryFile = 'webp_node_enc.wasm' + if (!isDataURI(wasmBinaryFile)) { + wasmBinaryFile = locateFile(wasmBinaryFile) + } + } else { + throw new Error('invariant') + } + function getBinary(file) { + try { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary) + } + if (readBinary) { + return readBinary(file) + } else { + throw 'both async and sync fetching of the wasm failed' + } + } catch (err) { + abort(err) + } + } + function getBinaryPromise() { + return Promise.resolve().then(function () { + return getBinary(wasmBinaryFile) + }) + } + function createWasm() { + var info = { a: asmLibraryArg } + function receiveInstance(instance, module) { + var exports = instance.exports + Module['asm'] = exports + wasmMemory = Module['asm']['x'] + updateGlobalBufferAndViews(wasmMemory.buffer) + wasmTable = Module['asm']['D'] + addOnInit(Module['asm']['y']) + removeRunDependency('wasm-instantiate') + } + addRunDependency('wasm-instantiate') + function receiveInstantiationResult(result) { + receiveInstance(result['instance']) + } + function instantiateArrayBuffer(receiver) { + return getBinaryPromise() + .then(function (binary) { + var result = WebAssembly.instantiate(binary, info) + return result + }) + .then(receiver, function (reason) { + err('failed to asynchronously prepare wasm: ' + reason) + abort(reason) + }) + } + function instantiateAsync() { + return instantiateArrayBuffer(receiveInstantiationResult) + } + if (Module['instantiateWasm']) { + try { + var exports = Module['instantiateWasm'](info, receiveInstance) + return exports + } catch (e) { + err('Module.instantiateWasm callback failed with error: ' + e) + return false + } + } + instantiateAsync().catch(readyPromiseReject) + return {} + } + function callRuntimeCallbacks(callbacks) { + while (callbacks.length > 0) { + var callback = callbacks.shift() + if (typeof callback == 'function') { + callback(Module) + continue + } + var func = callback.func + if (typeof func === 'number') { + if (callback.arg === undefined) { + wasmTable.get(func)() + } else { + wasmTable.get(func)(callback.arg) + } + } else { + func(callback.arg === undefined ? null : callback.arg) + } + } + } + function _atexit(func, arg) {} + function ___cxa_thread_atexit(a0, a1) { + return _atexit(a0, a1) + } + var structRegistrations = {} + function runDestructors(destructors) { + while (destructors.length) { + var ptr = destructors.pop() + var del = destructors.pop() + del(ptr) + } + } + function simpleReadValueFromPointer(pointer) { + return this['fromWireType'](HEAPU32[pointer >> 2]) + } + var awaitingDependencies = {} + var registeredTypes = {} + var typeDependencies = {} + var char_0 = 48 + var char_9 = 57 + function makeLegalFunctionName(name) { + if (undefined === name) { + return '_unknown' + } + name = name.replace(/[^a-zA-Z0-9_]/g, '$') + var f = name.charCodeAt(0) + if (f >= char_0 && f <= char_9) { + return '_' + name + } else { + return name + } + } + function createNamedFunction(name, body) { + name = makeLegalFunctionName(name) + return new Function( + 'body', + 'return function ' + + name + + '() {\n' + + ' "use strict";' + + ' return body.apply(this, arguments);\n' + + '};\n' + )(body) + } + function extendError(baseErrorType, errorName) { + var errorClass = createNamedFunction(errorName, function (message) { + this.name = errorName + this.message = message + var stack = new Error(message).stack + if (stack !== undefined) { + this.stack = + this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '') + } + }) + errorClass.prototype = Object.create(baseErrorType.prototype) + errorClass.prototype.constructor = errorClass + errorClass.prototype.toString = function () { + if (this.message === undefined) { + return this.name + } else { + return this.name + ': ' + this.message + } + } + return errorClass + } + var InternalError = undefined + function throwInternalError(message) { + throw new InternalError(message) + } + function whenDependentTypesAreResolved( + myTypes, + dependentTypes, + getTypeConverters + ) { + myTypes.forEach(function (type) { + typeDependencies[type] = dependentTypes + }) + function onComplete(typeConverters) { + var myTypeConverters = getTypeConverters(typeConverters) + if (myTypeConverters.length !== myTypes.length) { + throwInternalError('Mismatched type converter count') + } + for (var i = 0; i < myTypes.length; ++i) { + registerType(myTypes[i], myTypeConverters[i]) + } + } + var typeConverters = new Array(dependentTypes.length) + var unregisteredTypes = [] + var registered = 0 + dependentTypes.forEach(function (dt, i) { + if (registeredTypes.hasOwnProperty(dt)) { + typeConverters[i] = registeredTypes[dt] + } else { + unregisteredTypes.push(dt) + if (!awaitingDependencies.hasOwnProperty(dt)) { + awaitingDependencies[dt] = [] + } + awaitingDependencies[dt].push(function () { + typeConverters[i] = registeredTypes[dt] + ++registered + if (registered === unregisteredTypes.length) { + onComplete(typeConverters) + } + }) + } + }) + if (0 === unregisteredTypes.length) { + onComplete(typeConverters) + } + } + function __embind_finalize_value_object(structType) { + var reg = structRegistrations[structType] + delete structRegistrations[structType] + var rawConstructor = reg.rawConstructor + var rawDestructor = reg.rawDestructor + var fieldRecords = reg.fields + var fieldTypes = fieldRecords + .map(function (field) { + return field.getterReturnType + }) + .concat( + fieldRecords.map(function (field) { + return field.setterArgumentType + }) + ) + whenDependentTypesAreResolved( + [structType], + fieldTypes, + function (fieldTypes) { + var fields = {} + fieldRecords.forEach(function (field, i) { + var fieldName = field.fieldName + var getterReturnType = fieldTypes[i] + var getter = field.getter + var getterContext = field.getterContext + var setterArgumentType = fieldTypes[i + fieldRecords.length] + var setter = field.setter + var setterContext = field.setterContext + fields[fieldName] = { + read: function (ptr) { + return getterReturnType['fromWireType']( + getter(getterContext, ptr) + ) + }, + write: function (ptr, o) { + var destructors = [] + setter( + setterContext, + ptr, + setterArgumentType['toWireType'](destructors, o) + ) + runDestructors(destructors) + }, + } + }) + return [ + { + name: reg.name, + fromWireType: function (ptr) { + var rv = {} + for (var i in fields) { + rv[i] = fields[i].read(ptr) + } + rawDestructor(ptr) + return rv + }, + toWireType: function (destructors, o) { + for (var fieldName in fields) { + if (!(fieldName in o)) { + throw new TypeError('Missing field: "' + fieldName + '"') + } + } + var ptr = rawConstructor() + for (fieldName in fields) { + fields[fieldName].write(ptr, o[fieldName]) + } + if (destructors !== null) { + destructors.push(rawDestructor, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: rawDestructor, + }, + ] + } + ) + } + function __embind_register_bigint( + primitiveType, + name, + size, + minRange, + maxRange + ) {} + function getShiftFromSize(size) { + switch (size) { + case 1: + return 0 + case 2: + return 1 + case 4: + return 2 + case 8: + return 3 + default: + throw new TypeError('Unknown type size: ' + size) + } + } + function embind_init_charCodes() { + var codes = new Array(256) + for (var i = 0; i < 256; ++i) { + codes[i] = String.fromCharCode(i) + } + embind_charCodes = codes + } + var embind_charCodes = undefined + function readLatin1String(ptr) { + var ret = '' + var c = ptr + while (HEAPU8[c]) { + ret += embind_charCodes[HEAPU8[c++]] + } + return ret + } + var BindingError = undefined + function throwBindingError(message) { + throw new BindingError(message) + } + function registerType(rawType, registeredInstance, options) { + options = options || {} + if (!('argPackAdvance' in registeredInstance)) { + throw new TypeError( + 'registerType registeredInstance requires argPackAdvance' + ) + } + var name = registeredInstance.name + if (!rawType) { + throwBindingError( + 'type "' + name + '" must have a positive integer typeid pointer' + ) + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return + } else { + throwBindingError("Cannot register type '" + name + "' twice") + } + } + registeredTypes[rawType] = registeredInstance + delete typeDependencies[rawType] + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType] + delete awaitingDependencies[rawType] + callbacks.forEach(function (cb) { + cb() + }) + } + } + function __embind_register_bool( + rawType, + name, + size, + trueValue, + falseValue + ) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (wt) { + return !!wt + }, + toWireType: function (destructors, o) { + return o ? trueValue : falseValue + }, + argPackAdvance: 8, + readValueFromPointer: function (pointer) { + var heap + if (size === 1) { + heap = HEAP8 + } else if (size === 2) { + heap = HEAP16 + } else if (size === 4) { + heap = HEAP32 + } else { + throw new TypeError('Unknown boolean type size: ' + name) + } + return this['fromWireType'](heap[pointer >> shift]) + }, + destructorFunction: null, + }) + } + var emval_free_list = [] + var emval_handle_array = [ + {}, + { value: undefined }, + { value: null }, + { value: true }, + { value: false }, + ] + function __emval_decref(handle) { + if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { + emval_handle_array[handle] = undefined + emval_free_list.push(handle) + } + } + function count_emval_handles() { + var count = 0 + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + ++count + } + } + return count + } + function get_first_emval() { + for (var i = 5; i < emval_handle_array.length; ++i) { + if (emval_handle_array[i] !== undefined) { + return emval_handle_array[i] + } + } + return null + } + function init_emval() { + Module['count_emval_handles'] = count_emval_handles + Module['get_first_emval'] = get_first_emval + } + function __emval_register(value) { + switch (value) { + case undefined: { + return 1 + } + case null: { + return 2 + } + case true: { + return 3 + } + case false: { + return 4 + } + default: { + var handle = emval_free_list.length + ? emval_free_list.pop() + : emval_handle_array.length + emval_handle_array[handle] = { refcount: 1, value: value } + return handle + } + } + } + function __embind_register_emval(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (handle) { + var rv = emval_handle_array[handle].value + __emval_decref(handle) + return rv + }, + toWireType: function (destructors, value) { + return __emval_register(value) + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: null, + }) + } + function ensureOverloadTable(proto, methodName, humanName) { + if (undefined === proto[methodName].overloadTable) { + var prevFunc = proto[methodName] + proto[methodName] = function () { + if ( + !proto[methodName].overloadTable.hasOwnProperty(arguments.length) + ) { + throwBindingError( + "Function '" + + humanName + + "' called with an invalid number of arguments (" + + arguments.length + + ') - expects one of (' + + proto[methodName].overloadTable + + ')!' + ) + } + return proto[methodName].overloadTable[arguments.length].apply( + this, + arguments + ) + } + proto[methodName].overloadTable = [] + proto[methodName].overloadTable[prevFunc.argCount] = prevFunc + } + } + function exposePublicSymbol(name, value, numArguments) { + if (Module.hasOwnProperty(name)) { + if ( + undefined === numArguments || + (undefined !== Module[name].overloadTable && + undefined !== Module[name].overloadTable[numArguments]) + ) { + throwBindingError("Cannot register public name '" + name + "' twice") + } + ensureOverloadTable(Module, name, name) + if (Module.hasOwnProperty(numArguments)) { + throwBindingError( + 'Cannot register multiple overloads of a function with the same number of arguments (' + + numArguments + + ')!' + ) + } + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + if (undefined !== numArguments) { + Module[name].numArguments = numArguments + } + } + } + function enumReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return function (pointer) { + var heap = signed ? HEAP8 : HEAPU8 + return this['fromWireType'](heap[pointer]) + } + case 1: + return function (pointer) { + var heap = signed ? HEAP16 : HEAPU16 + return this['fromWireType'](heap[pointer >> 1]) + } + case 2: + return function (pointer) { + var heap = signed ? HEAP32 : HEAPU32 + return this['fromWireType'](heap[pointer >> 2]) + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_enum(rawType, name, size, isSigned) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + function ctor() {} + ctor.values = {} + registerType(rawType, { + name: name, + constructor: ctor, + fromWireType: function (c) { + return this.constructor.values[c] + }, + toWireType: function (destructors, c) { + return c.value + }, + argPackAdvance: 8, + readValueFromPointer: enumReadValueFromPointer(name, shift, isSigned), + destructorFunction: null, + }) + exposePublicSymbol(name, ctor) + } + function getTypeName(type) { + var ptr = ___getTypeName(type) + var rv = readLatin1String(ptr) + _free(ptr) + return rv + } + function requireRegisteredType(rawType, humanName) { + var impl = registeredTypes[rawType] + if (undefined === impl) { + throwBindingError( + humanName + ' has unknown type ' + getTypeName(rawType) + ) + } + return impl + } + function __embind_register_enum_value(rawEnumType, name, enumValue) { + var enumType = requireRegisteredType(rawEnumType, 'enum') + name = readLatin1String(name) + var Enum = enumType.constructor + var Value = Object.create(enumType.constructor.prototype, { + value: { value: enumValue }, + constructor: { + value: createNamedFunction( + enumType.name + '_' + name, + function () {} + ), + }, + }) + Enum.values[enumValue] = Value + Enum[name] = Value + } + function _embind_repr(v) { + if (v === null) { + return 'null' + } + var t = typeof v + if (t === 'object' || t === 'array' || t === 'function') { + return v.toString() + } else { + return '' + v + } + } + function floatReadValueFromPointer(name, shift) { + switch (shift) { + case 2: + return function (pointer) { + return this['fromWireType'](HEAPF32[pointer >> 2]) + } + case 3: + return function (pointer) { + return this['fromWireType'](HEAPF64[pointer >> 3]) + } + default: + throw new TypeError('Unknown float type: ' + name) + } + } + function __embind_register_float(rawType, name, size) { + var shift = getShiftFromSize(size) + name = readLatin1String(name) + registerType(rawType, { + name: name, + fromWireType: function (value) { + return value + }, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + return value + }, + argPackAdvance: 8, + readValueFromPointer: floatReadValueFromPointer(name, shift), + destructorFunction: null, + }) + } + function new_(constructor, argumentList) { + if (!(constructor instanceof Function)) { + throw new TypeError( + 'new_ called with constructor type ' + + typeof constructor + + ' which is not a function' + ) + } + var dummy = createNamedFunction( + constructor.name || 'unknownFunctionName', + function () {} + ) + dummy.prototype = constructor.prototype + var obj = new dummy() + var r = constructor.apply(obj, argumentList) + return r instanceof Object ? r : obj + } + function craftInvokerFunction( + humanName, + argTypes, + classType, + cppInvokerFunc, + cppTargetFunc + ) { + var argCount = argTypes.length + if (argCount < 2) { + throwBindingError( + "argTypes array size mismatch! Must at least get return value and 'this' types!" + ) + } + var isClassMethodFunc = argTypes[1] !== null && classType !== null + var needsDestructorStack = false + for (var i = 1; i < argTypes.length; ++i) { + if ( + argTypes[i] !== null && + argTypes[i].destructorFunction === undefined + ) { + needsDestructorStack = true + break + } + } + var returns = argTypes[0].name !== 'void' + var argsList = '' + var argsListWired = '' + for (var i = 0; i < argCount - 2; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired' + } + var invokerFnBody = + 'return function ' + + makeLegalFunctionName(humanName) + + '(' + + argsList + + ') {\n' + + 'if (arguments.length !== ' + + (argCount - 2) + + ') {\n' + + "throwBindingError('function " + + humanName + + " called with ' + arguments.length + ' arguments, expected " + + (argCount - 2) + + " args!');\n" + + '}\n' + if (needsDestructorStack) { + invokerFnBody += 'var destructors = [];\n' + } + var dtorStack = needsDestructorStack ? 'destructors' : 'null' + var args1 = [ + 'throwBindingError', + 'invoker', + 'fn', + 'runDestructors', + 'retType', + 'classParam', + ] + var args2 = [ + throwBindingError, + cppInvokerFunc, + cppTargetFunc, + runDestructors, + argTypes[0], + argTypes[1], + ] + if (isClassMethodFunc) { + invokerFnBody += + 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n' + } + for (var i = 0; i < argCount - 2; ++i) { + invokerFnBody += + 'var arg' + + i + + 'Wired = argType' + + i + + '.toWireType(' + + dtorStack + + ', arg' + + i + + '); // ' + + argTypes[i + 2].name + + '\n' + args1.push('argType' + i) + args2.push(argTypes[i + 2]) + } + if (isClassMethodFunc) { + argsListWired = + 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired + } + invokerFnBody += + (returns ? 'var rv = ' : '') + + 'invoker(fn' + + (argsListWired.length > 0 ? ', ' : '') + + argsListWired + + ');\n' + if (needsDestructorStack) { + invokerFnBody += 'runDestructors(destructors);\n' + } else { + for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { + var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired' + if (argTypes[i].destructorFunction !== null) { + invokerFnBody += + paramName + + '_dtor(' + + paramName + + '); // ' + + argTypes[i].name + + '\n' + args1.push(paramName + '_dtor') + args2.push(argTypes[i].destructorFunction) + } + } + } + if (returns) { + invokerFnBody += + 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n' + } else { + } + invokerFnBody += '}\n' + args1.push(invokerFnBody) + var invokerFunction = new_(Function, args1).apply(null, args2) + return invokerFunction + } + function heap32VectorToArray(count, firstElement) { + var array = [] + for (var i = 0; i < count; i++) { + array.push(HEAP32[(firstElement >> 2) + i]) + } + return array + } + function replacePublicSymbol(name, value, numArguments) { + if (!Module.hasOwnProperty(name)) { + throwInternalError('Replacing nonexistent public symbol') + } + if ( + undefined !== Module[name].overloadTable && + undefined !== numArguments + ) { + Module[name].overloadTable[numArguments] = value + } else { + Module[name] = value + Module[name].argCount = numArguments + } + } + function dynCallLegacy(sig, ptr, args) { + var f = Module['dynCall_' + sig] + return args && args.length + ? f.apply(null, [ptr].concat(args)) + : f.call(null, ptr) + } + function dynCall(sig, ptr, args) { + if (sig.includes('j')) { + return dynCallLegacy(sig, ptr, args) + } + return wasmTable.get(ptr).apply(null, args) + } + function getDynCaller(sig, ptr) { + var argCache = [] + return function () { + argCache.length = arguments.length + for (var i = 0; i < arguments.length; i++) { + argCache[i] = arguments[i] + } + return dynCall(sig, ptr, argCache) + } + } + function embind__requireFunction(signature, rawFunction) { + signature = readLatin1String(signature) + function makeDynCaller() { + if (signature.includes('j')) { + return getDynCaller(signature, rawFunction) + } + return wasmTable.get(rawFunction) + } + var fp = makeDynCaller() + if (typeof fp !== 'function') { + throwBindingError( + 'unknown function pointer with signature ' + + signature + + ': ' + + rawFunction + ) + } + return fp + } + var UnboundTypeError = undefined + function throwUnboundTypeError(message, types) { + var unboundTypes = [] + var seen = {} + function visit(type) { + if (seen[type]) { + return + } + if (registeredTypes[type]) { + return + } + if (typeDependencies[type]) { + typeDependencies[type].forEach(visit) + return + } + unboundTypes.push(type) + seen[type] = true + } + types.forEach(visit) + throw new UnboundTypeError( + message + ': ' + unboundTypes.map(getTypeName).join([', ']) + ) + } + function __embind_register_function( + name, + argCount, + rawArgTypesAddr, + signature, + rawInvoker, + fn + ) { + var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr) + name = readLatin1String(name) + rawInvoker = embind__requireFunction(signature, rawInvoker) + exposePublicSymbol( + name, + function () { + throwUnboundTypeError( + 'Cannot call ' + name + ' due to unbound types', + argTypes + ) + }, + argCount - 1 + ) + whenDependentTypesAreResolved([], argTypes, function (argTypes) { + var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1)) + replacePublicSymbol( + name, + craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn), + argCount - 1 + ) + return [] + }) + } + function integerReadValueFromPointer(name, shift, signed) { + switch (shift) { + case 0: + return signed + ? function readS8FromPointer(pointer) { + return HEAP8[pointer] + } + : function readU8FromPointer(pointer) { + return HEAPU8[pointer] + } + case 1: + return signed + ? function readS16FromPointer(pointer) { + return HEAP16[pointer >> 1] + } + : function readU16FromPointer(pointer) { + return HEAPU16[pointer >> 1] + } + case 2: + return signed + ? function readS32FromPointer(pointer) { + return HEAP32[pointer >> 2] + } + : function readU32FromPointer(pointer) { + return HEAPU32[pointer >> 2] + } + default: + throw new TypeError('Unknown integer type: ' + name) + } + } + function __embind_register_integer( + primitiveType, + name, + size, + minRange, + maxRange + ) { + name = readLatin1String(name) + if (maxRange === -1) { + maxRange = 4294967295 + } + var shift = getShiftFromSize(size) + var fromWireType = function (value) { + return value + } + if (minRange === 0) { + var bitshift = 32 - 8 * size + fromWireType = function (value) { + return (value << bitshift) >>> bitshift + } + } + var isUnsignedType = name.includes('unsigned') + registerType(primitiveType, { + name: name, + fromWireType: fromWireType, + toWireType: function (destructors, value) { + if (typeof value !== 'number' && typeof value !== 'boolean') { + throw new TypeError( + 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name + ) + } + if (value < minRange || value > maxRange) { + throw new TypeError( + 'Passing a number "' + + _embind_repr(value) + + '" from JS side to C/C++ side to an argument of type "' + + name + + '", which is outside the valid range [' + + minRange + + ', ' + + maxRange + + ']!' + ) + } + return isUnsignedType ? value >>> 0 : value | 0 + }, + argPackAdvance: 8, + readValueFromPointer: integerReadValueFromPointer( + name, + shift, + minRange !== 0 + ), + destructorFunction: null, + }) + } + function __embind_register_memory_view(rawType, dataTypeIndex, name) { + var typeMapping = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + ] + var TA = typeMapping[dataTypeIndex] + function decodeMemoryView(handle) { + handle = handle >> 2 + var heap = HEAPU32 + var size = heap[handle] + var data = heap[handle + 1] + return new TA(buffer, data, size) + } + name = readLatin1String(name) + registerType( + rawType, + { + name: name, + fromWireType: decodeMemoryView, + argPackAdvance: 8, + readValueFromPointer: decodeMemoryView, + }, + { ignoreDuplicateRegistrations: true } + ) + } + function __embind_register_std_string(rawType, name) { + name = readLatin1String(name) + var stdStringIsUTF8 = name === 'std::string' + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var str + if (stdStringIsUTF8) { + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i + if (i == length || HEAPU8[currentBytePtr] == 0) { + var maxRead = currentBytePtr - decodeStartPtr + var stringSegment = UTF8ToString(decodeStartPtr, maxRead) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + 1 + } + } + } else { + var a = new Array(length) + for (var i = 0; i < length; ++i) { + a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) + } + str = a.join('') + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value) + } + var getLength + var valueIsOfTypeString = typeof value === 'string' + if ( + !( + valueIsOfTypeString || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int8Array + ) + ) { + throwBindingError('Cannot pass non-string to std::string') + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + getLength = function () { + return lengthBytesUTF8(value) + } + } else { + getLength = function () { + return value.length + } + } + var length = getLength() + var ptr = _malloc(4 + length + 1) + HEAPU32[ptr >> 2] = length + if (stdStringIsUTF8 && valueIsOfTypeString) { + stringToUTF8(value, ptr + 4, length + 1) + } else { + if (valueIsOfTypeString) { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i) + if (charCode > 255) { + _free(ptr) + throwBindingError( + 'String has UTF-16 code units that do not fit in 8 bits' + ) + } + HEAPU8[ptr + 4 + i] = charCode + } + } else { + for (var i = 0; i < length; ++i) { + HEAPU8[ptr + 4 + i] = value[i] + } + } + } + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_std_wstring(rawType, charSize, name) { + name = readLatin1String(name) + var decodeString, encodeString, getHeap, lengthBytesUTF, shift + if (charSize === 2) { + decodeString = UTF16ToString + encodeString = stringToUTF16 + lengthBytesUTF = lengthBytesUTF16 + getHeap = function () { + return HEAPU16 + } + shift = 1 + } else if (charSize === 4) { + decodeString = UTF32ToString + encodeString = stringToUTF32 + lengthBytesUTF = lengthBytesUTF32 + getHeap = function () { + return HEAPU32 + } + shift = 2 + } + registerType(rawType, { + name: name, + fromWireType: function (value) { + var length = HEAPU32[value >> 2] + var HEAP = getHeap() + var str + var decodeStartPtr = value + 4 + for (var i = 0; i <= length; ++i) { + var currentBytePtr = value + 4 + i * charSize + if (i == length || HEAP[currentBytePtr >> shift] == 0) { + var maxReadBytes = currentBytePtr - decodeStartPtr + var stringSegment = decodeString(decodeStartPtr, maxReadBytes) + if (str === undefined) { + str = stringSegment + } else { + str += String.fromCharCode(0) + str += stringSegment + } + decodeStartPtr = currentBytePtr + charSize + } + } + _free(value) + return str + }, + toWireType: function (destructors, value) { + if (!(typeof value === 'string')) { + throwBindingError( + 'Cannot pass non-string to C++ string type ' + name + ) + } + var length = lengthBytesUTF(value) + var ptr = _malloc(4 + length + charSize) + HEAPU32[ptr >> 2] = length >> shift + encodeString(value, ptr + 4, length + charSize) + if (destructors !== null) { + destructors.push(_free, ptr) + } + return ptr + }, + argPackAdvance: 8, + readValueFromPointer: simpleReadValueFromPointer, + destructorFunction: function (ptr) { + _free(ptr) + }, + }) + } + function __embind_register_value_object( + rawType, + name, + constructorSignature, + rawConstructor, + destructorSignature, + rawDestructor + ) { + structRegistrations[rawType] = { + name: readLatin1String(name), + rawConstructor: embind__requireFunction( + constructorSignature, + rawConstructor + ), + rawDestructor: embind__requireFunction( + destructorSignature, + rawDestructor + ), + fields: [], + } + } + function __embind_register_value_object_field( + structType, + fieldName, + getterReturnType, + getterSignature, + getter, + getterContext, + setterArgumentType, + setterSignature, + setter, + setterContext + ) { + structRegistrations[structType].fields.push({ + fieldName: readLatin1String(fieldName), + getterReturnType: getterReturnType, + getter: embind__requireFunction(getterSignature, getter), + getterContext: getterContext, + setterArgumentType: setterArgumentType, + setter: embind__requireFunction(setterSignature, setter), + setterContext: setterContext, + }) + } + function __embind_register_void(rawType, name) { + name = readLatin1String(name) + registerType(rawType, { + isVoid: true, + name: name, + argPackAdvance: 0, + fromWireType: function () { + return undefined + }, + toWireType: function (destructors, o) { + return undefined + }, + }) + } + var emval_symbols = {} + function getStringOrSymbol(address) { + var symbol = emval_symbols[address] + if (symbol === undefined) { + return readLatin1String(address) + } else { + return symbol + } + } + function emval_get_global() { + if (typeof globalThis === 'object') { + return globalThis + } + return (function () { + return Function + })()('return this')() + } + function __emval_get_global(name) { + if (name === 0) { + return __emval_register(emval_get_global()) + } else { + name = getStringOrSymbol(name) + return __emval_register(emval_get_global()[name]) + } + } + function __emval_incref(handle) { + if (handle > 4) { + emval_handle_array[handle].refcount += 1 + } + } + function craftEmvalAllocator(argCount) { + var argsList = '' + for (var i = 0; i < argCount; ++i) { + argsList += (i !== 0 ? ', ' : '') + 'arg' + i + } + var functionBody = + 'return function emval_allocator_' + + argCount + + '(constructor, argTypes, args) {\n' + for (var i = 0; i < argCount; ++i) { + functionBody += + 'var argType' + + i + + " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " + + i + + '], "parameter ' + + i + + '");\n' + + 'var arg' + + i + + ' = argType' + + i + + '.readValueFromPointer(args);\n' + + 'args += argType' + + i + + "['argPackAdvance'];\n" + } + functionBody += + 'var obj = new constructor(' + + argsList + + ');\n' + + 'return __emval_register(obj);\n' + + '}\n' + return new Function( + 'requireRegisteredType', + 'Module', + '__emval_register', + functionBody + )(requireRegisteredType, Module, __emval_register) + } + var emval_newers = {} + function requireHandle(handle) { + if (!handle) { + throwBindingError('Cannot use deleted val. handle = ' + handle) + } + return emval_handle_array[handle].value + } + function __emval_new(handle, argCount, argTypes, args) { + handle = requireHandle(handle) + var newer = emval_newers[argCount] + if (!newer) { + newer = craftEmvalAllocator(argCount) + emval_newers[argCount] = newer + } + return newer(handle, argTypes, args) + } + function _abort() { + abort() + } + function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.copyWithin(dest, src, src + num) + } + function emscripten_realloc_buffer(size) { + try { + wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16) + updateGlobalBufferAndViews(wasmMemory.buffer) + return 1 + } catch (e) {} + } + function _emscripten_resize_heap(requestedSize) { + var oldSize = HEAPU8.length + requestedSize = requestedSize >>> 0 + var maxHeapSize = 2147483648 + if (requestedSize > maxHeapSize) { + return false + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown) + overGrownHeapSize = Math.min( + overGrownHeapSize, + requestedSize + 100663296 + ) + var newSize = Math.min( + maxHeapSize, + alignUp(Math.max(requestedSize, overGrownHeapSize), 65536) + ) + var replacement = emscripten_realloc_buffer(newSize) + if (replacement) { + return true + } + } + return false + } + InternalError = Module['InternalError'] = extendError( + Error, + 'InternalError' + ) + embind_init_charCodes() + BindingError = Module['BindingError'] = extendError(Error, 'BindingError') + init_emval() + UnboundTypeError = Module['UnboundTypeError'] = extendError( + Error, + 'UnboundTypeError' + ) + var asmLibraryArg = { + w: ___cxa_thread_atexit, + l: __embind_finalize_value_object, + p: __embind_register_bigint, + s: __embind_register_bool, + r: __embind_register_emval, + n: __embind_register_enum, + d: __embind_register_enum_value, + j: __embind_register_float, + h: __embind_register_function, + c: __embind_register_integer, + b: __embind_register_memory_view, + k: __embind_register_std_string, + g: __embind_register_std_wstring, + m: __embind_register_value_object, + a: __embind_register_value_object_field, + t: __embind_register_void, + f: __emval_decref, + v: __emval_get_global, + u: __emval_incref, + o: __emval_new, + i: _abort, + q: _emscripten_memcpy_big, + e: _emscripten_resize_heap, + } + var asm = createWasm() + var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () { + return (___wasm_call_ctors = Module['___wasm_call_ctors'] = + Module['asm']['y']).apply(null, arguments) + }) + var _malloc = (Module['_malloc'] = function () { + return (_malloc = Module['_malloc'] = Module['asm']['z']).apply( + null, + arguments + ) + }) + var _free = (Module['_free'] = function () { + return (_free = Module['_free'] = Module['asm']['A']).apply( + null, + arguments + ) + }) + var ___getTypeName = (Module['___getTypeName'] = function () { + return (___getTypeName = Module['___getTypeName'] = + Module['asm']['B']).apply(null, arguments) + }) + var ___embind_register_native_and_builtin_types = (Module[ + '___embind_register_native_and_builtin_types' + ] = function () { + return (___embind_register_native_and_builtin_types = Module[ + '___embind_register_native_and_builtin_types' + ] = + Module['asm']['C']).apply(null, arguments) + }) + var calledRun + dependenciesFulfilled = function runCaller() { + if (!calledRun) run() + if (!calledRun) dependenciesFulfilled = runCaller + } + function run(args) { + args = args || arguments_ + if (runDependencies > 0) { + return + } + preRun() + if (runDependencies > 0) { + return + } + function doRun() { + if (calledRun) return + calledRun = true + Module['calledRun'] = true + if (ABORT) return + initRuntime() + readyPromiseResolve(Module) + if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']() + postRun() + } + if (Module['setStatus']) { + Module['setStatus']('Running...') + setTimeout(function () { + setTimeout(function () { + Module['setStatus']('') + }, 1) + doRun() + }, 1) + } else { + doRun() + } + } + Module['run'] = run + if (Module['preInit']) { + if (typeof Module['preInit'] == 'function') + Module['preInit'] = [Module['preInit']] + while (Module['preInit'].length > 0) { + Module['preInit'].pop()() + } + } + run() + + return Module.ready + } +})() +export default Module diff --git a/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_enc.wasm b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_enc.wasm new file mode 100644 index 000000000000..7621054164f6 Binary files /dev/null and b/packages/astro/src/assets/services/vendor/squoosh/webp/webp_node_enc.wasm differ diff --git a/packages/astro/src/assets/types.ts b/packages/astro/src/assets/types.ts new file mode 100644 index 000000000000..f3f54b2dd09f --- /dev/null +++ b/packages/astro/src/assets/types.ts @@ -0,0 +1,125 @@ +/* eslint-disable @typescript-eslint/ban-types */ +import { VALID_INPUT_FORMATS, VALID_OUTPUT_FORMATS } from './consts.js'; +import { ImageService } from './services/service.js'; + +export type ImageQualityPreset = 'low' | 'mid' | 'high' | 'max' | (string & {}); +export type ImageQuality = ImageQualityPreset | number; +export type InputFormat = (typeof VALID_INPUT_FORMATS)[number] | (string & {}); +export type OutputFormat = (typeof VALID_OUTPUT_FORMATS)[number] | (string & {}); + +declare global { + // eslint-disable-next-line no-var + var astroAsset: { + imageService?: ImageService; + addStaticImage?: ((options: ImageTransform) => string) | undefined; + staticImages?: Map; + }; +} + +/** + * Type returned by ESM imports of images and direct calls to imageMetadata + */ +export interface ImageMetadata { + src: string; + width: number; + height: number; + format: InputFormat; +} + +/** + * Options accepted by the image transformation service. + */ +export type ImageTransform = { + src: ImageMetadata | string; + width?: number; + height?: number; + quality?: ImageQuality; + format?: OutputFormat; + [key: string]: any; +}; + +type WithRequired = T & { [P in K]-?: T[P] }; +type ImageSharedProps = T & { + /** + * Width of the image, the value of this property will be used to assign the `width` property on the final `img` element. + * + * For local images, this value will additionally be used to resize the image to the desired width, taking into account the original aspect ratio of the image. + * + * **Example**: + * ```astro + * ... + * ``` + * **Result**: + * ```html + * ... + * ``` + */ + width?: number | `${number}`; + /** + * Height of the image, the value of this property will be used to assign the `height` property on the final `img` element. + * + * For local images, if `width` is not present, this value will additionally be used to resize the image to the desired height, taking into account the original aspect ratio of the image. + * + * **Example**: + * ```astro + * ... + * ``` + * **Result**: + * ```html + * ... + * ``` + */ + height?: number | `${number}`; +}; + +export type LocalImageProps = ImageSharedProps & { + /** + * A reference to a local image imported through an ESM import. + * + * **Example**: + * ```js + * import myImage from "~/assets/my_image.png"; + * ``` + * And then refer to the image, like so: + * ```astro + * ... + * ``` + */ + src: ImageMetadata; + /** + * Desired output format for the image. Defaults to `webp`. + * + * **Example**: + * ```astro + * ... + * ``` + */ + format?: OutputFormat; + /** + * Desired quality for the image. Value can either be a preset such as `low` or `high`, or a numeric value from 0 to 100. + * + * The perceptual quality of the output image is loader-specific. + * For instance, a certain service might decide that `high` results in a very beautiful image, but another could choose for it to be at best passable. + * + * **Example**: + * ```astro + * ... + * ... + * ``` + */ + quality?: ImageQuality; +}; + +export type RemoteImageProps = WithRequired, 'width' | 'height'> & { + /** + * URL of a remote image. Can start with a protocol (ex: `https://`) or alternatively `/`, or `Astro.url`, for images in the `public` folder + * + * Remote images are not optimized, and require both `width` and `height` to be set. + * + * **Example**: + * ``` + * ... + * ``` + */ + src: string; +}; diff --git a/packages/astro/src/assets/utils/etag.ts b/packages/astro/src/assets/utils/etag.ts new file mode 100644 index 000000000000..78d208b908f7 --- /dev/null +++ b/packages/astro/src/assets/utils/etag.ts @@ -0,0 +1,45 @@ +/** + * FNV-1a Hash implementation + * @author Travis Webb (tjwebb) + * + * Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js + * License https://github.com/tjwebb/fnv-plus#license + * + * 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: string) => { + 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 etag = (payload: string, weak = false) => { + const prefix = weak ? 'W/"' : '"'; + return prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '"'; +}; diff --git a/packages/astro/src/assets/utils/metadata.ts b/packages/astro/src/assets/utils/metadata.ts new file mode 100644 index 000000000000..d1bc37bad205 --- /dev/null +++ b/packages/astro/src/assets/utils/metadata.ts @@ -0,0 +1,39 @@ +import { createRequire } from 'module'; +import fs from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import { ImageMetadata, InputFormat } from '../types.js'; +const require = createRequire(import.meta.url); +const sizeOf = require('image-size'); + +export interface Metadata extends ImageMetadata { + orientation?: number; +} + +export async function imageMetadata( + src: URL | string, + data?: Buffer +): Promise { + let file = data; + if (!file) { + try { + file = await fs.readFile(src); + } catch (e) { + return undefined; + } + } + + const { width, height, type, orientation } = await sizeOf(file); + const isPortrait = (orientation || 0) >= 5; + + if (!width || !height || !type) { + return undefined; + } + + return { + src: fileURLToPath(src), + width: isPortrait ? height : width, + height: isPortrait ? width : height, + format: type as InputFormat, + orientation, + }; +} diff --git a/packages/astro/src/assets/utils/queryParams.ts b/packages/astro/src/assets/utils/queryParams.ts new file mode 100644 index 000000000000..e2753201ea37 --- /dev/null +++ b/packages/astro/src/assets/utils/queryParams.ts @@ -0,0 +1,19 @@ +import { ImageMetadata, InputFormat } from '../types.js'; + +export function getOrigQueryParams( + params: URLSearchParams +): Omit | undefined { + const width = params.get('origWidth'); + const height = params.get('origHeight'); + const format = params.get('origFormat'); + + if (!width || !height || !format) { + return undefined; + } + + return { + width: parseInt(width), + height: parseInt(height), + format: format as InputFormat, + }; +} diff --git a/packages/astro/src/assets/utils/transformToPath.ts b/packages/astro/src/assets/utils/transformToPath.ts new file mode 100644 index 000000000000..925407eb1004 --- /dev/null +++ b/packages/astro/src/assets/utils/transformToPath.ts @@ -0,0 +1,17 @@ +import { basename, extname } from 'path'; +import { removeQueryString } from '../../core/path.js'; +import { shorthash } from '../../runtime/server/shorthash.js'; +import { isESMImportedImage } from '../internal.js'; +import { ImageTransform } from '../types.js'; + +export function propsToFilename(transform: ImageTransform) { + if (!isESMImportedImage(transform.src)) { + return transform.src; + } + + let filename = removeQueryString(transform.src.src); + const ext = extname(filename); + filename = basename(filename, ext); + const outputExt = transform.format ? `.${transform.format}` : ext; + return `/${filename}_${shorthash(JSON.stringify(transform))}${outputExt}`; +} diff --git a/packages/astro/src/assets/vite-plugin-assets.ts b/packages/astro/src/assets/vite-plugin-assets.ts new file mode 100644 index 000000000000..4fc8e95983df --- /dev/null +++ b/packages/astro/src/assets/vite-plugin-assets.ts @@ -0,0 +1,234 @@ +import MagicString from 'magic-string'; +import mime from 'mime'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { Readable } from 'node:stream'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import type * as vite from 'vite'; +import { normalizePath } from 'vite'; +import { AstroPluginOptions, ImageTransform } from '../@types/astro'; +import { error } from '../core/logger/core.js'; +import { joinPaths, prependForwardSlash } from '../core/path.js'; +import { VIRTUAL_MODULE_ID, VIRTUAL_SERVICE_ID } from './consts.js'; +import { isESMImportedImage } from './internal.js'; +import { isLocalService } from './services/service.js'; +import { copyWasmFiles } from './services/vendor/squoosh/copy-wasm.js'; +import { imageMetadata } from './utils/metadata.js'; +import { getOrigQueryParams } from './utils/queryParams.js'; +import { propsToFilename } from './utils/transformToPath.js'; + +const resolvedVirtualModuleId = '\0' + VIRTUAL_MODULE_ID; + +export default function assets({ + settings, + logging, + mode, +}: AstroPluginOptions & { mode: string }): vite.Plugin[] { + let resolvedConfig: vite.ResolvedConfig; + + globalThis.astroAsset = {}; + + return [ + // Expose the components and different utilities from `astro:assets` and handle serving images from `/_image` in dev + { + name: 'astro:assets', + config() { + return { + resolve: { + alias: [ + { + find: /^~\/assets\/(.+)$/, + replacement: fileURLToPath(new URL('./assets/$1', settings.config.srcDir)), + }, + ], + }, + }; + }, + async resolveId(id) { + if (id === VIRTUAL_SERVICE_ID) { + return await this.resolve(settings.config.image.service); + } + if (id === VIRTUAL_MODULE_ID) { + return resolvedVirtualModuleId; + } + }, + load(id) { + if (id === resolvedVirtualModuleId) { + return ` + export { getImage, getConfiguredImageService } from "astro/assets"; + export { default as Image } from "astro/components/Image.astro"; + `; + } + }, + // Handle serving images during development + configureServer(server) { + server.middlewares.use(async (req, res, next) => { + if (req.url?.startsWith('/_image')) { + // If the currently configured service isn't a local service, we don't need to do anything here. + // TODO: Support setting a specific service through a prop on Image / a parameter in getImage + if (!isLocalService(globalThis.astroAsset.imageService)) { + return next(); + } + + const url = new URL(req.url, 'file:'); + const filePath = url.searchParams.get('href'); + + if (!filePath) { + return next(); + } + + const filePathURL = new URL(filePath, 'file:'); + const file = await fs.readFile(filePathURL.pathname); + + // Get the file's metadata from the URL + let meta = getOrigQueryParams(filePathURL.searchParams); + + // If we don't have them (ex: the image came from Markdown, let's calculate them again) + if (!meta) { + meta = await imageMetadata(filePathURL, file); + + if (!meta) { + return next(); + } + } + + const transform = await globalThis.astroAsset.imageService.parseURL(url); + + if (transform === undefined) { + error(logging, 'image', `Failed to parse transform for ${url}`); + } + + // if no transforms were added, the original file will be returned as-is + let data = file; + let format = meta.format; + + if (transform) { + const result = await globalThis.astroAsset.imageService.transform(file, transform); + data = result.data; + format = result.format; + } + + res.setHeader('Content-Type', mime.getType(fileURLToPath(url)) || `image/${format}`); + res.setHeader('Cache-Control', 'max-age=360000'); + + const stream = Readable.from(data); + return stream.pipe(res); + } + + return next(); + }); + }, + buildStart() { + if (mode != 'build') { + return; + } + + globalThis.astroAsset.addStaticImage = (options) => { + if (!globalThis.astroAsset.staticImages) { + globalThis.astroAsset.staticImages = new Map(); + } + + let filePath: string; + if (globalThis.astroAsset.staticImages.has(options)) { + filePath = globalThis.astroAsset.staticImages.get(options)!; + } else { + // If the image is not imported, we can return the path as-is, since static references + // should only point ot valid paths for builds or remote images + if (!isESMImportedImage(options.src)) { + return options.src; + } + + filePath = prependForwardSlash( + joinPaths( + settings.config.base, + settings.config.build.assets, + propsToFilename(options) + ) + ); + globalThis.astroAsset.staticImages.set(options, filePath); + } + + return filePath; + }; + }, + async buildEnd() { + if (mode != 'build') { + return; + } + + const dir = + settings.config.output === 'server' + ? settings.config.build.server + : settings.config.outDir; + + await copyWasmFiles(new URL('./chunks', dir)); + }, + // In build, rewrite paths to ESM imported images in code to their final location + async renderChunk(code) { + const assetUrlRE = /__ASTRO_ASSET_IMAGE__([a-z\d]{8})__(?:_(.*?)__)?/g; + + let match; + let s; + while ((match = assetUrlRE.exec(code))) { + s = s || (s = new MagicString(code)); + const [full, hash, postfix = ''] = match; + + const file = this.getFileName(hash); + const outputFilepath = normalizePath(resolvedConfig.base + file + postfix); + + s.overwrite(match.index, match.index + full.length, outputFilepath); + } + + if (s) { + return { + code: s.toString(), + map: resolvedConfig.build.sourcemap ? s.generateMap({ hires: true }) : null, + }; + } else { + return null; + } + }, + }, + // Return a more advanced shape for images imported in ESM + { + name: 'astro:assets:esm', + enforce: 'pre', + configResolved(viteConfig) { + resolvedConfig = viteConfig; + }, + async load(id) { + if (/\.(heic|heif|avif|jpeg|jpg|png|tiff|webp|gif)$/.test(id)) { + const url = pathToFileURL(id); + const meta = await imageMetadata(url); + + if (!meta) { + return; + } + + // Build + if (!this.meta.watchMode) { + const pathname = decodeURI(url.pathname); + const filename = path.basename(pathname, path.extname(pathname) + `.${meta.format}`); + + const handle = this.emitFile({ + name: filename, + source: await fs.readFile(url), + type: 'asset', + }); + + meta.src = `__ASTRO_ASSET_IMAGE__${handle}__`; + } else { + // Pass the original file information through query params so we don't have to load the file twice + url.searchParams.append('origWidth', meta.width.toString()); + url.searchParams.append('origHeight', meta.height.toString()); + url.searchParams.append('origFormat', meta.format); + + meta.src = url.toString(); + } + + return `export default ${JSON.stringify(meta)}`; + } + }, + }, + ]; +} diff --git a/packages/astro/src/content/internal.ts b/packages/astro/src/content/internal.ts index 848e0039974c..36560d33bc79 100644 --- a/packages/astro/src/content/internal.ts +++ b/packages/astro/src/content/internal.ts @@ -1,3 +1,5 @@ +import { z } from 'zod'; +import { imageMetadata, type Metadata } from '../assets/utils/metadata.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { prependForwardSlash } from '../core/path.js'; @@ -188,3 +190,29 @@ async function render({ remarkPluginFrontmatter: mod.frontmatter, }; } + +export function createImage(options: { assetsDir: string }) { + return () => { + if (options.assetsDir === 'undefined') { + throw new Error('Enable `experimental.assets` in your Astro config to use image()'); + } + + return z.string().transform(async (imagePath) => { + const fullPath = new URL(imagePath, options.assetsDir); + return await getImageMetadata(fullPath); + }); + }; +} + +async function getImageMetadata( + imagePath: URL +): Promise<(Metadata & { __astro_asset: true }) | undefined> { + const meta = await imageMetadata(imagePath); + + if (!meta) { + return undefined; + } + + delete meta.orientation; + return { ...meta, __astro_asset: true }; +} diff --git a/packages/astro/src/content/template/types.d.ts b/packages/astro/src/content/template/types.d.ts index f14a541f1e8a..83c805c4e199 100644 --- a/packages/astro/src/content/template/types.d.ts +++ b/packages/astro/src/content/template/types.d.ts @@ -3,6 +3,13 @@ declare module 'astro:content' { export type CollectionEntry = (typeof entryMap)[C][keyof (typeof entryMap)[C]] & Render; + export const image: () => import('astro/zod').ZodObject<{ + src: import('astro/zod').ZodString; + width: import('astro/zod').ZodNumber; + height: import('astro/zod').ZodNumber; + format: import('astro/zod').ZodString; + }>; + type BaseSchemaWithoutEffects = | import('astro/zod').AnyZodObject | import('astro/zod').ZodUnion diff --git a/packages/astro/src/content/template/virtual-mod.mjs b/packages/astro/src/content/template/virtual-mod.mjs index ed4359510c2f..5ce29dcf8fcc 100644 --- a/packages/astro/src/content/template/virtual-mod.mjs +++ b/packages/astro/src/content/template/virtual-mod.mjs @@ -3,6 +3,7 @@ import { createCollectionToGlobResultMap, createGetCollection, createGetEntryBySlug, + createImage, } from 'astro/content/internal'; export { z } from 'astro/zod'; @@ -12,6 +13,7 @@ export function defineCollection(config) { } const contentDir = '@@CONTENT_DIR@@'; +const assetsDir = '@@ASSETS_DIR@@'; const entryGlob = import.meta.glob('@@ENTRY_GLOB_PATH@@', { query: { astroContent: true }, @@ -38,3 +40,7 @@ export const getEntryBySlug = createGetEntryBySlug({ getCollection, collectionToRenderEntryMap, }); + +export const image = createImage({ + assetsDir, +}); diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index afe15eeb0077..09edc2165385 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -6,6 +6,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { ErrorPayload as ViteErrorPayload, normalizePath, ViteDevServer } from 'vite'; import { z } from 'zod'; import { AstroConfig, AstroSettings } from '../@types/astro.js'; +import type { ImageMetadata } from '../assets/types.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { contentFileExts, CONTENT_TYPES_FILE } from './consts.js'; @@ -49,6 +50,23 @@ export const msg = { `${collection} does not have a config. We suggest adding one for type safety!`, }; +export function extractFrontmatterAssets(data: Record): string[] { + function findAssets(potentialAssets: Record): ImageMetadata[] { + return Object.values(potentialAssets).reduce((acc, curr) => { + if (typeof curr === 'object') { + if (curr.__astro === true) { + acc.push(curr); + } else { + acc.push(...findAssets(curr)); + } + } + return acc; + }, []); + } + + return findAssets(data).map((asset) => asset.src); +} + export function getEntrySlug({ id, collection, @@ -313,6 +331,7 @@ export function contentObservable(initialCtx: ContentCtx): ContentObservable { export type ContentPaths = { contentDir: URL; + assetsDir: URL; cacheDir: URL; typesTemplate: URL; virtualModTemplate: URL; @@ -331,6 +350,7 @@ export function getContentPaths( return { cacheDir: new URL('.astro/', root), contentDir: new URL('./content/', srcDir), + assetsDir: new URL('./assets/', srcDir), typesTemplate: new URL('types.d.ts', templateDir), virtualModTemplate: new URL('virtual-mod.mjs', templateDir), config: configStats, diff --git a/packages/astro/src/content/vite-plugin-content-imports.ts b/packages/astro/src/content/vite-plugin-content-imports.ts index d8075a1a1259..cd3c11214d6f 100644 --- a/packages/astro/src/content/vite-plugin-content-imports.ts +++ b/packages/astro/src/content/vite-plugin-content-imports.ts @@ -2,6 +2,7 @@ import * as devalue from 'devalue'; import type fsMod from 'node:fs'; import { pathToFileURL } from 'url'; import type { Plugin } from 'vite'; +import { normalizePath } from 'vite'; import { AstroSettings } from '../@types/astro.js'; import { AstroErrorData } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/errors.js'; @@ -9,6 +10,7 @@ import { escapeViteEnvReferences, getFileInfo } from '../vite-plugin-utils/index import { contentFileExts, CONTENT_FLAG } from './consts.js'; import { ContentConfig, + extractFrontmatterAssets, getContentPaths, getEntryData, getEntryInfo, @@ -91,11 +93,18 @@ export function astroContentImportPlugin({ ? await getEntryData(partialEntry, collectionConfig) : unparsedData; + const images = extractFrontmatterAssets(data).map( + (image) => `'${image}': await import('${normalizePath(image)}'),` + ); + const code = escapeViteEnvReferences(` export const id = ${JSON.stringify(entryInfo.id)}; export const collection = ${JSON.stringify(entryInfo.collection)}; export const slug = ${JSON.stringify(slug)}; export const body = ${JSON.stringify(body)}; +const frontmatterImages = { + ${images.join('\n')} +} export const data = ${devalue.uneval(data) /* TODO: reuse astro props serializer */}; export const _internal = { filePath: ${JSON.stringify(fileId)}, diff --git a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts index 120083ebfc37..32214ac2757f 100644 --- a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts +++ b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts @@ -22,10 +22,15 @@ export function astroContentVirtualModPlugin({ ) ) ); + + const assetsDir = settings.config.experimental.assets + ? contentPaths.assetsDir.toString() + : 'undefined'; const entryGlob = `${relContentDir}**/*{${contentFileExts.join(',')}}`; const virtualModContents = fsMod .readFileSync(contentPaths.virtualModTemplate, 'utf-8') .replace('@@CONTENT_DIR@@', relContentDir) + .replace('@@ASSETS_DIR@@', assetsDir) .replace('@@ENTRY_GLOB_PATH@@', entryGlob) .replace('@@RENDER_ENTRY_GLOB_PATH@@', entryGlob); diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index 7ae4de6a1e23..8f22d769cb8e 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -9,11 +9,15 @@ import type { AstroSettings, ComponentInstance, EndpointHandler, + ImageTransform, RouteType, SSRError, SSRLoadedRenderer, } from '../../@types/astro'; -import { getContentPaths } from '../../content/index.js'; +import { + generateImage as generateImageInternal, + getStaticImageList, +} from '../../assets/internal.js'; import { BuildInternals, hasPrerenderedPages } from '../../core/build/internal.js'; import { prependForwardSlash, @@ -101,6 +105,14 @@ export async function generatePages(opts: StaticBuildOptions, internals: BuildIn } } + if (opts.settings.config.experimental.assets) { + info(opts.logging, null, `\n${bgGreen(black(` generating optimized images `))}`); + for (const imageData of getStaticImageList()) { + await generateImage(opts, imageData[0], imageData[1]); + } + delete globalThis.astroAsset.addStaticImage; + } + await runHookBuildGenerated({ config: opts.settings.config, buildConfig: opts.buildConfig, @@ -110,6 +122,26 @@ export async function generatePages(opts: StaticBuildOptions, internals: BuildIn info(opts.logging, null, dim(`Completed in ${getTimeStat(timer, performance.now())}.\n`)); } +async function generateImage(opts: StaticBuildOptions, transform: ImageTransform, path: string) { + let timeStart = performance.now(); + const generationData = await generateImageInternal(opts, transform, path); + + if (!generationData) { + return; + } + + const timeEnd = performance.now(); + const timeChange = getTimeStat(timeStart, timeEnd); + const timeIncrease = `(+${timeChange})`; + info( + opts.logging, + null, + ` ${green('▶')} ${path} ${dim( + `(before: ${generationData.weight.before}kb, after: ${generationData.weight.after}kb)` + )} ${dim(timeIncrease)}` + ); +} + async function generatePage( opts: StaticBuildOptions, internals: BuildInternals, @@ -347,10 +379,7 @@ async function generatePath( const env = createEnvironment({ adapterName: undefined, logging, - markdown: { - ...settings.config.markdown, - contentDir: getContentPaths(settings.config).contentDir, - }, + markdown: settings.config.markdown, mode: opts.mode, renderers, async resolve(specifier: string) { diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index d4536b92c8ab..a49544659adb 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -6,7 +6,6 @@ import type { StaticBuildOptions } from '../types'; import glob from 'fast-glob'; import { fileURLToPath } from 'url'; -import { getContentPaths } from '../../../content/index.js'; import { runHookBuildSsr } from '../../../integrations/index.js'; import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../../vite-plugin-scripts/index.js'; import { pagesVirtualModuleId } from '../../app/index.js'; @@ -206,10 +205,7 @@ function buildManifest( routes, site: settings.config.site, base: settings.config.base, - markdown: { - ...settings.config.markdown, - contentDir: getContentPaths(settings.config).contentDir, - }, + markdown: settings.config.markdown, pageMap: null as any, propagation: Array.from(internals.propagation), renderers: [], diff --git a/packages/astro/src/core/config/config.ts b/packages/astro/src/core/config/config.ts index 394a968db16b..19583bddeae4 100644 --- a/packages/astro/src/core/config/config.ts +++ b/packages/astro/src/core/config/config.ts @@ -100,6 +100,8 @@ export function resolveFlags(flags: Partial): CLIFlags { host: typeof flags.host === 'string' || typeof flags.host === 'boolean' ? flags.host : undefined, drafts: typeof flags.drafts === 'boolean' ? flags.drafts : undefined, + experimentalAssets: + typeof flags.experimentalAssets === 'boolean' ? flags.experimentalAssets : undefined, }; } diff --git a/packages/astro/src/core/config/schema.ts b/packages/astro/src/core/config/schema.ts index 69380ee77e0c..89bdd2ccaf44 100644 --- a/packages/astro/src/core/config/schema.ts +++ b/packages/astro/src/core/config/schema.ts @@ -34,6 +34,9 @@ const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = { }, vite: {}, legacy: {}, + experimental: { + assets: false, + }, }; export const AstroConfigSchema = z.object({ @@ -115,6 +118,17 @@ export const AstroConfigSchema = z.object({ .optional() .default({}) ), + image: z + .object({ + service: z.union([ + z.literal('astro/assets/services/sharp'), + z.literal('astro/assets/services/squoosh'), + z.string().and(z.object({})), + ]), + }) + .default({ + service: 'astro/assets/services/squoosh', + }), markdown: z .object({ drafts: z.boolean().default(false), @@ -160,7 +174,12 @@ export const AstroConfigSchema = z.object({ vite: z .custom((data) => data instanceof Object && !Array.isArray(data)) .default(ASTRO_CONFIG_DEFAULTS.vite), - experimental: z.object({}).optional().default({}), + experimental: z + .object({ + assets: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.assets), + }) + .optional() + .default({}), legacy: z.object({}).optional().default({}), }); @@ -256,7 +275,7 @@ export function createRelativeSchema(cmd: string, fileProtocolRoot: URL) { config.base = sitePathname; /* eslint-disable no-console */ console.warn(`The site configuration value includes a pathname of ${sitePathname} but there is no base configuration. - + A future version of Astro will stop using the site pathname when producing and