0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-13 22:11:20 -05:00
astro/packages/webapi/run/build.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

225 lines
6.7 KiB
JavaScript
Raw Normal View History

import { rollup } from 'rollup'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import { posix as path } from 'node:path'
import { createRequire } from 'node:module'
2022-03-07 16:37:50 -05:00
import {
readFile as nodeReadFile,
rename,
rm,
writeFile,
} from 'node:fs/promises'
import { default as MagicString } from 'magic-string'
import { default as alias } from '@rollup/plugin-alias'
import { default as inject } from '@rollup/plugin-inject'
import { default as typescript } from '@rollup/plugin-typescript'
const readFileCache = Object.create(null)
const require = createRequire(import.meta.url)
2022-03-07 16:37:50 -05:00
const readFile = (/** @type {string} */ id) =>
readFileCache[id] || (readFileCache[id] = nodeReadFile(id, 'utf8'))
const pathToDOMException = path.resolve('src', 'lib', 'DOMException.js')
Move from yarn to pnpm (#2455) * chore: `yarn` => `pnpm` * docs: `yarn` => `pnpm` * chore(ci): yarn => pnpm * chore(ci): update pnpm cache path * fix: add missing deps * fix: add missing deps * test: add package.json to all test fixtures * chore: improve hoisting behavior * chore: move turbo into package.json * chore: update npmrc * fix: add missing `debug` dependency * chore: remove prepare script * test: fix new tests * fix: fully resolve renderer paths and `astro/internal` path * chore: update lockfile * chore: remove log * fix: resolve renderers in vite-plugin-jsx * fix: prefer public-hoist-pattern to shamefully-hoist * chore: ignore @babel/core peer warning * chore: update dependencies * test: add autoprefixer as explicit dep * chore: update `.npmrc` file in examples * chore: update dependencies * fix: resolve renderer dependencies in static build * fix: static build renderer resolution * chore: fix smoke tests * chore: hoist autoprefixer * chore: update lockfile * attempt: use full file:// path on Windows * attempt: use astro/internal * attempt: optimize astro/internal * attempt: expose ./internal.js * chore: add missing package.json files * attempt: resolve astro/internal path * chore: tidy package.json * chore: update lockfile * chore: update deps * chore: update deps * chore: yarn -> pnpm * attempt: explicit /@fs urls * attempt: explicit /@fs urls * chore: update all examples for pnpm * chore: fix hoisting for with-vite-plugin-pwa * chore(ci): fix sharp install * chore: update with-vite-plugin-pwa example * fix: pin vite-plugin-pwa to 0.11.11 * fix: add workbox-window to vite-plugin-pwa deps * refactor: use pnpm update --recursive Co-authored-by: JuanM04 <me@juanm04.com> * chore: yarn => pnpm * chore: yarn => pnpm * fix: update smoke test to skip examples which don't work in static build * update lockfile * chore: update .npmrc files * chore: update lockfile * fix: smoke script * chore: update .npmrc file * fix: return to shamefully-hoist (shamefully) * chore: update lockfile * fix(smoke): ignore scripts for smoke tests * fix: update example to disable renderers * chore: bump version * chore(ci): fix smoke tests * attempt: disable --frozen-lockfile for smoke tests * chore: update smoke test * chore: fix rebase issue * chore: update lockfile * fix: smoke tests * fix(ci): run external smoke tests first * fix(ci): run syntax * chore: update lockfile * fix(ci): ensure submodules are up-to-date * fix(ci): ensure submodules are up-to-date * chore: update lockfile * chore: update for webapi * chore: silence node:* warnings * chore: update deps * fix(ci): persist generated webapi assets * fix(ci): webapi build script * chore(ci): remove custom node caching * chore: keep turbo.json * chore: update turbo, ignore create-astro * chore: update deps * fix(ci): test command * chore(ci): update test script Co-authored-by: JuanM04 <me@juanm04.com>
2022-03-08 16:46:11 -05:00
const pathToEventTargetShim = path.resolve('node_modules', 'event-target-shim', 'index.mjs')
const pathToStructuredClone = path.resolve('node_modules', '@ungap', 'structured-clone', 'esm', 'index.js')
const plugins = [
typescript({
tsconfig: './tsconfig.json',
}),
alias({
entries: [
{ find: '@ungap/structured-clone', replacement: pathToStructuredClone },
{ find: 'event-target-shim', replacement: pathToEventTargetShim },
2022-03-07 16:37:50 -05:00
{
find: 'event-target-shim/dist/event-target-shim.js',
replacement: pathToEventTargetShim,
},
{
find: 'event-target-shim/dist/event-target-shim.umd.js',
replacement: pathToEventTargetShim,
},
{ find: 'node-domexception', replacement: pathToDOMException },
],
}),
nodeResolve({
2022-03-07 16:37:50 -05:00
dedupe: ['net', 'node:net'],
}),
inject({
// import { Promise as P } from 'es6-promise'
// P: [ 'es6-promise', 'Promise' ],
2022-03-07 16:37:50 -05:00
AbortController: [
'abort-controller/dist/abort-controller.mjs',
'AbortController',
],
Blob: ['fetch-blob/from.js', 'Blob'],
DOMException: [pathToDOMException, 'DOMException'],
Document: ['./Document', 'Document'],
Element: ['./Element', 'Element'],
Event: ['event-target-shim', 'Event'],
EventTarget: ['event-target-shim', 'EventTarget'],
defineEventAttribute: ['event-target-shim', 'defineEventAttribute'],
HTMLElement: ['./Element', 'HTMLElement'],
HTMLImageElement: ['./Element', 'HTMLImageElement'],
HTMLUnknownElement: ['./Element', 'HTMLUnknownElement'],
MediaQueryList: ['./MediaQueryList', 'MediaQueryList'],
Node: ['./Node', 'Node'],
ReadableStream: [
'web-streams-polyfill/dist/ponyfill.es6.mjs',
'ReadableStream',
],
ShadowRoot: ['./Node', 'ShadowRoot'],
Window: ['./Window', 'Window'],
'globalThis.ReadableStream': [
'web-streams-polyfill/dist/ponyfill.es6.mjs',
'ReadableStream',
],
}),
{
async load(id) {
const pathToEsm = id
const pathToMap = `${pathToEsm}.map`
const code = await readFile(pathToEsm, 'utf8')
const indexes = []
const replacements = [
// remove unused imports
2022-03-07 16:37:50 -05:00
[/(^|\n)import\s+[^']+'node:(buffer|fs|path|worker_threads)'/g, ``],
[/const \{ stat \} = fs/g, ``],
// remove unused polyfill utils
2022-03-07 16:37:50 -05:00
[/\nif \(\s*typeof Global[\W\w]+?\n\}/g, ``],
[/\nif \(\s*typeof window[\W\w]+?\n\}/g, ``],
[/\nif \(!globalThis\.ReadableStream\) \{[\W\w]+?\n\}/g, ``],
[/\nif \(typeof SymbolPolyfill[\W\w]+?\n\}/g, ``],
// remove unused polyfills
2022-03-07 16:37:50 -05:00
[/\nconst globals = getGlobals\(\);/g, ``],
[/\nconst queueMicrotask = [\W\w]+?\n\}\)\(\);/g, ``],
[/\nconst NativeDOMException =[^;]+;/g, ``],
[
/\nconst SymbolPolyfill\s*=[^;]+;/g,
'\nconst SymbolPolyfill = Symbol;',
],
[
/\n(const|let) DOMException[^;]*;/g,
`let DOMException$1=DOMException`,
],
[/\nconst DOMException = globalThis.DOMException[\W\w]+?\}\)\(\)/g, ``],
[/\nimport DOMException from 'node-domexception'/g, ``],
// use shared AbortController methods
2022-03-07 16:37:50 -05:00
[/ new DOMException\$1/g, `new DOMException`],
[/ from 'net'/g, `from 'node:net'`],
[/ throw createInvalidStateError/g, `throw new DOMException`],
[/= createAbortController/g, `= new AbortController`],
[/\nconst queueMicrotask = [\W\w]+?\n\}\)\(\)\;/g, ``],
// remove Body.prototype.buffer deprecation notice
2022-03-07 16:37:50 -05:00
[/\nBody\.prototype\.buffer[^\n]+/g, ``],
// remove Body.prototype.data deprecation notice
2022-03-07 16:37:50 -05:00
[/\n data: \{get: deprecate[\W\w]+?\)\}/g, ``],
]
for (const [replacee, replacer] of replacements) {
replacee.index = 0
let replaced = null
while ((replaced = replacee.exec(code)) !== null) {
const leadIndex = replaced.index
const tailIndex = replaced.index + replaced[0].length
2022-03-07 16:37:50 -05:00
indexes.unshift([leadIndex, tailIndex, replacer])
}
}
if (indexes.length) {
const magicString = new MagicString(code)
2022-03-07 16:37:50 -05:00
indexes.sort(([leadOfA], [leadOfB]) => leadOfA - leadOfB)
for (const [leadIndex, tailindex, replacer] of indexes) {
magicString.overwrite(leadIndex, tailindex, replacer)
}
2022-03-07 16:37:50 -05:00
const magicMap = magicString.generateMap({
source: pathToEsm,
file: pathToMap,
includeContent: true,
})
const modifiedEsm = magicString.toString()
const modifiedMap = magicMap.toString()
return { code: modifiedEsm, map: modifiedMap }
}
},
},
]
async function build() {
const configs = [
{
inputOptions: {
input: 'src/polyfill.ts',
plugins: plugins,
onwarn(warning, warn) {
if (warning.code !== 'UNRESOLVED_IMPORT') warn(warning)
},
},
outputOptions: {
inlineDynamicImports: true,
file: 'mod.js',
format: 'esm',
sourcemap: true,
},
},
]
for (const config of configs) {
const bundle = await rollup(config.inputOptions)
// or write the bundle to disk
await bundle.write(config.outputOptions)
// closes the bundle
await bundle.close()
// delete the lib directory
await rm('lib', { force: true, recursive: true })
await rm('exclusions.d.ts', { force: true, recursive: true })
await rm('exclusions.d.ts.map', { force: true, recursive: true })
await rm('inheritence.d.ts', { force: true, recursive: true })
await rm('inheritence.d.ts.map', { force: true, recursive: true })
await rm('polyfill.d.ts.map', { force: true, recursive: true })
await rm('polyfill.js.map', { force: true, recursive: true })
await rm('polyfill.js', { force: true, recursive: true })
await rm('ponyfill.d.ts', { force: true, recursive: true })
await rm('ponyfill.d.ts.map', { force: true, recursive: true })
await rm('ponyfill.js.map', { force: true, recursive: true })
await rm('ponyfill.js', { force: true, recursive: true })
await rename('polyfill.d.ts', 'mod.d.ts')
const modDTS = await readFile('./mod.d.ts')
2022-03-07 16:37:50 -05:00
writeFile(
'mod.d.ts',
modDTS
.replace('\n//# sourceMappingURL=polyfill.d.ts.map', '')
.replace('ponyfill.js', 'mod.js')
)
writeFile(
'apply.js',
`import { polyfill } from './mod.js'\n\nexport * from './mod.js'\n\npolyfill(globalThis)\n`
)
}
}
build()