astro/scripts/cmd/build.js
Erika 694918a56b
Implement RFC "A core story for images" (#6344)
* feat(assets): Add Vite plugin

* feat(images): Set up Image component

* fix(types): Attempt to fix type generation

* Revert "fix(types): Attempt to fix type generation"

This reverts commit 063aa276e2.

* fix(image): Fix image types causing build to fail

* feat(image): Implement client side part

* feat(services): Allow arbitrary transforms parameters

* fix(image): Fix paths and types

* config(types): Update config types to provide completions for available services

* feat(image): Add serving in dev

* feat(image): Improve type error messages

* refactor(image): Move sharp's parseParams to baseService

* refactor(image): Skip work in dev for remote servies

* feat(image): Add support for remote images

* feat(image): Add squoosh service

* chore: update export map

* refactor(image): Abstract attributes handling by services

* config(vercel): Remove test image service

* feat(image): Support for relative images in Markdown (WIP)

* feat(images): Add support for relative images in Markdown

* feat(image): Update with RFC feedback

* fix(image): Fix alt error on getImage

* feat(image): Add support for assets validation through content collections

* feat(image): Remove validateTransform

* feat(image): Move to assets folder

* fix(image): Fix package exports

* feat(image): Add static imports references to virtual moduel

* fix(image): Fix images from content collections not working when embedded

* chore: lockfile

* fix(markdown): Fix type

* fix(images): Flag enhanced images behing an experimental flag

* config(example): Update images example conifg

* fix(image): Fix types

* fix(image): Fix asset type for strict, allow arbritary input and output formats

* chore: fix example check

* feat(image): Emit assets for ESM imported images

* Add initial core image tests (#6381)

* feat(images): Make frontmatter extraction more generic than images for future

* feat(image): Add support for building

* fix(image): Fix types

* fix(images): Fix compatibility with image integration

* feat(images): Cuter generation stats

* fix(images): Globals are unsafe, it turns out

* fix(images): Only generate images if flag is enabled

* fix(images): Only create `addStaticImage` in build

* feat(images): Add SSR endpoint

* fix(images): Only inject route in SSR

* Add tests for SSR

* Remove console.log

* Updated lockfile

* rename to satisfy the link gods

* skip build tests for now

* fix(images): Fix WASM files not being copied in dev

* feat(images): Add quality presets

* fix build tests running

* Remove console.log

* Add tests for getImage

* Test local services

* Test the content collections API

* Add tests for quality

* Skipping content collections test

* feat(image): Add support for `~/assets` alias

* test(image): Add tests for aliases in dev

* Fix windows + content collections

* test(image): Add tests for aliased images and images in Markdown

* Fix markdown images being built

* Should be posix join

* Use the optimized image

* fix test

* Fixes windows smoke

* fix(image): Nits

* feat(images): Add automatic update for `env.d.ts` when experimental images are enabled

* fix(images): Revert env.d.ts change if the user opted-out of the experimental image support

* chore: remove bad image example project

* feat(image): Rename `experimental.images` to `experimental.assets`

* fix(images): Remove unused code in MDX integration

* chore: Remove unrelated change

* fix(images): Remove export from astro/components

* Fix, esm import on Win

* test(images): Add test for format

* fix(images): Add `client-image.d.ts` to export map

* chore: changeset

* fix(images): Adjust with feedback, no more automatic refine, asset() -> image()

* fix(images): Fix types

* fix(images): Remove unnecessary spread

* fix(images): Better types for parseUrl and transform

* fix(images): Fix types

* fix(images): Adjust from feedback

* fix(images): Pass width and height through getHTMLAttributes even if they're not added by the uesr

* fix(images): Recusirsively extract frontmatter assets

* fix(images): Use a reduce instead

* feat(images): Add support for data: URIs

* chore: changeset

* docs(images): Misc docs fixes

* Update .changeset/gold-rocks-cry.md

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

* Update .changeset/gold-rocks-cry.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* Update packages/astro/src/@types/astro.ts

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

* Update packages/astro/src/assets/services/service.ts

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

* Update packages/astro/src/assets/services/service.ts

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

* Update packages/astro/src/assets/services/service.ts

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

* Update packages/astro/src/assets/types.ts

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

* Update packages/astro/src/assets/types.ts

Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>

---------

Co-authored-by: Matthew Phillips <matthew@skypack.dev>
Co-authored-by: Matthew Phillips <matthew@matthewphillips.info>
Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2023-03-07 16:12:21 +01:00

130 lines
3.3 KiB
JavaScript

import { deleteAsync } from 'del';
import esbuild from 'esbuild';
import { copy } from 'esbuild-plugin-copy';
import { promises as fs } from 'fs';
import { dim, green, red, yellow } from 'kleur/colors';
import glob from 'tiny-glob';
import svelte from '../utils/svelte-plugin.js';
import prebuild from './prebuild.js';
/** @type {import('esbuild').BuildOptions} */
const defaultConfig = {
minify: false,
format: 'esm',
platform: 'node',
target: 'node16',
sourcemap: false,
sourcesContent: false,
};
const dt = new Intl.DateTimeFormat('en-us', {
hour: '2-digit',
minute: '2-digit',
});
function getPrebuilds(isDev, args) {
let prebuilds = [];
while (args.includes('--prebuild')) {
let idx = args.indexOf('--prebuild');
prebuilds.push(args[idx + 1]);
args.splice(idx, 2);
}
if (prebuilds.length && isDev) {
prebuilds.unshift('--no-minify');
}
return prebuilds;
}
export default async function build(...args) {
const config = Object.assign({}, defaultConfig);
const isDev = args.slice(-1)[0] === 'IS_DEV';
const prebuilds = getPrebuilds(isDev, args);
const patterns = args
.filter((f) => !!f) // remove empty args
.map((f) => f.replace(/^'/, '').replace(/'$/, '')); // Needed for Windows: glob strings contain surrounding string chars??? remove these
let entryPoints = [].concat(
...(await Promise.all(
patterns.map((pattern) => glob(pattern, { filesOnly: true, absolute: true }))
))
);
const noClean = args.includes('--no-clean-dist');
const bundle = args.includes('--bundle');
const forceCJS = args.includes('--force-cjs');
const copyWASM = args.includes('--copy-wasm');
const {
type = 'module',
version,
dependencies = {},
} = await fs.readFile('./package.json').then((res) => JSON.parse(res.toString()));
// expose PACKAGE_VERSION on process.env for CLI utils
config.define = { 'process.env.PACKAGE_VERSION': JSON.stringify(version) };
const format = type === 'module' && !forceCJS ? 'esm' : 'cjs';
const outdir = 'dist';
if (!noClean) {
await clean(outdir);
}
if (!isDev) {
await esbuild.build({
...config,
bundle,
external: bundle ? Object.keys(dependencies) : undefined,
entryPoints,
outdir,
outExtension: forceCJS ? { '.js': '.cjs' } : {},
format,
});
return;
}
const builder = await esbuild.build({
...config,
watch: {
onRebuild(error, result) {
if (prebuilds.length) {
prebuild(...prebuilds);
}
const date = dt.format(new Date());
if (error || (result && result.errors.length)) {
console.error(dim(`[${date}] `) + red(error || result.errors.join('\n')));
} else {
if (result.warnings.length) {
console.log(
dim(`[${date}] `) + yellow('⚠ updated with warnings:\n' + result.warnings.join('\n'))
);
}
console.log(dim(`[${date}] `) + green('✔ updated'));
}
},
},
entryPoints,
outdir,
format,
plugins: [
svelte({ isDev }),
...(copyWASM
? [
copy({
resolveFrom: 'cwd',
assets: {
from: ['./src/assets/services/vendor/squoosh/**/*.wasm'],
to: ['./dist/assets/services/vendor/squoosh'],
},
}),
]
: []),
],
});
process.on('beforeExit', () => {
builder.stop && builder.stop();
});
}
async function clean(outdir) {
return deleteAsync([`${outdir}/**`, `!${outdir}/**/*.d.ts`]);
}