🎉 initiate project *astro_rewrite*

This commit is contained in:
sindrekjelsrud 2023-07-19 21:31:30 +02:00
parent ffd4d5e86c
commit 2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions

61
node_modules/astro/LICENSE generated vendored Normal file
View file

@ -0,0 +1,61 @@
MIT License
Copyright (c) 2021 Fred K. Schott
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
"""
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

43
node_modules/astro/README.md generated vendored Normal file
View file

@ -0,0 +1,43 @@
<br/>
<p align="center">
<img src="../../.github/assets/banner.png" alt="Build the web you want">
<br/><br/>
<a href="https://astro.build">Astro</a> is the all-in-one web framework designed for speed.
<br/>
Pull your content from anywhere and deploy everywhere, all powered by your favorite UI components and libraries.
<br/><br/>
</p>
## Install
```bash
# Recommended!
npm create astro@latest
# Manual:
npm install --save-dev astro
```
Looking for help? Start with our [Getting Started](https://docs.astro.build/en/getting-started/) guide.
Looking for quick examples? [Open a starter project](https://astro.new/) right in your browser.
## Documentation
Visit our [official documentation](https://docs.astro.build/).
## Support
Having trouble? Get help in the official [Astro Discord](https://astro.build/chat).
## Contributing
**New contributors welcome!** Check out our [Contributors Guide](/CONTRIBUTING.md) for help getting started.
Join us on [Discord](https://astro.build/chat) to meet other maintainers. We'll help you get your first contribution in no time!
## Sponsors
Astro is generously supported by [Netlify](https://www.netlify.com/), [Vercel](https://vercel.com/), and several other amazing organizations [listed here.](https://astro.build/)
[❤️ Sponsor Astro! ❤️](https://github.com/withastro/.github/blob/main/FUNDING.md)

1478
node_modules/astro/astro-jsx.d.ts generated vendored Normal file

File diff suppressed because it is too large Load diff

76
node_modules/astro/astro.js generated vendored Executable file
View file

@ -0,0 +1,76 @@
#!/usr/bin/env node
'use strict';
// ISOMORPHIC FILE: NO TOP-LEVEL IMPORT/REQUIRE() ALLOWED
// This file has to run as both ESM and CJS on older Node.js versions
// Needed for Stackblitz: https://github.com/stackblitz/webcontainer-core/issues/281
const CI_INSTRUCTIONS = {
NETLIFY: 'https://docs.netlify.com/configure-builds/manage-dependencies/#node-js-and-javascript',
GITHUB_ACTIONS:
'https://docs.github.com/en/actions/guides/building-and-testing-nodejs#specifying-the-nodejs-version',
VERCEL: 'https://vercel.com/docs/runtimes#official-runtimes/node-js/node-js-version',
};
// Hardcode supported Node.js version so we don't have to read differently in CJS & ESM.
const engines = '>=16.12.0';
const skipSemverCheckIfAbove = 16;
/** `astro *` */
async function main() {
const version = process.versions.node;
// Fast-path for higher Node.js versions
if ((parseInt(version) || 0) <= skipSemverCheckIfAbove) {
try {
const semver = await import('semver');
if (!semver.satisfies(version, engines)) {
await errorNodeUnsupported();
return;
}
} catch {
await errorNodeUnsupported();
return;
}
}
return import('./dist/cli/index.js')
.then(({ cli }) => cli(process.argv))
.catch((error) => {
console.error(error);
process.exit(1);
});
}
async function errorNodeUnsupported() {
console.error(`\
Node.js v${process.versions.node} is not supported by Astro!
Please upgrade Node.js to a supported version: "${engines}"\n`);
const ci = typeof require !== 'undefined' ? require('ci-info') : await import('ci-info');
// Special instructions for CI environments, which may have special steps needed.
// This is a common issue that we can help users with proactively.
if (ci.isCI) {
let platform;
for (const [key, value] of Object.entries(ci)) {
if (value === true) {
platform = key;
break;
}
}
console.log(
`${ci.name} CI Environment Detected!\nAdditional steps may be needed to set your Node.js version:`
);
console.log(`Documentation: https://docs.astro.build/guides/deploy`);
if (CI_INSTRUCTIONS[platform]) {
console.log(`${ci.name} Documentation: ${CI_INSTRUCTIONS[platform]}`);
}
console.log(``);
}
process.exit(1);
}
main()
.then(() => process.exit(0))
.catch(() => process.exit(1));

416
node_modules/astro/client-base.d.ts generated vendored Normal file
View file

@ -0,0 +1,416 @@
/// <reference path="./import-meta.d.ts" />
// eslint-disable-next-line @typescript-eslint/no-namespace
declare namespace App {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Locals {}
}
interface ImportMetaEnv {
/**
* The prefix for Astro-generated asset links if the build.assetsPrefix config option is set. This can be used to create asset links not handled by Astro.
*/
readonly ASSETS_PREFIX: string;
/**
* This is set to the site option specified in your projects Astro config file.
*/
readonly SITE: string;
}
interface ImportMeta {
/**
* Astro and Vite expose environment variables through `import.meta.env`. For a complete list of the environment variables available, see the two references below.
*
* - [Astro reference](https://docs.astro.build/en/guides/environment-variables/#default-environment-variables)
* - [Vite reference](https://vitejs.dev/guide/env-and-mode.html#env-variables)
*/
readonly env: ImportMetaEnv;
}
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's type here is different from the internal function since the Vite module implicitly pass the service config
/**
* 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 });
* ---
* <img src={optimizedImage.src} {...optimizedImage.attributes} />
* ```
*
* This is functionally equivalent to using the `<Image />` component, as the component calls this function internally.
*/
getImage: (
options: import('./dist/assets/types.js').ImageTransform
) => Promise<import('./dist/assets/types.js').GetImageResult>;
getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService;
Image: typeof import('./components/Image.astro').default;
};
type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] };
type ImgAttributes = WithRequired<
Omit<import('./types').HTMLAttributes<'img'>, 'src' | 'width' | 'height'>,
'alt'
>;
export type LocalImageProps = Simplify<
import('./dist/assets/types.js').LocalImageProps<ImgAttributes>
>;
export type RemoteImageProps = Simplify<
import('./dist/assets/types.js').RemoteImageProps<ImgAttributes>
>;
export const { getImage, getConfiguredImageService, Image }: AstroAssets;
}
type MD = import('./dist/@types/astro').MarkdownInstance<Record<string, any>>;
interface ExportedMarkdownModuleEntities {
frontmatter: MD['frontmatter'];
file: MD['file'];
url: MD['url'];
getHeadings: MD['getHeadings'];
/** @deprecated Renamed to `getHeadings()` */
getHeaders: () => void;
Content: MD['Content'];
rawContent: MD['rawContent'];
compiledContent: MD['compiledContent'];
load: MD['default'];
}
declare module '*.md' {
const { load }: ExportedMarkdownModuleEntities;
export const {
frontmatter,
file,
url,
getHeadings,
getHeaders,
Content,
rawContent,
compiledContent,
}: ExportedMarkdownModuleEntities;
export default load;
}
declare module '*.markdown' {
const { load }: ExportedMarkdownModuleEntities;
export const {
frontmatter,
file,
url,
getHeadings,
getHeaders,
Content,
rawContent,
compiledContent,
}: ExportedMarkdownModuleEntities;
export default load;
}
declare module '*.mkdn' {
const { load }: ExportedMarkdownModuleEntities;
export const {
frontmatter,
file,
url,
getHeadings,
getHeaders,
Content,
rawContent,
compiledContent,
}: ExportedMarkdownModuleEntities;
export default load;
}
declare module '*.mkd' {
const { load }: ExportedMarkdownModuleEntities;
export const {
frontmatter,
file,
url,
getHeadings,
getHeaders,
Content,
rawContent,
compiledContent,
}: ExportedMarkdownModuleEntities;
export default load;
}
declare module '*.mdwn' {
const { load }: ExportedMarkdownModuleEntities;
export const {
frontmatter,
file,
url,
getHeadings,
getHeaders,
Content,
rawContent,
compiledContent,
}: ExportedMarkdownModuleEntities;
export default load;
}
declare module '*.mdown' {
const { load }: ExportedMarkdownModuleEntities;
export const {
frontmatter,
file,
url,
getHeadings,
getHeaders,
Content,
rawContent,
compiledContent,
}: ExportedMarkdownModuleEntities;
export default load;
}
declare module '*.mdx' {
type MDX = import('./dist/@types/astro').MDXInstance<Record<string, any>>;
export const frontmatter: MDX['frontmatter'];
export const file: MDX['file'];
export const url: MDX['url'];
export const getHeadings: MDX['getHeadings'];
export const Content: MDX['Content'];
const load: MDX['default'];
export default load;
}
declare module 'astro:ssr-manifest' {
export const manifest: import('./dist/@types/astro').SSRManifest;
}
// Everything below are Vite's types (apart from image types, which are in `client.d.ts`)
// CSS modules
type CSSModuleClasses = { readonly [key: string]: string };
declare module '*.module.css' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.scss' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.sass' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.less' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.styl' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.stylus' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.pcss' {
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.sss' {
const classes: CSSModuleClasses;
export default classes;
}
// CSS
declare module '*.css' {
const css: string;
export default css;
}
declare module '*.scss' {
const css: string;
export default css;
}
declare module '*.sass' {
const css: string;
export default css;
}
declare module '*.less' {
const css: string;
export default css;
}
declare module '*.styl' {
const css: string;
export default css;
}
declare module '*.stylus' {
const css: string;
export default css;
}
declare module '*.pcss' {
const css: string;
export default css;
}
declare module '*.sss' {
const css: string;
export default css;
}
// Built-in asset types
// see `src/node/constants.ts`
// images
declare module '*.jfif' {
const src: string;
export default src;
}
declare module '*.pjpeg' {
const src: string;
export default src;
}
declare module '*.pjp' {
const src: string;
export default src;
}
declare module '*.ico' {
const src: string;
export default src;
}
// media
declare module '*.mp4' {
const src: string;
export default src;
}
declare module '*.webm' {
const src: string;
export default src;
}
declare module '*.ogg' {
const src: string;
export default src;
}
declare module '*.mp3' {
const src: string;
export default src;
}
declare module '*.wav' {
const src: string;
export default src;
}
declare module '*.flac' {
const src: string;
export default src;
}
declare module '*.aac' {
const src: string;
export default src;
}
declare module '*.opus' {
const src: string;
export default src;
}
// fonts
declare module '*.woff' {
const src: string;
export default src;
}
declare module '*.woff2' {
const src: string;
export default src;
}
declare module '*.eot' {
const src: string;
export default src;
}
declare module '*.ttf' {
const src: string;
export default src;
}
declare module '*.otf' {
const src: string;
export default src;
}
// other
declare module '*.webmanifest' {
const src: string;
export default src;
}
declare module '*.pdf' {
const src: string;
export default src;
}
declare module '*.txt' {
const src: string;
export default src;
}
// wasm?init
declare module '*.wasm?init' {
const initWasm: (options: WebAssembly.Imports) => Promise<WebAssembly.Instance>;
export default initWasm;
}
// web worker
declare module '*?worker' {
const workerConstructor: {
new (): Worker;
};
export default workerConstructor;
}
declare module '*?worker&inline' {
const workerConstructor: {
new (): Worker;
};
export default workerConstructor;
}
declare module '*?worker&url' {
const src: string;
export default src;
}
declare module '*?sharedworker' {
const sharedWorkerConstructor: {
new (): SharedWorker;
};
export default sharedWorkerConstructor;
}
declare module '*?sharedworker&inline' {
const sharedWorkerConstructor: {
new (): SharedWorker;
};
export default sharedWorkerConstructor;
}
declare module '*?sharedworker&url' {
const src: string;
export default src;
}
declare module '*?raw' {
const src: string;
export default src;
}
declare module '*?url' {
const src: string;
export default src;
}
declare module '*?inline' {
const src: string;
export default src;
}

41
node_modules/astro/client-image.d.ts generated vendored Normal file
View file

@ -0,0 +1,41 @@
/// <reference path="./client-base.d.ts" />
// TODO: Merge this file with `client-base.d.ts` in 3.0, when the `astro:assets` feature isn't under a flag anymore.
type InputFormat = import('./dist/assets/types.js').ImageInputFormat;
interface ImageMetadata {
src: string;
width: number;
height: number;
format: InputFormat;
}
declare module '*.gif' {
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;
}
declare module '*.svg' {
const metadata: ImageMetadata;
export default metadata;
}

31
node_modules/astro/client.d.ts generated vendored Normal file
View file

@ -0,0 +1,31 @@
/// <reference path="./client-base.d.ts" />
// images
declare module '*.jpg' {
const src: string;
export default src;
}
declare module '*.jpeg' {
const src: string;
export default src;
}
declare module '*.png' {
const src: string;
export default src;
}
declare module '*.gif' {
const src: string;
export default src;
}
declare module '*.svg' {
const src: string;
export default src;
}
declare module '*.webp' {
const src: string;
export default src;
}
declare module '*.avif' {
const src: string;
export default src;
}

90
node_modules/astro/components/Code.astro generated vendored Normal file
View file

@ -0,0 +1,90 @@
---
import type * as shiki from 'shiki';
import { renderToHtml } from 'shiki';
import { getHighlighter } from './Shiki.js';
interface Props {
/** The code to highlight. Required. */
code: string;
/**
* The language of your code.
* Supports all languages listed here: https://github.com/shikijs/shiki/blob/main/docs/languages.md#all-languages
* Instructions for loading a custom language: https://github.com/shikijs/shiki/blob/main/docs/languages.md#supporting-your-own-languages-with-shiki
*
* @default "plaintext"
*/
lang?: shiki.Lang | shiki.ILanguageRegistration;
/**
* The styling theme.
* Supports all themes listed here: https://github.com/shikijs/shiki/blob/main/docs/themes.md#all-themes
* Instructions for loading a custom theme: https://github.com/shikijs/shiki/blob/main/docs/themes.md#loading-theme
*
* @default "github-dark"
*/
theme?: shiki.IThemeRegistration;
/**
* Enable word wrapping.
* - true: enabled.
* - false: disabled.
* - null: All overflow styling removed. Code will overflow the element by default.
*
* @default false
*/
wrap?: boolean | null;
/**
* Generate inline code element only, without the pre element wrapper.
*
* @default false
*/
inline?: boolean;
}
const {
code,
lang = 'plaintext',
theme = 'github-dark',
wrap = false,
inline = false,
} = Astro.props;
// 1. Get the shiki syntax highlighter
const highlighter = await getHighlighter({
theme,
// Load custom lang if passed an object, otherwise load the default
langs: typeof lang !== 'string' ? [lang] : undefined,
});
// 2. Turn code into shiki theme tokens
const tokens = highlighter.codeToThemedTokens(code, typeof lang === 'string' ? lang : lang.id);
// 3. Get shiki theme object
const _theme = highlighter.getTheme();
// 4. Render the theme tokens as html
const html = renderToHtml(tokens, {
themeName: _theme.name,
fg: _theme.fg,
bg: _theme.bg,
elements: {
pre({ className, style, children }) {
// Swap to `code` tag if inline
const tag = inline ? 'code' : 'pre';
// Replace "shiki" class naming with "astro-code"
className = className.replace(/shiki/g, 'astro-code');
// Handle code wrapping
// if wrap=null, do nothing.
if (wrap === false) {
style += '; overflow-x: auto;"';
} else if (wrap === true) {
style += '; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;"';
}
return `<${tag} class="${className}" style="${style}" tabindex="0">${children}</${tag}>`;
},
code({ children }) {
return inline ? children : `<code>${children}</code>`;
},
},
});
---
<Fragment set:html={html} />

61
node_modules/astro/components/Debug.astro generated vendored Normal file
View file

@ -0,0 +1,61 @@
---
import Code from './Code.astro';
const key = Object.keys(Astro.props)[0];
const value = Astro.props[key];
---
<div class="astro-debug">
<div class="astro-debug-header">
<h2 class="astro-debug-title">
<span class="astro-debug-label">Debug</span>
<span class="astro-debug-name">"{key}"</span>
</h2>
</div>
<Code code={JSON.stringify(value, null, 2)} />
</div>
<style is:inline>
.astro-debug {
font-size: 14px;
padding: 1rem 1.5rem;
background: white;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,
'Open Sans', 'Helvetica Neue', sans-serif;
}
.astro-debug-header,
pre.astro-code {
margin: -1rem -1.5rem 1rem;
padding: 0.25rem 0.75rem;
}
.astro-debug-header {
background: #ff1639;
border-radius: 4px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.astro-debug-title {
font-size: 1em;
color: white;
margin: 0.5em 0;
}
.astro-debug-label {
font-weight: bold;
text-transform: uppercase;
margin-right: 0.75em;
}
pre.astro-code {
border: 1px solid #eee;
padding: 1rem 0.75rem;
border-radius: 4px;
border-top-left-radius: 0;
border-top-right-radius: 0;
font-size: 14px;
}
</style>

28
node_modules/astro/components/Image.astro generated vendored Normal file
View file

@ -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);
---
<img src={image.src} {...image.attributes} />

97
node_modules/astro/components/Shiki.js generated vendored Normal file
View file

@ -0,0 +1,97 @@
import { getHighlighter as getShikiHighlighter } from 'shiki';
import { themes } from './shiki-themes.js';
import { languages } from './shiki-languages.js';
// Caches Promise<Highlighter> for reuse when the same theme and langs are provided
const _resolvedHighlighters = new Map();
/** @type {Promise<any>} */
let _allLanguages;
function stringify(opts) {
// Always sort keys before stringifying to make sure objects match regardless of parameter ordering
return JSON.stringify(opts, Object.keys(opts).sort());
}
/**
* @param {import('shiki').HighlighterOptions} opts
* @returns {Promise<import('shiki').HighlighterOptions>}
*/
export async function resolveHighlighterOptions(opts) {
const resolvedThemes = [];
if (opts.theme && opts.theme in themes) {
resolvedThemes.push(await themes[opts.theme]());
} else if (Object.keys(opts.theme).length) {
resolvedThemes.push(opts.theme);
}
let resolvedLanguages;
if (opts.langs) {
resolvedLanguages = opts.langs;
} else {
if (!_allLanguages) {
_allLanguages = (await Promise.all(Object.values(languages).map((fn) => fn()))).filter(
Boolean
);
}
resolvedLanguages = await _allLanguages;
}
/** @type {import('shiki').HighlighterOptions} */
const highlighterOptions = {
...opts,
themes: resolvedThemes,
langs: resolvedLanguages,
};
// Do not pass through the theme as that will attempt to load it, even if it's included in themes
delete highlighterOptions['theme'];
return highlighterOptions;
}
/**
* @param {import('shiki').HighlighterOptions} opts
* @returns {Promise<import('shiki').Highlighter>}
*/
async function resolveHighlighter(opts) {
const highlighterOptions = await resolveHighlighterOptions(opts);
// Start the async getHighlighter call and cache the Promise
const highlighter = getShikiHighlighter(highlighterOptions).then((hl) => {
hl.setColorReplacements({
'#000001': 'var(--astro-code-color-text)',
'#000002': 'var(--astro-code-color-background)',
'#000004': 'var(--astro-code-token-constant)',
'#000005': 'var(--astro-code-token-string)',
'#000006': 'var(--astro-code-token-comment)',
'#000007': 'var(--astro-code-token-keyword)',
'#000008': 'var(--astro-code-token-parameter)',
'#000009': 'var(--astro-code-token-function)',
'#000010': 'var(--astro-code-token-string-expression)',
'#000011': 'var(--astro-code-token-punctuation)',
'#000012': 'var(--astro-code-token-link)',
});
return hl;
});
return highlighter;
}
/**
* @param {import('shiki').HighlighterOptions} opts
* @returns {Promise<import('shiki').Highlighter>}
*/
export function getHighlighter(opts) {
const key = stringify(opts);
// Highlighter has already been requested, reuse the same instance
if (_resolvedHighlighters.has(key)) {
return _resolvedHighlighters.get(key);
}
const highlighter = resolveHighlighter(opts);
_resolvedHighlighters.set(key, highlighter);
return highlighter;
}

2
node_modules/astro/components/index.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export { default as Code } from './Code.astro';
export { default as Debug } from './Debug.astro';

176
node_modules/astro/components/shiki-languages.js generated vendored Normal file
View file

@ -0,0 +1,176 @@
/**
* This file is prebuilt from packages/astro/scripts/shiki-gen-languages.mjs
* Do not edit this directly, but instead edit that file and rerun it to generate this file.
*/
import { BUNDLED_LANGUAGES } from 'shiki';
function handleLang(grammar, language) {
const lang = BUNDLED_LANGUAGES.find((l) => l.id === language);
if (lang) {
return {
...lang,
grammar,
};
} else {
return undefined;
}
}
// prettier-ignore
export const languages = {
'abap': () => import('shiki/languages/abap.tmLanguage.json').then((mod) => handleLang(mod.default, 'abap')),
'actionscript-3': () => import('shiki/languages/actionscript-3.tmLanguage.json').then((mod) => handleLang(mod.default, 'actionscript-3')),
'ada': () => import('shiki/languages/ada.tmLanguage.json').then((mod) => handleLang(mod.default, 'ada')),
'apache': () => import('shiki/languages/apache.tmLanguage.json').then((mod) => handleLang(mod.default, 'apache')),
'apex': () => import('shiki/languages/apex.tmLanguage.json').then((mod) => handleLang(mod.default, 'apex')),
'apl': () => import('shiki/languages/apl.tmLanguage.json').then((mod) => handleLang(mod.default, 'apl')),
'applescript': () => import('shiki/languages/applescript.tmLanguage.json').then((mod) => handleLang(mod.default, 'applescript')),
'ara': () => import('shiki/languages/ara.tmLanguage.json').then((mod) => handleLang(mod.default, 'ara')),
'asm': () => import('shiki/languages/asm.tmLanguage.json').then((mod) => handleLang(mod.default, 'asm')),
'astro': () => import('shiki/languages/astro.tmLanguage.json').then((mod) => handleLang(mod.default, 'astro')),
'awk': () => import('shiki/languages/awk.tmLanguage.json').then((mod) => handleLang(mod.default, 'awk')),
'ballerina': () => import('shiki/languages/ballerina.tmLanguage.json').then((mod) => handleLang(mod.default, 'ballerina')),
'bat': () => import('shiki/languages/bat.tmLanguage.json').then((mod) => handleLang(mod.default, 'bat')),
'berry': () => import('shiki/languages/berry.tmLanguage.json').then((mod) => handleLang(mod.default, 'berry')),
'bibtex': () => import('shiki/languages/bibtex.tmLanguage.json').then((mod) => handleLang(mod.default, 'bibtex')),
'bicep': () => import('shiki/languages/bicep.tmLanguage.json').then((mod) => handleLang(mod.default, 'bicep')),
'blade': () => import('shiki/languages/blade.tmLanguage.json').then((mod) => handleLang(mod.default, 'blade')),
'c': () => import('shiki/languages/c.tmLanguage.json').then((mod) => handleLang(mod.default, 'c')),
'cadence': () => import('shiki/languages/cadence.tmLanguage.json').then((mod) => handleLang(mod.default, 'cadence')),
'clarity': () => import('shiki/languages/clarity.tmLanguage.json').then((mod) => handleLang(mod.default, 'clarity')),
'clojure': () => import('shiki/languages/clojure.tmLanguage.json').then((mod) => handleLang(mod.default, 'clojure')),
'cmake': () => import('shiki/languages/cmake.tmLanguage.json').then((mod) => handleLang(mod.default, 'cmake')),
'cobol': () => import('shiki/languages/cobol.tmLanguage.json').then((mod) => handleLang(mod.default, 'cobol')),
'codeql': () => import('shiki/languages/codeql.tmLanguage.json').then((mod) => handleLang(mod.default, 'codeql')),
'coffee': () => import('shiki/languages/coffee.tmLanguage.json').then((mod) => handleLang(mod.default, 'coffee')),
'cpp-macro': () => import('shiki/languages/cpp-macro.tmLanguage.json').then((mod) => handleLang(mod.default, 'cpp-macro')),
'cpp': () => import('shiki/languages/cpp.tmLanguage.json').then((mod) => handleLang(mod.default, 'cpp')),
'crystal': () => import('shiki/languages/crystal.tmLanguage.json').then((mod) => handleLang(mod.default, 'crystal')),
'csharp': () => import('shiki/languages/csharp.tmLanguage.json').then((mod) => handleLang(mod.default, 'csharp')),
'css': () => import('shiki/languages/css.tmLanguage.json').then((mod) => handleLang(mod.default, 'css')),
'cue': () => import('shiki/languages/cue.tmLanguage.json').then((mod) => handleLang(mod.default, 'cue')),
'd': () => import('shiki/languages/d.tmLanguage.json').then((mod) => handleLang(mod.default, 'd')),
'dart': () => import('shiki/languages/dart.tmLanguage.json').then((mod) => handleLang(mod.default, 'dart')),
'dax': () => import('shiki/languages/dax.tmLanguage.json').then((mod) => handleLang(mod.default, 'dax')),
'diff': () => import('shiki/languages/diff.tmLanguage.json').then((mod) => handleLang(mod.default, 'diff')),
'docker': () => import('shiki/languages/docker.tmLanguage.json').then((mod) => handleLang(mod.default, 'docker')),
'dream-maker': () => import('shiki/languages/dream-maker.tmLanguage.json').then((mod) => handleLang(mod.default, 'dream-maker')),
'elixir': () => import('shiki/languages/elixir.tmLanguage.json').then((mod) => handleLang(mod.default, 'elixir')),
'elm': () => import('shiki/languages/elm.tmLanguage.json').then((mod) => handleLang(mod.default, 'elm')),
'erb': () => import('shiki/languages/erb.tmLanguage.json').then((mod) => handleLang(mod.default, 'erb')),
'erlang': () => import('shiki/languages/erlang.tmLanguage.json').then((mod) => handleLang(mod.default, 'erlang')),
'fish': () => import('shiki/languages/fish.tmLanguage.json').then((mod) => handleLang(mod.default, 'fish')),
'fsharp': () => import('shiki/languages/fsharp.tmLanguage.json').then((mod) => handleLang(mod.default, 'fsharp')),
'gherkin': () => import('shiki/languages/gherkin.tmLanguage.json').then((mod) => handleLang(mod.default, 'gherkin')),
'git-commit': () => import('shiki/languages/git-commit.tmLanguage.json').then((mod) => handleLang(mod.default, 'git-commit')),
'git-rebase': () => import('shiki/languages/git-rebase.tmLanguage.json').then((mod) => handleLang(mod.default, 'git-rebase')),
'glsl': () => import('shiki/languages/glsl.tmLanguage.json').then((mod) => handleLang(mod.default, 'glsl')),
'gnuplot': () => import('shiki/languages/gnuplot.tmLanguage.json').then((mod) => handleLang(mod.default, 'gnuplot')),
'go': () => import('shiki/languages/go.tmLanguage.json').then((mod) => handleLang(mod.default, 'go')),
'graphql': () => import('shiki/languages/graphql.tmLanguage.json').then((mod) => handleLang(mod.default, 'graphql')),
'groovy': () => import('shiki/languages/groovy.tmLanguage.json').then((mod) => handleLang(mod.default, 'groovy')),
'hack': () => import('shiki/languages/hack.tmLanguage.json').then((mod) => handleLang(mod.default, 'hack')),
'haml': () => import('shiki/languages/haml.tmLanguage.json').then((mod) => handleLang(mod.default, 'haml')),
'handlebars': () => import('shiki/languages/handlebars.tmLanguage.json').then((mod) => handleLang(mod.default, 'handlebars')),
'haskell': () => import('shiki/languages/haskell.tmLanguage.json').then((mod) => handleLang(mod.default, 'haskell')),
'hcl': () => import('shiki/languages/hcl.tmLanguage.json').then((mod) => handleLang(mod.default, 'hcl')),
'hlsl': () => import('shiki/languages/hlsl.tmLanguage.json').then((mod) => handleLang(mod.default, 'hlsl')),
'html': () => import('shiki/languages/html.tmLanguage.json').then((mod) => handleLang(mod.default, 'html')),
'http': () => import('shiki/languages/http.tmLanguage.json').then((mod) => handleLang(mod.default, 'http')),
'imba': () => import('shiki/languages/imba.tmLanguage.json').then((mod) => handleLang(mod.default, 'imba')),
'ini': () => import('shiki/languages/ini.tmLanguage.json').then((mod) => handleLang(mod.default, 'ini')),
'java': () => import('shiki/languages/java.tmLanguage.json').then((mod) => handleLang(mod.default, 'java')),
'javascript': () => import('shiki/languages/javascript.tmLanguage.json').then((mod) => handleLang(mod.default, 'javascript')),
'jinja-html': () => import('shiki/languages/jinja-html.tmLanguage.json').then((mod) => handleLang(mod.default, 'jinja-html')),
'jinja': () => import('shiki/languages/jinja.tmLanguage.json').then((mod) => handleLang(mod.default, 'jinja')),
'jison': () => import('shiki/languages/jison.tmLanguage.json').then((mod) => handleLang(mod.default, 'jison')),
'json': () => import('shiki/languages/json.tmLanguage.json').then((mod) => handleLang(mod.default, 'json')),
'json5': () => import('shiki/languages/json5.tmLanguage.json').then((mod) => handleLang(mod.default, 'json5')),
'jsonc': () => import('shiki/languages/jsonc.tmLanguage.json').then((mod) => handleLang(mod.default, 'jsonc')),
'jsonnet': () => import('shiki/languages/jsonnet.tmLanguage.json').then((mod) => handleLang(mod.default, 'jsonnet')),
'jssm': () => import('shiki/languages/jssm.tmLanguage.json').then((mod) => handleLang(mod.default, 'jssm')),
'jsx': () => import('shiki/languages/jsx.tmLanguage.json').then((mod) => handleLang(mod.default, 'jsx')),
'julia': () => import('shiki/languages/julia.tmLanguage.json').then((mod) => handleLang(mod.default, 'julia')),
'kotlin': () => import('shiki/languages/kotlin.tmLanguage.json').then((mod) => handleLang(mod.default, 'kotlin')),
'latex': () => import('shiki/languages/latex.tmLanguage.json').then((mod) => handleLang(mod.default, 'latex')),
'less': () => import('shiki/languages/less.tmLanguage.json').then((mod) => handleLang(mod.default, 'less')),
'liquid': () => import('shiki/languages/liquid.tmLanguage.json').then((mod) => handleLang(mod.default, 'liquid')),
'lisp': () => import('shiki/languages/lisp.tmLanguage.json').then((mod) => handleLang(mod.default, 'lisp')),
'logo': () => import('shiki/languages/logo.tmLanguage.json').then((mod) => handleLang(mod.default, 'logo')),
'lua': () => import('shiki/languages/lua.tmLanguage.json').then((mod) => handleLang(mod.default, 'lua')),
'make': () => import('shiki/languages/make.tmLanguage.json').then((mod) => handleLang(mod.default, 'make')),
'markdown': () => import('shiki/languages/markdown.tmLanguage.json').then((mod) => handleLang(mod.default, 'markdown')),
'marko': () => import('shiki/languages/marko.tmLanguage.json').then((mod) => handleLang(mod.default, 'marko')),
'matlab': () => import('shiki/languages/matlab.tmLanguage.json').then((mod) => handleLang(mod.default, 'matlab')),
'mdx': () => import('shiki/languages/mdx.tmLanguage.json').then((mod) => handleLang(mod.default, 'mdx')),
'mermaid': () => import('shiki/languages/mermaid.tmLanguage.json').then((mod) => handleLang(mod.default, 'mermaid')),
'nginx': () => import('shiki/languages/nginx.tmLanguage.json').then((mod) => handleLang(mod.default, 'nginx')),
'nim': () => import('shiki/languages/nim.tmLanguage.json').then((mod) => handleLang(mod.default, 'nim')),
'nix': () => import('shiki/languages/nix.tmLanguage.json').then((mod) => handleLang(mod.default, 'nix')),
'objective-c': () => import('shiki/languages/objective-c.tmLanguage.json').then((mod) => handleLang(mod.default, 'objective-c')),
'objective-cpp': () => import('shiki/languages/objective-cpp.tmLanguage.json').then((mod) => handleLang(mod.default, 'objective-cpp')),
'ocaml': () => import('shiki/languages/ocaml.tmLanguage.json').then((mod) => handleLang(mod.default, 'ocaml')),
'pascal': () => import('shiki/languages/pascal.tmLanguage.json').then((mod) => handleLang(mod.default, 'pascal')),
'perl': () => import('shiki/languages/perl.tmLanguage.json').then((mod) => handleLang(mod.default, 'perl')),
'php-html': () => import('shiki/languages/php-html.tmLanguage.json').then((mod) => handleLang(mod.default, 'php-html')),
'php': () => import('shiki/languages/php.tmLanguage.json').then((mod) => handleLang(mod.default, 'php')),
'plsql': () => import('shiki/languages/plsql.tmLanguage.json').then((mod) => handleLang(mod.default, 'plsql')),
'postcss': () => import('shiki/languages/postcss.tmLanguage.json').then((mod) => handleLang(mod.default, 'postcss')),
'powerquery': () => import('shiki/languages/powerquery.tmLanguage.json').then((mod) => handleLang(mod.default, 'powerquery')),
'powershell': () => import('shiki/languages/powershell.tmLanguage.json').then((mod) => handleLang(mod.default, 'powershell')),
'prisma': () => import('shiki/languages/prisma.tmLanguage.json').then((mod) => handleLang(mod.default, 'prisma')),
'prolog': () => import('shiki/languages/prolog.tmLanguage.json').then((mod) => handleLang(mod.default, 'prolog')),
'proto': () => import('shiki/languages/proto.tmLanguage.json').then((mod) => handleLang(mod.default, 'proto')),
'pug': () => import('shiki/languages/pug.tmLanguage.json').then((mod) => handleLang(mod.default, 'pug')),
'puppet': () => import('shiki/languages/puppet.tmLanguage.json').then((mod) => handleLang(mod.default, 'puppet')),
'purescript': () => import('shiki/languages/purescript.tmLanguage.json').then((mod) => handleLang(mod.default, 'purescript')),
'python': () => import('shiki/languages/python.tmLanguage.json').then((mod) => handleLang(mod.default, 'python')),
'r': () => import('shiki/languages/r.tmLanguage.json').then((mod) => handleLang(mod.default, 'r')),
'raku': () => import('shiki/languages/raku.tmLanguage.json').then((mod) => handleLang(mod.default, 'raku')),
'razor': () => import('shiki/languages/razor.tmLanguage.json').then((mod) => handleLang(mod.default, 'razor')),
'rel': () => import('shiki/languages/rel.tmLanguage.json').then((mod) => handleLang(mod.default, 'rel')),
'riscv': () => import('shiki/languages/riscv.tmLanguage.json').then((mod) => handleLang(mod.default, 'riscv')),
'rst': () => import('shiki/languages/rst.tmLanguage.json').then((mod) => handleLang(mod.default, 'rst')),
'ruby': () => import('shiki/languages/ruby.tmLanguage.json').then((mod) => handleLang(mod.default, 'ruby')),
'rust': () => import('shiki/languages/rust.tmLanguage.json').then((mod) => handleLang(mod.default, 'rust')),
'sas': () => import('shiki/languages/sas.tmLanguage.json').then((mod) => handleLang(mod.default, 'sas')),
'sass': () => import('shiki/languages/sass.tmLanguage.json').then((mod) => handleLang(mod.default, 'sass')),
'scala': () => import('shiki/languages/scala.tmLanguage.json').then((mod) => handleLang(mod.default, 'scala')),
'scheme': () => import('shiki/languages/scheme.tmLanguage.json').then((mod) => handleLang(mod.default, 'scheme')),
'scss': () => import('shiki/languages/scss.tmLanguage.json').then((mod) => handleLang(mod.default, 'scss')),
'shaderlab': () => import('shiki/languages/shaderlab.tmLanguage.json').then((mod) => handleLang(mod.default, 'shaderlab')),
'shellscript': () => import('shiki/languages/shellscript.tmLanguage.json').then((mod) => handleLang(mod.default, 'shellscript')),
'smalltalk': () => import('shiki/languages/smalltalk.tmLanguage.json').then((mod) => handleLang(mod.default, 'smalltalk')),
'solidity': () => import('shiki/languages/solidity.tmLanguage.json').then((mod) => handleLang(mod.default, 'solidity')),
'sparql': () => import('shiki/languages/sparql.tmLanguage.json').then((mod) => handleLang(mod.default, 'sparql')),
'sql': () => import('shiki/languages/sql.tmLanguage.json').then((mod) => handleLang(mod.default, 'sql')),
'ssh-config': () => import('shiki/languages/ssh-config.tmLanguage.json').then((mod) => handleLang(mod.default, 'ssh-config')),
'stata': () => import('shiki/languages/stata.tmLanguage.json').then((mod) => handleLang(mod.default, 'stata')),
'stylus': () => import('shiki/languages/stylus.tmLanguage.json').then((mod) => handleLang(mod.default, 'stylus')),
'svelte': () => import('shiki/languages/svelte.tmLanguage.json').then((mod) => handleLang(mod.default, 'svelte')),
'swift': () => import('shiki/languages/swift.tmLanguage.json').then((mod) => handleLang(mod.default, 'swift')),
'system-verilog': () => import('shiki/languages/system-verilog.tmLanguage.json').then((mod) => handleLang(mod.default, 'system-verilog')),
'tasl': () => import('shiki/languages/tasl.tmLanguage.json').then((mod) => handleLang(mod.default, 'tasl')),
'tcl': () => import('shiki/languages/tcl.tmLanguage.json').then((mod) => handleLang(mod.default, 'tcl')),
'tex': () => import('shiki/languages/tex.tmLanguage.json').then((mod) => handleLang(mod.default, 'tex')),
'toml': () => import('shiki/languages/toml.tmLanguage.json').then((mod) => handleLang(mod.default, 'toml')),
'tsx': () => import('shiki/languages/tsx.tmLanguage.json').then((mod) => handleLang(mod.default, 'tsx')),
'turtle': () => import('shiki/languages/turtle.tmLanguage.json').then((mod) => handleLang(mod.default, 'turtle')),
'twig': () => import('shiki/languages/twig.tmLanguage.json').then((mod) => handleLang(mod.default, 'twig')),
'typescript': () => import('shiki/languages/typescript.tmLanguage.json').then((mod) => handleLang(mod.default, 'typescript')),
'v': () => import('shiki/languages/v.tmLanguage.json').then((mod) => handleLang(mod.default, 'v')),
'vb': () => import('shiki/languages/vb.tmLanguage.json').then((mod) => handleLang(mod.default, 'vb')),
'verilog': () => import('shiki/languages/verilog.tmLanguage.json').then((mod) => handleLang(mod.default, 'verilog')),
'vhdl': () => import('shiki/languages/vhdl.tmLanguage.json').then((mod) => handleLang(mod.default, 'vhdl')),
'viml': () => import('shiki/languages/viml.tmLanguage.json').then((mod) => handleLang(mod.default, 'viml')),
'vue-html': () => import('shiki/languages/vue-html.tmLanguage.json').then((mod) => handleLang(mod.default, 'vue-html')),
'vue': () => import('shiki/languages/vue.tmLanguage.json').then((mod) => handleLang(mod.default, 'vue')),
'wasm': () => import('shiki/languages/wasm.tmLanguage.json').then((mod) => handleLang(mod.default, 'wasm')),
'wenyan': () => import('shiki/languages/wenyan.tmLanguage.json').then((mod) => handleLang(mod.default, 'wenyan')),
'wgsl': () => import('shiki/languages/wgsl.tmLanguage.json').then((mod) => handleLang(mod.default, 'wgsl')),
'xml': () => import('shiki/languages/xml.tmLanguage.json').then((mod) => handleLang(mod.default, 'xml')),
'xsl': () => import('shiki/languages/xsl.tmLanguage.json').then((mod) => handleLang(mod.default, 'xsl')),
'yaml': () => import('shiki/languages/yaml.tmLanguage.json').then((mod) => handleLang(mod.default, 'yaml')),
'zenscript': () => import('shiki/languages/zenscript.tmLanguage.json').then((mod) => handleLang(mod.default, 'zenscript')),
};

43
node_modules/astro/components/shiki-themes.js generated vendored Normal file
View file

@ -0,0 +1,43 @@
/**
* This file is prebuilt from packages/astro/scripts/shiki-gen-themes.mjs
* Do not edit this directly, but instead edit that file and rerun it to generate this file.
*/
// prettier-ignore
export const themes = {
'css-variables': () => import('shiki/themes/css-variables.json').then(mod => mod.default),
'dark-plus': () => import('shiki/themes/dark-plus.json').then(mod => mod.default),
'dracula-soft': () => import('shiki/themes/dracula-soft.json').then(mod => mod.default),
'dracula': () => import('shiki/themes/dracula.json').then(mod => mod.default),
'github-dark-dimmed': () => import('shiki/themes/github-dark-dimmed.json').then(mod => mod.default),
'github-dark': () => import('shiki/themes/github-dark.json').then(mod => mod.default),
'github-light': () => import('shiki/themes/github-light.json').then(mod => mod.default),
'hc_light': () => import('shiki/themes/hc_light.json').then(mod => mod.default),
'light-plus': () => import('shiki/themes/light-plus.json').then(mod => mod.default),
'material-theme-darker': () => import('shiki/themes/material-theme-darker.json').then(mod => mod.default),
'material-theme-lighter': () => import('shiki/themes/material-theme-lighter.json').then(mod => mod.default),
'material-theme-ocean': () => import('shiki/themes/material-theme-ocean.json').then(mod => mod.default),
'material-theme-palenight': () => import('shiki/themes/material-theme-palenight.json').then(mod => mod.default),
'material-theme': () => import('shiki/themes/material-theme.json').then(mod => mod.default),
'min-dark': () => import('shiki/themes/min-dark.json').then(mod => mod.default),
'min-light': () => import('shiki/themes/min-light.json').then(mod => mod.default),
'monokai': () => import('shiki/themes/monokai.json').then(mod => mod.default),
'nord': () => import('shiki/themes/nord.json').then(mod => mod.default),
'one-dark-pro': () => import('shiki/themes/one-dark-pro.json').then(mod => mod.default),
'poimandres': () => import('shiki/themes/poimandres.json').then(mod => mod.default),
'rose-pine-dawn': () => import('shiki/themes/rose-pine-dawn.json').then(mod => mod.default),
'rose-pine-moon': () => import('shiki/themes/rose-pine-moon.json').then(mod => mod.default),
'rose-pine': () => import('shiki/themes/rose-pine.json').then(mod => mod.default),
'slack-dark': () => import('shiki/themes/slack-dark.json').then(mod => mod.default),
'slack-ochin': () => import('shiki/themes/slack-ochin.json').then(mod => mod.default),
'solarized-dark': () => import('shiki/themes/solarized-dark.json').then(mod => mod.default),
'solarized-light': () => import('shiki/themes/solarized-light.json').then(mod => mod.default),
'vitesse-dark': () => import('shiki/themes/vitesse-dark.json').then(mod => mod.default),
'vitesse-light': () => import('shiki/themes/vitesse-light.json').then(mod => mod.default),
// old theme names for compat
'material-darker': () => import('shiki/themes/material-theme-darker').then(mod => mod.default),
'material-default': () => import('shiki/themes/material-theme').then(mod => mod.default),
'material-lighter': () => import('shiki/themes/material-theme-lighter').then(mod => mod.default),
'material-ocean': () => import('shiki/themes/material-theme-ocean').then(mod => mod.default),
'material-palenight': () => import('shiki/themes/material-theme-palenight').then(mod => mod.default),
};

26
node_modules/astro/config.d.ts generated vendored Normal file
View file

@ -0,0 +1,26 @@
type ViteUserConfig = import('vite').UserConfig;
type ViteUserConfigFn = import('vite').UserConfigFn;
type AstroUserConfig = import('./dist/@types/astro.js').AstroUserConfig;
type ImageServiceConfig = import('./dist/@types/astro.js').ImageServiceConfig;
/**
* See the full Astro Configuration API Documentation
* https://astro.build/config
*/
export function defineConfig(config: AstroUserConfig): AstroUserConfig;
/**
* Use Astro to generate a fully resolved Vite config
*/
export function getViteConfig(config: ViteUserConfig): ViteUserConfigFn;
/**
* Return the configuration needed to use the Sharp-based image service
* See: https://docs.astro.build/en/guides/assets/#using-sharp
*/
export function sharpImageService(): ImageServiceConfig;
/**
* Return the configuration needed to use the Squoosh-based image service
*/
export function squooshImageService(): ImageServiceConfig;

15
node_modules/astro/config.mjs generated vendored Normal file
View file

@ -0,0 +1,15 @@
export { defineConfig, getViteConfig } from './dist/config/index.js';
export function sharpImageService() {
return {
entrypoint: 'astro/assets/services/sharp',
config: {},
};
}
export function squooshImageService() {
return {
entrypoint: 'astro/assets/services/squoosh',
config: {},
};
}

83
node_modules/astro/content-module.template.mjs generated vendored Normal file
View file

@ -0,0 +1,83 @@
// astro-head-inject
import {
createCollectionToGlobResultMap,
createGetCollection,
createGetDataEntryById,
createGetEntries,
createGetEntry,
createGetEntryBySlug,
createReference,
} from 'astro/content/runtime';
export { z } from 'astro/zod';
const contentDir = '@@CONTENT_DIR@@';
const contentEntryGlob = import.meta.glob('@@CONTENT_ENTRY_GLOB_PATH@@', {
query: { astroContentCollectionEntry: true },
});
const contentCollectionToEntryMap = createCollectionToGlobResultMap({
globResult: contentEntryGlob,
contentDir,
});
const dataEntryGlob = import.meta.glob('@@DATA_ENTRY_GLOB_PATH@@', {
query: { astroDataCollectionEntry: true },
});
const dataCollectionToEntryMap = createCollectionToGlobResultMap({
globResult: dataEntryGlob,
contentDir,
});
const collectionToEntryMap = createCollectionToGlobResultMap({
globResult: { ...contentEntryGlob, ...dataEntryGlob },
contentDir,
});
let lookupMap = {};
/* @@LOOKUP_MAP_ASSIGNMENT@@ */
function createGlobLookup(glob) {
return async (collection, lookupId) => {
const filePath = lookupMap[collection]?.entries[lookupId];
if (!filePath) return undefined;
return glob[collection][filePath];
};
}
const renderEntryGlob = import.meta.glob('@@RENDER_ENTRY_GLOB_PATH@@', {
query: { astroRenderContent: true },
});
const collectionToRenderEntryMap = createCollectionToGlobResultMap({
globResult: renderEntryGlob,
contentDir,
});
export function defineCollection(config) {
if (!config.type) config.type = 'content';
return config;
}
export const getCollection = createGetCollection({
contentCollectionToEntryMap,
dataCollectionToEntryMap,
getRenderEntryImport: createGlobLookup(collectionToRenderEntryMap),
});
export const getEntryBySlug = createGetEntryBySlug({
getEntryImport: createGlobLookup(contentCollectionToEntryMap),
getRenderEntryImport: createGlobLookup(collectionToRenderEntryMap),
});
export const getDataEntryById = createGetDataEntryById({
dataCollectionToEntryMap,
});
export const getEntry = createGetEntry({
getEntryImport: createGlobLookup(collectionToEntryMap),
getRenderEntryImport: createGlobLookup(collectionToRenderEntryMap),
});
export const getEntries = createGetEntries(getEntry);
export const reference = createReference({ lookupMap });

201
node_modules/astro/content-types.template.d.ts generated vendored Normal file
View file

@ -0,0 +1,201 @@
declare module 'astro:content' {
interface Render {
'.md': Promise<{
Content: import('astro').MarkdownInstance<{}>['Content'];
headings: import('astro').MarkdownHeading[];
remarkPluginFrontmatter: Record<string, any>;
}>;
}
}
declare module 'astro:content' {
export { z } from 'astro/zod';
export type CollectionEntry<C extends keyof AnyEntryMap> = AnyEntryMap[C][keyof AnyEntryMap[C]];
// TODO: Remove this when having this fallback is no longer relevant. 2.3? 3.0? - erika, 2023-04-04
/**
* @deprecated
* `astro:content` no longer provide `image()`.
*
* Please use it through `schema`, like such:
* ```ts
* import { defineCollection, z } from "astro:content";
*
* defineCollection({
* schema: ({ image }) =>
* z.object({
* image: image(),
* }),
* });
* ```
*/
export const image: never;
// This needs to be in sync with ImageMetadata
export type ImageFunction = () => import('astro/zod').ZodObject<{
src: import('astro/zod').ZodString;
width: import('astro/zod').ZodNumber;
height: import('astro/zod').ZodNumber;
format: import('astro/zod').ZodUnion<
[
import('astro/zod').ZodLiteral<'png'>,
import('astro/zod').ZodLiteral<'jpg'>,
import('astro/zod').ZodLiteral<'jpeg'>,
import('astro/zod').ZodLiteral<'tiff'>,
import('astro/zod').ZodLiteral<'webp'>,
import('astro/zod').ZodLiteral<'gif'>,
import('astro/zod').ZodLiteral<'svg'>
]
>;
}>;
type BaseSchemaWithoutEffects =
| import('astro/zod').AnyZodObject
| import('astro/zod').ZodUnion<import('astro/zod').AnyZodObject[]>
| import('astro/zod').ZodDiscriminatedUnion<string, import('astro/zod').AnyZodObject[]>
| import('astro/zod').ZodIntersection<
import('astro/zod').AnyZodObject,
import('astro/zod').AnyZodObject
>;
type BaseSchema =
| BaseSchemaWithoutEffects
| import('astro/zod').ZodEffects<BaseSchemaWithoutEffects>;
export type SchemaContext = { image: ImageFunction };
type DataCollectionConfig<S extends BaseSchema> = {
type: 'data';
schema?: S | ((context: SchemaContext) => S);
};
type ContentCollectionConfig<S extends BaseSchema> = {
type?: 'content';
schema?: S | ((context: SchemaContext) => S);
};
type CollectionConfig<S> = ContentCollectionConfig<S> | DataCollectionConfig<S>;
export function defineCollection<S extends BaseSchema>(
input: CollectionConfig<S>
): CollectionConfig<S>;
type AllValuesOf<T> = T extends any ? T[keyof T] : never;
type ValidContentEntrySlug<C extends keyof ContentEntryMap> = AllValuesOf<
ContentEntryMap[C]
>['slug'];
export function getEntryBySlug<
C extends keyof ContentEntryMap,
E extends ValidContentEntrySlug<C> | (string & {})
>(
collection: C,
// Note that this has to accept a regular string too, for SSR
entrySlug: E
): E extends ValidContentEntrySlug<C>
? Promise<CollectionEntry<C>>
: Promise<CollectionEntry<C> | undefined>;
export function getDataEntryById<C extends keyof DataEntryMap, E extends keyof DataEntryMap[C]>(
collection: C,
entryId: E
): Promise<CollectionEntry<C>>;
export function getCollection<C extends keyof AnyEntryMap, E extends CollectionEntry<C>>(
collection: C,
filter?: (entry: CollectionEntry<C>) => entry is E
): Promise<E[]>;
export function getCollection<C extends keyof AnyEntryMap>(
collection: C,
filter?: (entry: CollectionEntry<C>) => unknown
): Promise<CollectionEntry<C>[]>;
export function getEntry<
C extends keyof ContentEntryMap,
E extends ValidContentEntrySlug<C> | (string & {})
>(entry: {
collection: C;
slug: E;
}): E extends ValidContentEntrySlug<C>
? Promise<CollectionEntry<C>>
: Promise<CollectionEntry<C> | undefined>;
export function getEntry<
C extends keyof DataEntryMap,
E extends keyof DataEntryMap[C] | (string & {})
>(entry: {
collection: C;
id: E;
}): E extends keyof DataEntryMap[C]
? Promise<DataEntryMap[C][E]>
: Promise<CollectionEntry<C> | undefined>;
export function getEntry<
C extends keyof ContentEntryMap,
E extends ValidContentEntrySlug<C> | (string & {})
>(
collection: C,
slug: E
): E extends ValidContentEntrySlug<C>
? Promise<CollectionEntry<C>>
: Promise<CollectionEntry<C> | undefined>;
export function getEntry<
C extends keyof DataEntryMap,
E extends keyof DataEntryMap[C] | (string & {})
>(
collection: C,
id: E
): E extends keyof DataEntryMap[C]
? Promise<DataEntryMap[C][E]>
: Promise<CollectionEntry<C> | undefined>;
/** Resolve an array of entry references from the same collection */
export function getEntries<C extends keyof ContentEntryMap>(
entries: {
collection: C;
slug: ValidContentEntrySlug<C>;
}[]
): Promise<CollectionEntry<C>[]>;
export function getEntries<C extends keyof DataEntryMap>(
entries: {
collection: C;
id: keyof DataEntryMap[C];
}[]
): Promise<CollectionEntry<C>[]>;
export function reference<C extends keyof AnyEntryMap>(
collection: C
): import('astro/zod').ZodEffects<
import('astro/zod').ZodString,
C extends keyof ContentEntryMap
? {
collection: C;
slug: ValidContentEntrySlug<C>;
}
: {
collection: C;
id: keyof DataEntryMap[C];
}
>;
// Allow generic `string` to avoid excessive type errors in the config
// if `dev` is not running to update as you edit.
// Invalid collection names will be caught at build time.
export function reference<C extends string>(
collection: C
): import('astro/zod').ZodEffects<import('astro/zod').ZodString, never>;
type ReturnTypeOrOriginal<T> = T extends (...args: any[]) => infer R ? R : T;
type InferEntrySchema<C extends keyof AnyEntryMap> = import('astro/zod').infer<
ReturnTypeOrOriginal<Required<ContentConfig['collections'][C]>['schema']>
>;
type ContentEntryMap = {
// @@CONTENT_ENTRY_MAP@@
};
type DataEntryMap = {
// @@DATA_ENTRY_MAP@@
};
type AnyEntryMap = ContentEntryMap & DataEntryMap;
type ContentConfig = '@@CONTENT_CONFIG_TYPE@@';
}

0
node_modules/astro/dist/@types/app.d.js generated vendored Normal file
View file

1846
node_modules/astro/dist/@types/astro.d.ts generated vendored Normal file

File diff suppressed because it is too large Load diff

0
node_modules/astro/dist/@types/astro.js generated vendored Normal file
View file

41
node_modules/astro/dist/@types/typed-emitter.d.ts generated vendored Normal file
View file

@ -0,0 +1,41 @@
/**
* The MIT License (MIT)
* Copyright (c) 2018 Andy Wermke
* https://github.com/andywer/typed-emitter/blob/9a139b6fa0ec6b0db6141b5b756b784e4f7ef4e4/LICENSE
*/
export type EventMap = {
[key: string]: (...args: any[]) => void;
};
/**
* Type-safe event emitter.
*
* Use it like this:
*
* ```typescript
* type MyEvents = {
* error: (error: Error) => void;
* message: (from: string, content: string) => void;
* }
*
* const myEmitter = new EventEmitter() as TypedEmitter<MyEvents>;
*
* myEmitter.emit("error", "x") // <- Will catch this type error;
* ```
*/
export interface TypedEventEmitter<Events extends EventMap> {
addListener<E extends keyof Events>(event: E, listener: Events[E]): this;
on<E extends keyof Events>(event: E, listener: Events[E]): this;
once<E extends keyof Events>(event: E, listener: Events[E]): this;
prependListener<E extends keyof Events>(event: E, listener: Events[E]): this;
prependOnceListener<E extends keyof Events>(event: E, listener: Events[E]): this;
off<E extends keyof Events>(event: E, listener: Events[E]): this;
removeAllListeners<E extends keyof Events>(event?: E): this;
removeListener<E extends keyof Events>(event: E, listener: Events[E]): this;
emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
eventNames(): (keyof Events | string | symbol)[];
rawListeners<E extends keyof Events>(event: E): Events[E][];
listeners<E extends keyof Events>(event: E): Events[E][];
listenerCount<E extends keyof Events>(event: E): number;
getMaxListeners(): number;
setMaxListeners(maxListeners: number): this;
}

0
node_modules/astro/dist/@types/typed-emitter.js generated vendored Normal file
View file

9
node_modules/astro/dist/assets/consts.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export declare const VIRTUAL_MODULE_ID = "astro:assets";
export declare const VIRTUAL_SERVICE_ID = "virtual:image-service";
export declare const VALID_INPUT_FORMATS: readonly ["jpeg", "jpg", "png", "tiff", "webp", "gif", "svg"];
/**
* Valid formats that our base services support.
* Certain formats can be imported (namely SVGs) but will not be processed.
*/
export declare const VALID_SUPPORTED_FORMATS: readonly ["jpeg", "jpg", "png", "tiff", "webp", "gif", "svg"];
export declare const VALID_OUTPUT_FORMATS: readonly ["avif", "png", "webp", "jpeg", "jpg", "svg"];

36
node_modules/astro/dist/assets/consts.js generated vendored Normal file
View file

@ -0,0 +1,36 @@
const VIRTUAL_MODULE_ID = "astro:assets";
const VIRTUAL_SERVICE_ID = "virtual:image-service";
const VALID_INPUT_FORMATS = [
// TODO: `image-size` does not support the following formats, so users can't import them.
// However, it would be immensely useful to add, for three reasons:
// - `heic` and `heif` are common formats, especially among Apple users.
// - AVIF is a common format on the web that's bound to become more and more common.
// - It's totally reasonable for an user's provided image service to want to support more image types.
//'heic',
//'heif',
//'avif',
"jpeg",
"jpg",
"png",
"tiff",
"webp",
"gif",
"svg"
];
const VALID_SUPPORTED_FORMATS = [
"jpeg",
"jpg",
"png",
"tiff",
"webp",
"gif",
"svg"
];
const VALID_OUTPUT_FORMATS = ["avif", "png", "webp", "jpeg", "jpg", "svg"];
export {
VALID_INPUT_FORMATS,
VALID_OUTPUT_FORMATS,
VALID_SUPPORTED_FORMATS,
VIRTUAL_MODULE_ID,
VIRTUAL_SERVICE_ID
};

22
node_modules/astro/dist/assets/generate.d.ts generated vendored Normal file
View file

@ -0,0 +1,22 @@
import type { StaticBuildOptions } from '../core/build/types.js';
import type { ImageTransform } from './types.js';
interface GenerationDataUncached {
cached: false;
weight: {
before: number;
after: number;
};
}
interface GenerationDataCached {
cached: true;
}
type GenerationData = GenerationDataUncached | GenerationDataCached;
export declare function generateImage(buildOpts: StaticBuildOptions, options: ImageTransform, filepath: string): Promise<GenerationData | undefined>;
export declare function getStaticImageList(): Iterable<[
string,
{
path: string;
options: ImageTransform;
}
]>;
export {};

90
node_modules/astro/dist/assets/generate.js generated vendored Normal file
View file

@ -0,0 +1,90 @@
import fs from "node:fs";
import { basename, join } from "node:path/posix";
import { warn } from "../core/logger/core.js";
import { prependForwardSlash } from "../core/path.js";
import { isServerLikeOutput } from "../prerender/utils.js";
import { getConfiguredImageService, isESMImportedImage } from "./internal.js";
async function generateImage(buildOpts, options, filepath) {
if (!isESMImportedImage(options.src)) {
return void 0;
}
let useCache = true;
const assetsCacheDir = new URL("assets/", buildOpts.settings.config.cacheDir);
try {
await fs.promises.mkdir(assetsCacheDir, { recursive: true });
} catch (err) {
warn(
buildOpts.logging,
"astro:assets",
`An error was encountered while creating the cache directory. Proceeding without caching. Error: ${err}`
);
useCache = false;
}
let serverRoot, clientRoot;
if (isServerLikeOutput(buildOpts.settings.config)) {
serverRoot = buildOpts.settings.config.build.server;
clientRoot = buildOpts.settings.config.build.client;
} else {
serverRoot = buildOpts.settings.config.outDir;
clientRoot = buildOpts.settings.config.outDir;
}
const finalFileURL = new URL("." + filepath, clientRoot);
const finalFolderURL = new URL("./", finalFileURL);
const cachedFileURL = new URL(basename(filepath), assetsCacheDir);
try {
await fs.promises.copyFile(cachedFileURL, finalFileURL);
return {
cached: true
};
} catch (e) {
}
const originalImagePath = options.src.src;
const fileData = await fs.promises.readFile(
new URL(
"." + prependForwardSlash(
join(buildOpts.settings.config.build.assets, basename(originalImagePath))
),
serverRoot
)
);
const imageService = await getConfiguredImageService();
const resultData = await imageService.transform(
fileData,
{ ...options, src: originalImagePath },
buildOpts.settings.config.image.service.config
);
await fs.promises.mkdir(finalFolderURL, { recursive: true });
if (useCache) {
try {
await fs.promises.writeFile(cachedFileURL, resultData.data);
await fs.promises.copyFile(cachedFileURL, finalFileURL);
} catch (e) {
warn(
buildOpts.logging,
"astro:assets",
`An error was encountered while creating the cache directory. Proceeding without caching. Error: ${e}`
);
await fs.promises.writeFile(finalFileURL, resultData.data);
}
} else {
await fs.promises.writeFile(finalFileURL, resultData.data);
}
return {
cached: false,
weight: {
before: Math.trunc(fileData.byteLength / 1024),
after: Math.trunc(resultData.data.byteLength / 1024)
}
};
}
function getStaticImageList() {
var _a, _b;
if (!((_a = globalThis == null ? void 0 : globalThis.astroAsset) == null ? void 0 : _a.staticImages)) {
return [];
}
return (_b = globalThis.astroAsset.staticImages) == null ? void 0 : _b.entries();
}
export {
generateImage,
getStaticImageList
};

5
node_modules/astro/dist/assets/image-endpoint.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
import type { APIRoute } from '../@types/astro.js';
/**
* Endpoint used in SSR to serve optimized images
*/
export declare const get: APIRoute;

55
node_modules/astro/dist/assets/image-endpoint.js generated vendored Normal file
View file

@ -0,0 +1,55 @@
import mime from "mime/lite.js";
import { isRemotePath } from "../core/path.js";
import { getConfiguredImageService } from "./internal.js";
import { isLocalService } from "./services/service.js";
import { etag } from "./utils/etag.js";
import { imageServiceConfig } from "astro:assets";
async function loadRemoteImage(src) {
try {
const res = await fetch(src);
if (!res.ok) {
return void 0;
}
return Buffer.from(await res.arrayBuffer());
} catch (err) {
return void 0;
}
}
const get = 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, imageServiceConfig);
if (!(transform == null ? void 0 : transform.src)) {
throw new Error("Incorrect transform returned by `parseURL`");
}
let inputBuffer = void 0;
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,
imageServiceConfig
);
return new Response(data, {
status: 200,
headers: {
"Content-Type": mime.getType(format) ?? `image/${format}`,
"Cache-Control": "public, max-age=31536000",
ETag: etag(data.toString()),
Date: (/* @__PURE__ */ new Date()).toUTCString()
}
});
} catch (err) {
return new Response(`Server Error: ${err}`, { status: 500 });
}
};
export {
get
};

3
node_modules/astro/dist/assets/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
export { getConfiguredImageService, getImage } from './internal.js';
export { baseService, isLocalService } from './services/service.js';
export { type LocalImageProps, type RemoteImageProps } from './types.js';

9
node_modules/astro/dist/assets/index.js generated vendored Normal file
View file

@ -0,0 +1,9 @@
import { getConfiguredImageService, getImage } from "./internal.js";
import { baseService, isLocalService } from "./services/service.js";
import {} from "./types.js";
export {
baseService,
getConfiguredImageService,
getImage,
isLocalService
};

5
node_modules/astro/dist/assets/internal.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
import { type ImageService } from './services/service.js';
import type { GetImageResult, ImageMetadata, ImageTransform } from './types.js';
export declare function isESMImportedImage(src: ImageMetadata | string): src is ImageMetadata;
export declare function getConfiguredImageService(): Promise<ImageService>;
export declare function getImage(options: ImageTransform, serviceConfig: Record<string, any>): Promise<GetImageResult>;

48
node_modules/astro/dist/assets/internal.js generated vendored Normal file
View file

@ -0,0 +1,48 @@
import { AstroError, AstroErrorData } from "../core/errors/index.js";
import { isLocalService } from "./services/service.js";
function isESMImportedImage(src) {
return typeof src === "object";
}
async function getConfiguredImageService() {
var _a;
if (!((_a = globalThis == null ? void 0 : globalThis.astroAsset) == null ? void 0 : _a.imageService)) {
const { default: service } = await import(
// @ts-expect-error
"virtual:image-service"
).catch((e) => {
const error = new AstroError(AstroErrorData.InvalidImageService);
error.cause = e;
throw error;
});
if (!globalThis.astroAsset)
globalThis.astroAsset = {};
globalThis.astroAsset.imageService = service;
return service;
}
return globalThis.astroAsset.imageService;
}
async function getImage(options, serviceConfig) {
if (!options || typeof options !== "object") {
throw new AstroError({
...AstroErrorData.ExpectedImageOptions,
message: AstroErrorData.ExpectedImageOptions.message(JSON.stringify(options))
});
}
const service = await getConfiguredImageService();
const validatedOptions = service.validateOptions ? service.validateOptions(options, serviceConfig) : options;
let imageURL = service.getURL(validatedOptions, serviceConfig);
if (isLocalService(service) && globalThis.astroAsset.addStaticImage) {
imageURL = globalThis.astroAsset.addStaticImage(validatedOptions);
}
return {
rawOptions: options,
options: validatedOptions,
src: imageURL,
attributes: service.getHTMLAttributes !== void 0 ? service.getHTMLAttributes(validatedOptions, serviceConfig) : {}
};
}
export {
getConfiguredImageService,
getImage,
isESMImportedImage
};

82
node_modules/astro/dist/assets/services/service.d.ts generated vendored Normal file
View file

@ -0,0 +1,82 @@
/// <reference types="node" />
import type { ImageOutputFormat, ImageTransform } from '../types.js';
export type ImageService = LocalImageService | ExternalImageService;
export declare function isLocalService(service: ImageService | undefined): service is LocalImageService;
export declare function parseQuality(quality: string): string | number;
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, serviceConfig: Record<string, any>) => 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, serviceConfig: Record<string, any>) => Record<string, any>;
/**
* Validate and return the options passed by the user.
*
* This method is useful to present errors to users who have entered invalid options.
* For instance, if they are missing a required property or have entered an invalid image format.
*
* This method should returns options, and can be used to set defaults (ex: a default output format to be used if the user didn't specify one.)
*/
validateOptions?: (options: ImageTransform, serviceConfig: Record<string, any>) => ImageTransform;
}
export type ExternalImageService = SharedServiceProps;
export 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, serviceConfig: Record<string, any>) => 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, serviceConfig: Record<string, any>) => Promise<{
data: Buffer;
format: ImageOutputFormat;
}>;
}
export type BaseServiceTransform = {
src: string;
width?: number;
height?: number;
format: string;
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 adhere to the included services limitations:
* - Remote images are passed as is.
* - Only a limited amount of formats are supported.
* - For remote images, `width` and `height` are always required.
*
*/
export declare const baseService: Omit<LocalImageService, 'transform'>;
export {};

121
node_modules/astro/dist/assets/services/service.js generated vendored Normal file
View file

@ -0,0 +1,121 @@
import { AstroError, AstroErrorData } from "../../core/errors/index.js";
import { joinPaths } from "../../core/path.js";
import { VALID_SUPPORTED_FORMATS } from "../consts.js";
import { isESMImportedImage } from "../internal.js";
function isLocalService(service) {
if (!service) {
return false;
}
return "transform" in service;
}
function parseQuality(quality) {
let result = parseInt(quality);
if (Number.isNaN(result)) {
return quality;
}
return result;
}
const baseService = {
validateOptions(options) {
if (!options.src || typeof options.src !== "string" && typeof options.src !== "object") {
throw new AstroError({
...AstroErrorData.ExpectedImage,
message: AstroErrorData.ExpectedImage.message(JSON.stringify(options.src))
});
}
if (!isESMImportedImage(options.src)) {
if (options.src.startsWith("/@fs/")) {
throw new AstroError({
...AstroErrorData.LocalImageUsedWrongly,
message: AstroErrorData.LocalImageUsedWrongly.message(options.src)
});
}
let missingDimension;
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, options.src)
});
}
} else {
if (!VALID_SUPPORTED_FORMATS.includes(options.src.format)) {
throw new AstroError({
...AstroErrorData.UnsupportedImageFormat,
message: AstroErrorData.UnsupportedImageFormat.message(
options.src.format,
options.src.src,
VALID_SUPPORTED_FORMATS
)
});
}
if (options.src.format === "svg") {
options.format = "svg";
}
}
if (!options.format) {
options.format = "webp";
}
return options;
},
getHTMLAttributes(options) {
let targetWidth = options.width;
let targetHeight = options.height;
if (isESMImportedImage(options.src)) {
const aspectRatio = options.src.width / options.src.height;
if (targetHeight && !targetWidth) {
targetWidth = Math.round(targetHeight * aspectRatio);
} else if (targetWidth && !targetHeight) {
targetHeight = Math.round(targetWidth / aspectRatio);
} else if (!targetWidth && !targetHeight) {
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) {
if (!isESMImportedImage(options.src)) {
return options.src;
}
const searchParams = new URLSearchParams();
searchParams.append("href", options.src.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 joinPaths(import.meta.env.BASE_URL, "/_image?") + searchParams;
},
parseURL(url) {
const params = url.searchParams;
if (!params.has("href")) {
return void 0;
}
const transform = {
src: params.get("href"),
width: params.has("w") ? parseInt(params.get("w")) : void 0,
height: params.has("h") ? parseInt(params.get("h")) : void 0,
format: params.get("f"),
quality: params.get("q")
};
return transform;
}
};
export {
baseService,
isLocalService,
parseQuality
};

3
node_modules/astro/dist/assets/services/sharp.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import { type LocalImageService } from './service.js';
declare const sharpService: LocalImageService;
export default sharpService;

61
node_modules/astro/dist/assets/services/sharp.js generated vendored Normal file
View file

@ -0,0 +1,61 @@
import {
baseService,
parseQuality
} from "./service.js";
let sharp;
const qualityTable = {
low: 25,
mid: 50,
high: 80,
max: 100
};
async function loadSharp() {
let sharpImport;
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 = {
validateOptions: baseService.validateOptions,
getURL: baseService.getURL,
parseURL: baseService.parseURL,
getHTMLAttributes: baseService.getHTMLAttributes,
async transform(inputBuffer, transformOptions) {
if (!sharp)
sharp = await loadSharp();
const transform = transformOptions;
if (transform.format === "svg")
return { data: inputBuffer, format: "svg" };
let result = sharp(inputBuffer, { failOnError: false, pages: -1 });
result.rotate();
if (transform.height && !transform.width) {
result.resize({ height: transform.height });
} else if (transform.width) {
result.resize({ width: transform.width });
}
if (transform.format) {
let quality = void 0;
if (transform.quality) {
const parsedQuality = parseQuality(transform.quality);
if (typeof parsedQuality === "number") {
quality = parsedQuality;
} else {
quality = transform.quality in qualityTable ? qualityTable[transform.quality] : void 0;
}
}
result.toFormat(transform.format, { quality });
}
const { data, info } = await result.toBuffer({ resolveWithObject: true });
return {
data,
format: info.format
};
}
};
var sharp_default = sharpService;
export {
sharp_default as default
};

3
node_modules/astro/dist/assets/services/squoosh.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import { type LocalImageService } from './service.js';
declare const service: LocalImageService;
export default service;

84
node_modules/astro/dist/assets/services/squoosh.js generated vendored Normal file
View file

@ -0,0 +1,84 @@
import { imageMetadata } from "../utils/metadata.js";
import {
baseService,
parseQuality
} from "./service.js";
import { processBuffer } from "./vendor/squoosh/image-pool.js";
const baseQuality = { low: 25, mid: 50, high: 80, max: 100 };
const qualityTable = {
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
};
async function getRotationForEXIF(transform, inputBuffer) {
const filePath = transform.src.slice("/@fs".length);
const filePathURL = new URL("." + filePath, "file:");
const meta = await imageMetadata(filePathURL, inputBuffer);
if (!meta)
return void 0;
switch (meta.orientation) {
case 3:
case 4:
return { type: "rotate", numRotations: 2 };
case 5:
case 6:
return { type: "rotate", numRotations: 1 };
case 7:
case 8:
return { type: "rotate", numRotations: 3 };
}
}
const service = {
validateOptions: baseService.validateOptions,
getURL: baseService.getURL,
parseURL: baseService.parseURL,
getHTMLAttributes: baseService.getHTMLAttributes,
async transform(inputBuffer, transformOptions) {
const transform = transformOptions;
let format = transform.format;
if (format === "svg")
return { data: inputBuffer, format: "svg" };
const operations = [];
const rotation = await getRotationForEXIF(transform, inputBuffer);
if (rotation) {
operations.push(rotation);
}
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 = void 0;
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] : void 0;
}
}
const data = await processBuffer(inputBuffer, operations, format, quality);
return {
data: Buffer.from(data),
format
};
}
};
var squoosh_default = service;
export {
squoosh_default as default
};

View file

@ -0,0 +1,11 @@
var AVIFTune = /* @__PURE__ */ ((AVIFTune2) => {
AVIFTune2[AVIFTune2["auto"] = 0] = "auto";
AVIFTune2[AVIFTune2["psnr"] = 1] = "psnr";
AVIFTune2[AVIFTune2["ssim"] = 2] = "ssim";
return AVIFTune2;
})(AVIFTune || {});
var avif_enc_d_default = moduleFactory;
export {
AVIFTune,
avif_enc_d_default as default
};

View file

@ -0,0 +1,2 @@
declare var Module: (Module: any) => any;
export default Module;

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
declare var Module: (Module: any) => any;
export default Module;

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,158 @@
/// <reference types="node" />
interface DecodeModule extends EmscriptenWasm.Module {
decode: (data: Uint8Array) => ImageData;
}
export interface ResizeOptions {
width?: number;
height?: number;
method: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3';
premultiply: boolean;
linearRGB: boolean;
}
export interface RotateOptions {
numRotations: number;
}
import type { MozJPEGModule as MozJPEGEncodeModule } from './mozjpeg/mozjpeg_enc';
import type { WebPModule as WebPEncodeModule } from './webp/webp_enc';
import type { AVIFModule as AVIFEncodeModule } from './avif/avif_enc';
import ImageData from './image_data.js';
export declare const preprocessors: {
readonly resize: {
readonly name: "Resize";
readonly description: "Resize the image before compressing";
readonly instantiate: () => Promise<(buffer: Uint8Array, input_width: number, input_height: number, { width, height, method, premultiply, linearRGB }: ResizeOptions) => ImageData>;
readonly defaultOptions: {
readonly method: "lanczos3";
readonly fitMethod: "stretch";
readonly premultiply: true;
readonly linearRGB: true;
};
};
readonly rotate: {
readonly name: "Rotate";
readonly description: "Rotate image";
readonly instantiate: () => Promise<(buffer: Uint8Array, width: number, height: number, { numRotations }: RotateOptions) => Promise<ImageData>>;
readonly defaultOptions: {
readonly numRotations: 0;
};
};
};
export declare const codecs: {
readonly mozjpeg: {
readonly name: "MozJPEG";
readonly extension: "jpg";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<DecodeModule>;
readonly enc: () => Promise<MozJPEGEncodeModule>;
readonly defaultEncoderOptions: {
readonly quality: 75;
readonly baseline: false;
readonly arithmetic: false;
readonly progressive: true;
readonly optimize_coding: true;
readonly smoothing: 0;
readonly color_space: 3;
readonly quant_table: 3;
readonly trellis_multipass: false;
readonly trellis_opt_zero: false;
readonly trellis_opt_table: false;
readonly trellis_loops: 1;
readonly auto_subsample: true;
readonly chroma_subsample: 2;
readonly separate_chroma_quality: false;
readonly chroma_quality: 75;
};
readonly autoOptimize: {
readonly option: "quality";
readonly min: 0;
readonly max: 100;
};
};
readonly webp: {
readonly name: "WebP";
readonly extension: "webp";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<DecodeModule>;
readonly enc: () => Promise<WebPEncodeModule>;
readonly defaultEncoderOptions: {
readonly quality: 75;
readonly target_size: 0;
readonly target_PSNR: 0;
readonly method: 4;
readonly sns_strength: 50;
readonly filter_strength: 60;
readonly filter_sharpness: 0;
readonly filter_type: 1;
readonly partitions: 0;
readonly segments: 4;
readonly pass: 1;
readonly show_compressed: 0;
readonly preprocessing: 0;
readonly autofilter: 0;
readonly partition_limit: 0;
readonly alpha_compression: 1;
readonly alpha_filtering: 1;
readonly alpha_quality: 100;
readonly lossless: 0;
readonly exact: 0;
readonly image_hint: 0;
readonly emulate_jpeg_size: 0;
readonly thread_level: 0;
readonly low_memory: 0;
readonly near_lossless: 100;
readonly use_delta_palette: 0;
readonly use_sharp_yuv: 0;
};
readonly autoOptimize: {
readonly option: "quality";
readonly min: 0;
readonly max: 100;
};
};
readonly avif: {
readonly name: "AVIF";
readonly extension: "avif";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<DecodeModule>;
readonly enc: () => Promise<AVIFEncodeModule>;
readonly defaultEncoderOptions: {
readonly cqLevel: 33;
readonly cqAlphaLevel: -1;
readonly denoiseLevel: 0;
readonly tileColsLog2: 0;
readonly tileRowsLog2: 0;
readonly speed: 6;
readonly subsample: 1;
readonly chromaDeltaQ: false;
readonly sharpness: 0;
readonly tune: 0;
};
readonly autoOptimize: {
readonly option: "cqLevel";
readonly min: 62;
readonly max: 0;
};
};
readonly oxipng: {
readonly name: "OxiPNG";
readonly extension: "png";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<{
decode: (buffer: Buffer | Uint8Array) => any;
}>;
readonly enc: () => Promise<{
encode: (buffer: Uint8ClampedArray | ArrayBuffer, width: number, height: number, opts: {
level: number;
}) => any;
}>;
readonly defaultEncoderOptions: {
readonly level: 2;
};
readonly autoOptimize: {
readonly option: "level";
readonly min: 6;
readonly max: 1;
};
};
};
export {};

View file

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

View file

@ -0,0 +1,9 @@
export declare function pathify(path: string): string;
export declare function instantiateEmscriptenWasm<T extends EmscriptenWasm.Module>(factory: EmscriptenWasm.ModuleFactory<T>, bytes: Uint8Array): Promise<T>;
export declare function dirname(url: string): string;
/**
* 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 __filename 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 declare function getModuleURL(url: string | undefined): string;

View file

@ -0,0 +1,31 @@
import { fileURLToPath, pathToFileURL } from "node:url";
function pathify(path) {
if (path.startsWith("file://")) {
path = fileURLToPath(path);
}
return path;
}
function instantiateEmscriptenWasm(factory, bytes) {
return factory({
// @ts-expect-error This is a valid Emscripten option, but the type definitions don't know about it
wasmBinary: bytes,
locateFile(file) {
return file;
}
});
}
function dirname(url) {
return url.substring(0, url.lastIndexOf("/"));
}
function getModuleURL(url) {
if (!url) {
return pathToFileURL(__filename).toString();
}
return url;
}
export {
dirname,
getModuleURL,
instantiateEmscriptenWasm,
pathify
};

View file

@ -0,0 +1,4 @@
/// <reference types="node" />
import type { ImageOutputFormat } from '../../../types.js';
import type { Operation } from './image.js';
export declare function processBuffer(buffer: Buffer, operations: Operation[], encoding: ImageOutputFormat, quality?: number): Promise<Uint8Array>;

View file

@ -0,0 +1,96 @@
import { cpus } from "node:os";
import { fileURLToPath } from "node:url";
import { isMainThread } from "node:worker_threads";
import { getModuleURL } from "./emscripten-utils.js";
import * as impl from "./impl.js";
import execOnce from "./utils/execOnce.js";
import WorkerPool from "./utils/workerPool.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))
);
});
function handleJob(params) {
switch (params.operation) {
case "decode":
return impl.decodeBuffer(params.buffer);
case "resize":
return impl.resize({
image: params.imageData,
width: params.width,
height: params.height
});
case "rotate":
return impl.rotate(params.imageData, params.numRotations);
case "encodeavif":
return impl.encodeAvif(params.imageData, { quality: params.quality });
case "encodejpeg":
return impl.encodeJpeg(params.imageData, { quality: params.quality });
case "encodepng":
return impl.encodePng(params.imageData);
case "encodewebp":
return impl.encodeWebp(params.imageData, { quality: params.quality });
default:
throw Error(`Invalid job "${params.operation}"`);
}
}
async function processBuffer(buffer, operations, encoding, quality) {
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
});
case "jpeg":
case "jpg":
return await worker.dispatchJob({
operation: "encodejpeg",
imageData,
quality
});
case "png":
return await worker.dispatchJob({
operation: "encodepng",
imageData
});
case "webp":
return await worker.dispatchJob({
operation: "encodewebp",
imageData,
quality
});
default:
throw Error(`Unsupported encoding format`);
}
}
if (!isMainThread) {
WorkerPool.useThisThreadAsWorker(handleJob);
}
export {
processBuffer
};

View file

@ -0,0 +1,14 @@
/// <reference types="node" />
import type { ImageOutputFormat } from '../../../types.js';
type RotateOperation = {
type: 'rotate';
numRotations: number;
};
type ResizeOperation = {
type: 'resize';
width?: number;
height?: number;
};
export type Operation = RotateOperation | ResizeOperation;
export declare function processBuffer(buffer: Buffer, operations: Operation[], encoding: ImageOutputFormat, quality?: number): Promise<Uint8Array>;
export {};

View file

@ -0,0 +1,27 @@
import * as impl from "./impl.js";
async function processBuffer(buffer, operations, encoding, quality) {
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 });
case "jpeg":
case "jpg":
return await impl.encodeJpeg(imageData, { quality });
case "png":
return await impl.encodePng(imageData);
case "webp":
return await impl.encodeWebp(imageData, { quality });
default:
throw Error(`Unsupported encoding format`);
}
}
export {
processBuffer
};

View file

@ -0,0 +1,9 @@
/// <reference types="node" />
export default class ImageData {
static from(input: ImageData): ImageData;
private _data;
width: number;
height: number;
get data(): Buffer;
constructor(data: Buffer | Uint8Array | Uint8ClampedArray, width: number, height: number);
}

View file

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

View file

@ -0,0 +1,22 @@
/// <reference types="node" />
import ImageData from './image_data.js';
export declare function decodeBuffer(_buffer: Buffer | Uint8Array): Promise<ImageData>;
export declare function rotate(image: ImageData, numRotations: number): Promise<ImageData>;
type ResizeOpts = {
image: ImageData;
} & {
width?: number;
height?: number;
};
export declare function resize({ image, width, height }: ResizeOpts): Promise<ImageData>;
export declare function encodeJpeg(image: ImageData, opts: {
quality?: number;
}): Promise<Uint8Array>;
export declare function encodeWebp(image: ImageData, opts: {
quality?: number;
}): Promise<Uint8Array>;
export declare function encodeAvif(image: ImageData, opts: {
quality?: number;
}): Promise<Uint8Array>;
export declare function encodePng(image: ImageData): Promise<Uint8Array>;
export {};

View file

@ -0,0 +1,112 @@
import { codecs as supportedFormats, preprocessors } from "./codecs.js";
import ImageData from "./image_data.js";
const DELAY_MS = 1e3;
let _promise;
function delayOnce(ms) {
if (!_promise) {
_promise = new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
return _promise;
}
function maybeDelay() {
const isAppleM1 = process.arch === "arm64" && process.platform === "darwin";
if (isAppleM1) {
return delayOnce(DELAY_MS);
}
return Promise.resolve();
}
async function decodeBuffer(_buffer) {
var _a;
const buffer = Buffer.from(_buffer);
const firstChunk = buffer.slice(0, 16);
const firstChunkString = Array.from(firstChunk).map((v) => String.fromCodePoint(v)).join("");
if (firstChunkString.includes("GIF")) {
throw Error(`GIF images are not supported, please install the @astrojs/image/sharp plugin`);
}
const key = (_a = Object.entries(supportedFormats).find(
([, { detectors }]) => detectors.some((detector) => detector.exec(firstChunkString))
)) == null ? void 0 : _a[0];
if (!key) {
throw Error(`Buffer has an unsupported format`);
}
const encoder = supportedFormats[key];
const mod = await encoder.dec();
const rgba = mod.decode(new Uint8Array(buffer));
return rgba;
}
async function rotate(image, numRotations) {
image = ImageData.from(image);
const m = await preprocessors["rotate"].instantiate();
return await m(image.data, image.width, image.height, { numRotations });
}
async function resize({ image, width, height }) {
image = ImageData.from(image);
const p = preprocessors["resize"];
const m = await p.instantiate();
await maybeDelay();
return await m(image.data, image.width, image.height, {
...p.defaultOptions,
width,
height
});
}
async function encodeJpeg(image, opts) {
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;
}
async function encodeWebp(image, opts) {
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;
}
async function encodeAvif(image, opts) {
image = ImageData.from(image);
const e = supportedFormats["avif"];
const m = await e.enc();
await maybeDelay();
const val = e.autoOptimize.min;
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;
}
async function encodePng(image) {
image = ImageData.from(image);
const e = supportedFormats["oxipng"];
const m = await e.enc();
await maybeDelay();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions
});
return r;
}
export {
decodeBuffer,
encodeAvif,
encodeJpeg,
encodePng,
encodeWebp,
resize,
rotate
};

View file

@ -0,0 +1,11 @@
var MozJpegColorSpace = /* @__PURE__ */ ((MozJpegColorSpace2) => {
MozJpegColorSpace2[MozJpegColorSpace2["GRAYSCALE"] = 1] = "GRAYSCALE";
MozJpegColorSpace2[MozJpegColorSpace2["RGB"] = 2] = "RGB";
MozJpegColorSpace2[MozJpegColorSpace2["YCbCr"] = 3] = "YCbCr";
return MozJpegColorSpace2;
})(MozJpegColorSpace || {});
var mozjpeg_enc_d_default = moduleFactory;
export {
MozJpegColorSpace,
mozjpeg_enc_d_default as default
};

View file

@ -0,0 +1,2 @@
declare var Module: (Module: any) => any;
export default Module;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
declare var Module: (Module: any) => any;
export default Module;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,10 @@
/**
* @param {Uint8Array} data
* @param {number} level
* @param {boolean} interlace
* @returns {Uint8Array}
*/
export declare function optimise(data: any, level: any, interlace: any): any;
declare function init(input: any): Promise<WebAssembly.Exports>;
export default init;
export declare function cleanup(): void;

View file

@ -0,0 +1,89 @@
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);
}
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;
}
var squoosh_oxipng_default = init;
function cleanup() {
wasm = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
export {
cleanup,
squoosh_oxipng_default as default,
optimise
};

Binary file not shown.

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,15 @@
/**
* @param {Uint8Array} data
* @param {number} width
* @param {number} height
* @returns {Uint8Array}
*/
export declare function encode(data: any, width: any, height: any): any;
/**
* @param {Uint8Array} data
* @returns {ImageData}
*/
export declare function decode(data: any): any;
declare function init(input: any): Promise<WebAssembly.Exports>;
export default init;
export declare function cleanup(): void;

View file

@ -0,0 +1,138 @@
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(void 0);
heap.push(void 0, 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);
}
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;
}
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;
}
var squoosh_png_default = init;
function cleanup() {
wasm = null;
cachegetUint8ClampedMemory0 = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
export {
cleanup,
decode,
squoosh_png_default as default,
encode
};

Binary file not shown.

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,15 @@
/**
* @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 declare function resize(input_image: any, input_width: any, input_height: any, output_width: any, output_height: any, typ_idx: any, premultiply: any, color_space_conversion: any): any;
declare function init(input: any): Promise<WebAssembly.Exports>;
export default init;
export declare function cleanup(): void;

View file

@ -0,0 +1,95 @@
let wasm;
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
let cachegetUint8ClampedMemory0 = null;
function getUint8ClampedMemory0() {
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
}
return cachegetUint8ClampedMemory0;
}
function getClampedArrayU8FromWasm0(ptr, len) {
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
}
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;
}
var squoosh_resize_default = init;
function cleanup() {
wasm = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
export {
cleanup,
squoosh_resize_default as default,
resize
};

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

File diff suppressed because one or more lines are too long

Binary file not shown.

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: Buffer;
export default _default;

View file

@ -0,0 +1,4 @@
var rotate_wasm_default = Buffer.from("AGFzbQEAAAABDAJgAn9/AGADf39/AAMGBQAAAAABBQMBABAGEQJ/AEGAgMAAC38AQYCAwAALBy4EBm1lbW9yeQIABnJvdGF0ZQAECl9fZGF0YV9lbmQDAAtfX2hlYXBfYmFzZQMBCpsJBUkBAX8gACABbCIAQf////8DcSICBEBBCCEBIABBAnRBCGohAANAIAAgASgCADYCACABQQRqIQEgAEEEaiEAIAJBf2oiAg0ACwsLzQMBFH8gAUECdCERIAAgAWwiDEECdEEEaiESA0ACQAJAAkACQCAEQQFxRQRAIAMgAU8NAiADQQFqIQgMAQsgA0EPaiICIANJIggNASACIAFJIgVFDQEgASADQRBqIAgbIAEgBRshCCACIQMLIAEgA0EQaiICIAIgAUsbIQ0gA0F/cyETIBIgA0ECdGshFEEAIQVBACEOA0ACQAJAIA5FBEAgBSAASQ0BQQEhBAwGCyAAIAVBEGogBUEPaiICIAVJIgcbIAAgAiAASRshBUEBIQQgByACIABPcg0FDAELIAUiAkEBaiEFC0EBIQ4gAyANTw0AIAAgAkEQaiIPIAAgD0kbQQJ0IAJBAnRrIRUgEyABIAJsaiEHIBQgASACQQFqbEECdGohCSADIQoDQCAAIApsIgYgAmoiBEEQaiAAIAZqIA8gAEkbIgYgBEkgDCAGSXINAyAEIAZHBEAgBEECdEEIaiELIBUhBiAHIRAgCSEEA0AgDCABIBBqIhBNDQUgBCALKAIANgIAIAQgEWohBCALQQRqIQsgBkF8aiIGDQALCyAHQX9qIQcgCUF8aiEJIA0gCkEBaiIKRw0ACwwACwALDwsACyAIIQMMAAsAC1MBAX8CQCAAIAFsQQJ0IgJBCGoiAEEIRg0AIAAgAmpBfGohAEEAIQEDQCABIAJGDQEgACABQQhqKAIANgIAIABBfGohACACIAFBBGoiAUcNAAsLC9oDARN/IABBf2ohEEEAIAFBAnRrIREgACABbCIMQQJ0QQhqIRIDQAJAAkACQAJAIARBAXFFBEAgAyABTw0CIANBAWohCQwBCyADQQ9qIgIgA0kiCQ0BIAIgAUkiBUUNASABIANBEGogCRsgASAFGyEJIAIhAwsgASADQRBqIgIgAiABSxshDSASIANBAnRqIRNBACEFQQAhBgNAAkACQCAGQQFxRQRAIAUgAEkNAUEBIQQMBgsgACAFQRBqIAVBD2oiAiAFSSIIGyAAIAIgAEkbIQVBASEEIAggAiAAT3INBQwBCyAFIgJBAWohBQtBASEGIAMgDU8NACAAIAJBEGoiDiAAIA5JG0ECdCACQQJ0ayEUIAMgASAAIAJrbGohCCATIAEgECACa2xBAnRqIQogAyELA0AgACALbCIHIAJqIgRBEGogACAHaiAOIABJGyIHIARJIAwgB0lyDQMgBCAHRwRAIARBAnRBCGohBiAUIQcgCCEPIAohBANAIAwgDyABayIPTQ0FIAQgBigCADYCACAEIBFqIQQgBkEEaiEGIAdBfGoiBw0ACwtBASEGIAhBAWohCCAKQQRqIQogDSALQQFqIgtHDQALDAALAAsPCwALIAkhAwwACwALUAACQAJAAkACQCACQbMBTARAIAJFDQIgAkHaAEcNASAAIAEQAQ8LIAJBtAFGDQIgAkGOAkYNAwsACyAAIAEQAA8LIAAgARACDwsgACABEAMLAE0JcHJvZHVjZXJzAghsYW5ndWFnZQEEUnVzdAAMcHJvY2Vzc2VkLWJ5AQVydXN0Yx0xLjQ3LjAgKDE4YmY2YjRmMCAyMDIwLTEwLTA3KQ==", "base64");
export {
rotate_wasm_default as default
};

View file

@ -0,0 +1 @@
export default function execOnce<T extends (...args: any[]) => ReturnType<T>>(fn: T): T;

View file

@ -0,0 +1,14 @@
function execOnce(fn) {
let used = false;
let result;
return (...args) => {
if (!used) {
used = true;
result = fn(...args);
}
return result;
};
}
export {
execOnce as default
};

View file

@ -0,0 +1,22 @@
/// <reference types="node" />
import { Worker } from 'worker_threads';
interface Job<I> {
msg: I;
resolve: (result: any) => void;
reject: (reason: any) => void;
}
export default class WorkerPool<I, O> {
numWorkers: number;
jobQueue: TransformStream<Job<I>, Job<I>>;
workerQueue: TransformStream<Worker, Worker>;
done: Promise<void>;
constructor(numWorkers: number, workerFile: string);
_readLoop(): Promise<void>;
_nextWorker(): Promise<Worker>;
_terminateAll(): Promise<void>;
join(): Promise<void>;
dispatchJob(msg: I): Promise<O>;
private jobPromise;
static useThisThreadAsWorker<I, O>(cb: (msg: I) => O): void;
}
export {};

View file

@ -0,0 +1,95 @@
import { parentPort, Worker } from "worker_threads";
function uuid() {
return Array.from({ length: 16 }, () => Math.floor(Math.random() * 256).toString(16)).join("");
}
class WorkerPool {
constructor(numWorkers, workerFile) {
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(() => {
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) {
return new Promise((resolve, reject) => {
const writer = this.jobQueue.writable.getWriter();
writer.write({ msg, resolve, reject });
writer.releaseLock();
});
}
jobPromise(worker, msg) {
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) {
parentPort.on("message", async (data) => {
const { msg, id } = data;
try {
const result = await cb(msg);
parentPort.postMessage({ result, id });
} catch (e) {
parentPort.postMessage({ error: e.message, id });
}
});
}
}
export {
WorkerPool as default
};

View file

@ -0,0 +1,4 @@
var webp_enc_d_default = moduleFactory;
export {
webp_enc_d_default as default
};

View file

@ -0,0 +1,2 @@
declare var Module: (Module: any) => any;
export default Module;

File diff suppressed because it is too large Load diff

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more