From 3dc1ca2fac8d9965cc5085a5d09e72ed87b4281a Mon Sep 17 00:00:00 2001 From: Erika <3019731+Princesseuh@users.noreply.github.com> Date: Thu, 27 Jul 2023 18:24:39 +0200 Subject: [PATCH] feat: remove webapi in favor of a smaller polyfill (#7840) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: remove webapi in favor of a smaller polyfill * test: remove old test * test: 🤦‍♀️ * chore: changeset --- .changeset/spicy-eels-rush.md | 8 + .eslintignore | 1 - .prettierignore | 1 - benchmark/packages/timer/package.json | 1 - benchmark/packages/timer/src/server.ts | 7 +- package.json | 1 - packages/astro/package.json | 1 - packages/astro/src/core/app/node.ts | 1 + packages/astro/src/core/polyfill.ts | 23 +- packages/astro/test/custom-elements.test.js | 70 ---- .../fixtures/custom-elements/astro.config.mjs | 6 - .../my-component-lib/hydration-polyfill.js | 1 - .../custom-elements/my-component-lib/index.js | 31 -- .../my-component-lib/package.json | 13 - .../my-component-lib/polyfill.js | 2 - .../my-component-lib/server.js | 30 -- .../custom-elements/my-component-lib/shim.js | 28 -- .../fixtures/custom-elements/package.json | 9 - .../src/components/my-element.js | 13 - .../custom-elements/src/pages/ctr.astro | 16 - .../custom-elements/src/pages/index.astro | 15 - .../custom-elements/src/pages/nested.astro | 11 - .../custom-elements/src/pages/nossr.astro | 14 - packages/astro/test/test-utils.js | 6 - packages/integrations/netlify/package.json | 1 - .../netlify/src/netlify-functions.ts | 6 +- packages/integrations/node/package.json | 1 - packages/integrations/node/src/server.ts | 8 +- packages/integrations/vercel/package.json | 1 - .../vercel/src/serverless/entrypoint.ts | 6 +- packages/webapi/.gitignore | 2 - packages/webapi/CHANGELOG.md | 109 ------ packages/webapi/LICENSE | 27 -- packages/webapi/README.md | 155 --------- packages/webapi/apply.js | 5 - packages/webapi/mod.d.ts | 13 - packages/webapi/package.json | 97 ------ packages/webapi/run/build.js | 224 ------------ packages/webapi/src/exclusions.ts | 57 --- packages/webapi/src/inheritance.ts | 26 -- packages/webapi/src/lib/Alert.ts | 3 - packages/webapi/src/lib/AnimationFrame.ts | 41 --- .../src/lib/CanvasRenderingContext2D.ts | 222 ------------ packages/webapi/src/lib/CharacterData.ts | 45 --- .../webapi/src/lib/CustomElementRegistry.ts | 92 ----- packages/webapi/src/lib/CustomEvent.ts | 26 -- packages/webapi/src/lib/DOMException.ts | 40 --- packages/webapi/src/lib/Document.ts | 197 ----------- packages/webapi/src/lib/Element.ts | 166 --------- packages/webapi/src/lib/HTMLCanvasElement.ts | 69 ---- packages/webapi/src/lib/HTMLImageElement.ts | 16 - packages/webapi/src/lib/IdleCallback.ts | 41 --- packages/webapi/src/lib/Image.ts | 15 - packages/webapi/src/lib/ImageData.ts | 111 ------ packages/webapi/src/lib/MediaQueryList.ts | 40 --- packages/webapi/src/lib/Node.ts | 192 ----------- packages/webapi/src/lib/Observer.ts | 41 --- packages/webapi/src/lib/OffscreenCanvas.ts | 102 ------ packages/webapi/src/lib/Storage.ts | 67 ---- packages/webapi/src/lib/StyleSheet.ts | 24 -- packages/webapi/src/lib/Timeout.ts | 30 -- packages/webapi/src/lib/TreeWalker.ts | 67 ---- packages/webapi/src/lib/Window.ts | 49 --- packages/webapi/src/lib/structuredClone.ts | 4 - packages/webapi/src/lib/utils.ts | 61 ---- packages/webapi/src/polyfill.ts | 325 ------------------ packages/webapi/src/ponyfill.ts | 148 -------- packages/webapi/src/types.d.ts | 4 - packages/webapi/test/basic.js | 87 ----- packages/webapi/test/characterdata.js | 42 --- packages/webapi/test/elements.js | 70 ---- packages/webapi/test/fetch.js | 40 --- packages/webapi/test/imagedata.js | 54 --- packages/webapi/test/internals.js | 26 -- packages/webapi/test/media.js | 20 -- packages/webapi/test/offscreencanvas.js | 39 --- packages/webapi/test/options.js | 44 --- packages/webapi/test/storage.js | 32 -- packages/webapi/test/structuredclone.js | 28 -- packages/webapi/test/urlpattern.js | 19 - packages/webapi/tsconfig.json | 15 - scripts/package.json | 1 - scripts/smoke/cleanup.js | 5 +- scripts/smoke/index.js | 5 +- 84 files changed, 37 insertions(+), 3775 deletions(-) create mode 100644 .changeset/spicy-eels-rush.md delete mode 100644 packages/astro/test/custom-elements.test.js delete mode 100644 packages/astro/test/fixtures/custom-elements/astro.config.mjs delete mode 100644 packages/astro/test/fixtures/custom-elements/my-component-lib/hydration-polyfill.js delete mode 100644 packages/astro/test/fixtures/custom-elements/my-component-lib/index.js delete mode 100644 packages/astro/test/fixtures/custom-elements/my-component-lib/package.json delete mode 100644 packages/astro/test/fixtures/custom-elements/my-component-lib/polyfill.js delete mode 100644 packages/astro/test/fixtures/custom-elements/my-component-lib/server.js delete mode 100644 packages/astro/test/fixtures/custom-elements/my-component-lib/shim.js delete mode 100644 packages/astro/test/fixtures/custom-elements/package.json delete mode 100644 packages/astro/test/fixtures/custom-elements/src/components/my-element.js delete mode 100644 packages/astro/test/fixtures/custom-elements/src/pages/ctr.astro delete mode 100644 packages/astro/test/fixtures/custom-elements/src/pages/index.astro delete mode 100644 packages/astro/test/fixtures/custom-elements/src/pages/nested.astro delete mode 100644 packages/astro/test/fixtures/custom-elements/src/pages/nossr.astro delete mode 100644 packages/webapi/.gitignore delete mode 100644 packages/webapi/CHANGELOG.md delete mode 100644 packages/webapi/LICENSE delete mode 100644 packages/webapi/README.md delete mode 100644 packages/webapi/apply.js delete mode 100644 packages/webapi/mod.d.ts delete mode 100644 packages/webapi/package.json delete mode 100644 packages/webapi/run/build.js delete mode 100644 packages/webapi/src/exclusions.ts delete mode 100644 packages/webapi/src/inheritance.ts delete mode 100644 packages/webapi/src/lib/Alert.ts delete mode 100644 packages/webapi/src/lib/AnimationFrame.ts delete mode 100644 packages/webapi/src/lib/CanvasRenderingContext2D.ts delete mode 100644 packages/webapi/src/lib/CharacterData.ts delete mode 100644 packages/webapi/src/lib/CustomElementRegistry.ts delete mode 100644 packages/webapi/src/lib/CustomEvent.ts delete mode 100644 packages/webapi/src/lib/DOMException.ts delete mode 100644 packages/webapi/src/lib/Document.ts delete mode 100644 packages/webapi/src/lib/Element.ts delete mode 100644 packages/webapi/src/lib/HTMLCanvasElement.ts delete mode 100644 packages/webapi/src/lib/HTMLImageElement.ts delete mode 100644 packages/webapi/src/lib/IdleCallback.ts delete mode 100644 packages/webapi/src/lib/Image.ts delete mode 100644 packages/webapi/src/lib/ImageData.ts delete mode 100644 packages/webapi/src/lib/MediaQueryList.ts delete mode 100644 packages/webapi/src/lib/Node.ts delete mode 100644 packages/webapi/src/lib/Observer.ts delete mode 100644 packages/webapi/src/lib/OffscreenCanvas.ts delete mode 100644 packages/webapi/src/lib/Storage.ts delete mode 100644 packages/webapi/src/lib/StyleSheet.ts delete mode 100644 packages/webapi/src/lib/Timeout.ts delete mode 100644 packages/webapi/src/lib/TreeWalker.ts delete mode 100644 packages/webapi/src/lib/Window.ts delete mode 100644 packages/webapi/src/lib/structuredClone.ts delete mode 100644 packages/webapi/src/lib/utils.ts delete mode 100644 packages/webapi/src/polyfill.ts delete mode 100644 packages/webapi/src/ponyfill.ts delete mode 100644 packages/webapi/src/types.d.ts delete mode 100644 packages/webapi/test/basic.js delete mode 100644 packages/webapi/test/characterdata.js delete mode 100644 packages/webapi/test/elements.js delete mode 100644 packages/webapi/test/fetch.js delete mode 100644 packages/webapi/test/imagedata.js delete mode 100644 packages/webapi/test/internals.js delete mode 100644 packages/webapi/test/media.js delete mode 100644 packages/webapi/test/offscreencanvas.js delete mode 100644 packages/webapi/test/options.js delete mode 100644 packages/webapi/test/storage.js delete mode 100644 packages/webapi/test/structuredclone.js delete mode 100644 packages/webapi/test/urlpattern.js delete mode 100644 packages/webapi/tsconfig.json diff --git a/.changeset/spicy-eels-rush.md b/.changeset/spicy-eels-rush.md new file mode 100644 index 000000000000..672de5c7d3f0 --- /dev/null +++ b/.changeset/spicy-eels-rush.md @@ -0,0 +1,8 @@ +--- +'astro': major +'@astrojs/netlify': major +'@astrojs/vercel': major +'@astrojs/node': major +--- + +Reduced the amount of polyfills provided by Astro. Astro will no longer provide (no-op) polyfills for several web apis such as HTMLElement, Image or Document. If you need access to those APIs on the server, we recommend using more proper polyfills available on npm. diff --git a/.eslintignore b/.eslintignore index f5104aedd5b4..2b3b5903586c 100644 --- a/.eslintignore +++ b/.eslintignore @@ -2,7 +2,6 @@ packages/**/*.min.js packages/**/dist/**/* packages/**/fixtures/**/* -packages/webapi/**/* packages/astro/vendor/vite/**/* examples/**/* scripts/**/* diff --git a/.prettierignore b/.prettierignore index 1f339633891d..f53f92086ca7 100644 --- a/.prettierignore +++ b/.prettierignore @@ -22,5 +22,4 @@ benchmark/results/ .changeset # Files -packages/webapi/mod.d.ts pnpm-lock.yaml diff --git a/benchmark/packages/timer/package.json b/benchmark/packages/timer/package.json index abcfe1d3e4f2..ddb63a270170 100644 --- a/benchmark/packages/timer/package.json +++ b/benchmark/packages/timer/package.json @@ -23,7 +23,6 @@ "dev": "astro-scripts dev \"src/**/*.ts\"" }, "dependencies": { - "@astrojs/webapi": "workspace:*", "server-destroy": "^1.0.1" }, "peerDependencies": { diff --git a/benchmark/packages/timer/src/server.ts b/benchmark/packages/timer/src/server.ts index 28a406841a84..d33e65c00ab8 100644 --- a/benchmark/packages/timer/src/server.ts +++ b/benchmark/packages/timer/src/server.ts @@ -1,11 +1,8 @@ -import { polyfill } from '@astrojs/webapi'; import type { SSRManifest } from 'astro'; -import { NodeApp } from 'astro/app/node'; +import { NodeApp, applyPolyfills } from 'astro/app/node'; import type { IncomingMessage, ServerResponse } from 'node:http'; -polyfill(globalThis, { - exclude: 'window document', -}); +applyPolyfills(); export function createExports(manifest: SSRManifest) { const app = new NodeApp(manifest); diff --git a/package.json b/package.json index 0f590c509d4f..f497b2770753 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,6 @@ } }, "dependencies": { - "@astrojs/webapi": "workspace:*", "astro-benchmark": "workspace:*" }, "devDependencies": { diff --git a/packages/astro/package.json b/packages/astro/package.json index 42345657644a..ec1f19c57432 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -120,7 +120,6 @@ "@astrojs/language-server": "^1.0.0", "@astrojs/markdown-remark": "^2.2.1", "@astrojs/telemetry": "^2.1.1", - "@astrojs/webapi": "^2.2.0", "@babel/core": "^7.22.5", "@babel/generator": "^7.22.5", "@babel/parser": "^7.22.5", diff --git a/packages/astro/src/core/app/node.ts b/packages/astro/src/core/app/node.ts index 2cfc686a2322..f31af36db970 100644 --- a/packages/astro/src/core/app/node.ts +++ b/packages/astro/src/core/app/node.ts @@ -6,6 +6,7 @@ import { IncomingMessage } from 'node:http'; import { TLSSocket } from 'node:tls'; import { deserializeManifest } from './common.js'; import { App, type MatchOptions } from './index.js'; +export { apply as applyPolyfills } from '../polyfill.js'; const clientAddressSymbol = Symbol.for('astro.clientAddress'); diff --git a/packages/astro/src/core/polyfill.ts b/packages/astro/src/core/polyfill.ts index 99e0d5cc55ce..daceb53e22bb 100644 --- a/packages/astro/src/core/polyfill.ts +++ b/packages/astro/src/core/polyfill.ts @@ -1,8 +1,21 @@ -import { polyfill } from '@astrojs/webapi'; +import { File } from 'node:buffer'; +import crypto from 'node:crypto'; + +// NOTE: This file does not intend to polyfill everything that exists, its main goal is to make life easier +// for users deploying to runtime that do support these features. In the future, we hope for this file to disappear. export function apply() { - // polyfill WebAPIs for Node.js runtime - polyfill(globalThis, { - exclude: 'window document', - }); + // Remove when Node 18 is dropped for Node 20 + if (!globalThis.crypto) { + Object.defineProperty(globalThis, 'crypto', { + value: crypto.webcrypto, + }); + } + + // Remove when Node 18 is dropped for Node 20 + if (!globalThis.File) { + Object.defineProperty(globalThis, 'File', { + value: File, + }); + } } diff --git a/packages/astro/test/custom-elements.test.js b/packages/astro/test/custom-elements.test.js deleted file mode 100644 index 53a13b478792..000000000000 --- a/packages/astro/test/custom-elements.test.js +++ /dev/null @@ -1,70 +0,0 @@ -import { expect } from 'chai'; -import { load as cheerioLoad } from 'cheerio'; -import { loadFixture } from './test-utils.js'; - -describe('Custom Elements', () => { - let fixture; - - before(async () => { - fixture = await loadFixture({ - root: './fixtures/custom-elements/', - }); - await fixture.build(); - }); - - it('Work as constructors', async () => { - const html = await fixture.readFile('/ctr/index.html'); - const $ = cheerioLoad(html); - - // test 1: Element rendered - expect($('my-element')).to.have.lengthOf(1); - - // test 2: shadow rendered - expect($('my-element template[shadowroot=open][shadowrootmode=open]')).to.have.lengthOf(1); - }); - - it('Works with exported tagName', async () => { - const html = await fixture.readFile('/index.html'); - const $ = cheerioLoad(html); - - // test 1: Element rendered - expect($('my-element')).to.have.lengthOf(1); - - // test 2: shadow rendered - expect($('my-element template[shadowroot=open][shadowrootmode=open]')).to.have.lengthOf(1); - }); - - it.skip('Hydration works with exported tagName', async () => { - const html = await fixture.readFile('/load/index.html'); - const $ = cheerioLoad(html); - - // SSR - // test 1: Element rendered - expect($('my-element')).to.have.lengthOf(1); - - // test 2: shadow rendered - expect($('my-element template[shadowroot=open][shadowrootmode=open]')).to.have.lengthOf(1); - - // Hydration - // test 3: Component and polyfill scripts bundled separately - expect($('script')).to.have.lengthOf(2); - }); - - it('Custom elements not claimed by renderer are rendered as regular HTML', async () => { - const html = await fixture.readFile('/nossr/index.html'); - const $ = cheerioLoad(html); - - // test 1: Rendered the client-only element - expect($('client-element')).to.have.lengthOf(1); - // No children - expect($('client-element').text()).to.equal(''); - }); - - it('Can import a client-only element that is nested in JSX', async () => { - const html = await fixture.readFile('/nested/index.html'); - const $ = cheerioLoad(html); - - // test 1: Element rendered - expect($('client-only-element')).to.have.lengthOf(1); - }); -}); diff --git a/packages/astro/test/fixtures/custom-elements/astro.config.mjs b/packages/astro/test/fixtures/custom-elements/astro.config.mjs deleted file mode 100644 index 439334f8fa17..000000000000 --- a/packages/astro/test/fixtures/custom-elements/astro.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ -import { defineConfig } from 'astro/config'; -import ceIntegration from '@test/custom-element-renderer'; - -export default defineConfig({ - integrations: [ceIntegration()], -}) diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/hydration-polyfill.js b/packages/astro/test/fixtures/custom-elements/my-component-lib/hydration-polyfill.js deleted file mode 100644 index 665844481c7c..000000000000 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/hydration-polyfill.js +++ /dev/null @@ -1 +0,0 @@ -globalThis.somePolyfillHere = ''; diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js b/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js deleted file mode 100644 index 5b9bba7e62e6..000000000000 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js +++ /dev/null @@ -1,31 +0,0 @@ -function getViteConfiguration() { - return { - optimizeDeps: { - include: ['@test/custom-element-renderer/polyfill.js', '@test/custom-element-renderer/hydration-polyfill.js'], - exclude: ['@test/custom-element-renderer/server.js'] - }, - }; -} - -export default function () { - return { - name: '@test/custom-element-renderer', - hooks: { - 'astro:config:setup': ({ updateConfig, addRenderer, injectScript }) => { - // Inject the necessary polyfills on every page - injectScript('head-inline', `import('@test/custom-element-renderer/polyfill.js');`); - // Inject the hydration code, before a component is hydrated. - injectScript('before-hydration', `import('@test/custom-element-renderer/hydration-polyfill.js');`); - // Add the lit renderer so that Astro can understand lit components. - addRenderer({ - name: '@test/custom-element-renderer', - serverEntrypoint: '@test/custom-element-renderer/server.js', - }); - // Update the vite configuration. - updateConfig({ - vite: getViteConfiguration(), - }); - }, - }, - }; -} diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/package.json b/packages/astro/test/fixtures/custom-elements/my-component-lib/package.json deleted file mode 100644 index f1d53b9854c9..000000000000 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@test/custom-element-renderer", - "version": "0.1.0", - "private": true, - "main": "index.js", - "type": "module", - "exports": { - ".": "./index.js", - "./server.js": "./server.js", - "./polyfill.js": "./polyfill.js", - "./hydration-polyfill.js": "./hydration-polyfill.js" - } -} diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/polyfill.js b/packages/astro/test/fixtures/custom-elements/my-component-lib/polyfill.js deleted file mode 100644 index 92788352b7ef..000000000000 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/polyfill.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log('this is a polyfill'); -export default {}; diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/server.js b/packages/astro/test/fixtures/custom-elements/my-component-lib/server.js deleted file mode 100644 index 688923159b80..000000000000 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/server.js +++ /dev/null @@ -1,30 +0,0 @@ -function getConstructor(Component) { - if (typeof Component === 'string') { - const tagName = Component; - Component = customElements.get(tagName); - } - return Component; -} - -function check(component) { - const Component = getConstructor(component); - if (typeof Component === 'function' && globalThis.HTMLElement.isPrototypeOf(Component)) { - return true; - } - return false; -} - -function renderToStaticMarkup(component, props, innerHTML) { - const Component = getConstructor(component); - const el = new Component(); - el.connectedCallback(); - const html = `<${el.localName}>${el.innerHTML}` - return { - html - }; -} - -export default { - check, - renderToStaticMarkup -}; diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/shim.js b/packages/astro/test/fixtures/custom-elements/my-component-lib/shim.js deleted file mode 100644 index eb969e528d09..000000000000 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/shim.js +++ /dev/null @@ -1,28 +0,0 @@ -globalThis.customElements = { - _elements: new Map(), - define(name, ctr) { - ctr.tagName = name; - this._elements.set(name, ctr); - }, - get(name) { - return this._elements.get(name); - } -}; - -globalThis.HTMLElement = class { - attachShadow() { - this.shadowRoot = new HTMLElement(); - } - - get localName() { - return this.constructor.tagName; - } - - get innerHTML() { - return this._innerHTML; - } - - set innerHTML(val) { - this._innerHTML = val; - } -}; diff --git a/packages/astro/test/fixtures/custom-elements/package.json b/packages/astro/test/fixtures/custom-elements/package.json deleted file mode 100644 index 80246a3b0499..000000000000 --- a/packages/astro/test/fixtures/custom-elements/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@test/custom-elements", - "version": "0.0.0", - "private": true, - "dependencies": { - "astro": "workspace:*", - "@test/custom-element-renderer": "workspace:*" - } -} diff --git a/packages/astro/test/fixtures/custom-elements/src/components/my-element.js b/packages/astro/test/fixtures/custom-elements/src/components/my-element.js deleted file mode 100644 index ffc5e6ffb5d0..000000000000 --- a/packages/astro/test/fixtures/custom-elements/src/components/my-element.js +++ /dev/null @@ -1,13 +0,0 @@ -export const tagName = 'my-element'; - -class MyElement extends HTMLElement { - connectedCallback() { - this.attachShadow({ mode: 'open' }); - this.shadowRoot.innerHTML = `Hello from a custom element!`; - this.innerHTML = `
Light dom!
` - } -} - -customElements.define(tagName, MyElement); - -export default MyElement; diff --git a/packages/astro/test/fixtures/custom-elements/src/pages/ctr.astro b/packages/astro/test/fixtures/custom-elements/src/pages/ctr.astro deleted file mode 100644 index 8b1c83512a82..000000000000 --- a/packages/astro/test/fixtures/custom-elements/src/pages/ctr.astro +++ /dev/null @@ -1,16 +0,0 @@ ---- -import MyElement from '../components/my-element.js'; - -const title = 'My App'; ---- - - - - {title} - - -

{title}

- - - - \ No newline at end of file diff --git a/packages/astro/test/fixtures/custom-elements/src/pages/index.astro b/packages/astro/test/fixtures/custom-elements/src/pages/index.astro deleted file mode 100644 index b7380624aed5..000000000000 --- a/packages/astro/test/fixtures/custom-elements/src/pages/index.astro +++ /dev/null @@ -1,15 +0,0 @@ ---- -import '../components/my-element.js'; -const title = 'My App'; ---- - - - - {title} - - -

{title}

- - - - \ No newline at end of file diff --git a/packages/astro/test/fixtures/custom-elements/src/pages/nested.astro b/packages/astro/test/fixtures/custom-elements/src/pages/nested.astro deleted file mode 100644 index f23e3b6bcd91..000000000000 --- a/packages/astro/test/fixtures/custom-elements/src/pages/nested.astro +++ /dev/null @@ -1,11 +0,0 @@ ---- -let show = true ---- - - - Custom element not imported but nested - - - {show && } - - \ No newline at end of file diff --git a/packages/astro/test/fixtures/custom-elements/src/pages/nossr.astro b/packages/astro/test/fixtures/custom-elements/src/pages/nossr.astro deleted file mode 100644 index 53e580afbbc3..000000000000 --- a/packages/astro/test/fixtures/custom-elements/src/pages/nossr.astro +++ /dev/null @@ -1,14 +0,0 @@ ---- -const title = 'My App'; ---- - - - - {title} - - -

{title}

- - - - \ No newline at end of file diff --git a/packages/astro/test/test-utils.js b/packages/astro/test/test-utils.js index 27f5d83f794a..a55fd213bcad 100644 --- a/packages/astro/test/test-utils.js +++ b/packages/astro/test/test-utils.js @@ -1,4 +1,3 @@ -import { polyfill } from '@astrojs/webapi'; import { execa } from 'execa'; import fastGlob from 'fast-glob'; import fs from 'node:fs'; @@ -17,11 +16,6 @@ import { nodeLogDestination } from '../dist/core/logger/node.js'; import preview from '../dist/core/preview/index.js'; import { sync } from '../dist/core/sync/index.js'; -// polyfill WebAPIs to globalThis for Node v12, Node v14, and Node v16 -polyfill(globalThis, { - exclude: 'window document', -}); - // Disable telemetry when running tests process.env.ASTRO_TELEMETRY_DISABLED = true; diff --git a/packages/integrations/netlify/package.json b/packages/integrations/netlify/package.json index e6ff36e457e9..fe5f3cc6b2f4 100644 --- a/packages/integrations/netlify/package.json +++ b/packages/integrations/netlify/package.json @@ -39,7 +39,6 @@ }, "dependencies": { "@astrojs/underscore-redirects": "^0.2.0", - "@astrojs/webapi": "^2.2.0", "@netlify/functions": "^1.6.0", "esbuild": "^0.18.16" }, diff --git a/packages/integrations/netlify/src/netlify-functions.ts b/packages/integrations/netlify/src/netlify-functions.ts index cc6636ec4853..91c4f1ef7417 100644 --- a/packages/integrations/netlify/src/netlify-functions.ts +++ b/packages/integrations/netlify/src/netlify-functions.ts @@ -1,12 +1,10 @@ -import { polyfill } from '@astrojs/webapi'; import { builder, type Handler } from '@netlify/functions'; import type { SSRManifest } from 'astro'; import { App } from 'astro/app'; +import { applyPolyfills } from 'astro/app/node'; import { ASTRO_LOCALS_HEADER } from './integration-functions.js'; -polyfill(globalThis, { - exclude: 'window document', -}); +applyPolyfills(); export interface Args { builders?: boolean; diff --git a/packages/integrations/node/package.json b/packages/integrations/node/package.json index bb33df74dfad..f4162a5cdbce 100644 --- a/packages/integrations/node/package.json +++ b/packages/integrations/node/package.json @@ -33,7 +33,6 @@ "test": "mocha --exit --timeout 20000 test/" }, "dependencies": { - "@astrojs/webapi": "^2.2.0", "send": "^0.18.0", "server-destroy": "^1.0.1" }, diff --git a/packages/integrations/node/src/server.ts b/packages/integrations/node/src/server.ts index 98f5cd14bd4f..04c81c2d1f85 100644 --- a/packages/integrations/node/src/server.ts +++ b/packages/integrations/node/src/server.ts @@ -1,14 +1,10 @@ -import { polyfill } from '@astrojs/webapi'; import type { SSRManifest } from 'astro'; -import { NodeApp } from 'astro/app/node'; +import { NodeApp, applyPolyfills } from 'astro/app/node'; import middleware from './nodeMiddleware.js'; import startServer from './standalone.js'; import type { Options } from './types'; -polyfill(globalThis, { - exclude: 'window document', -}); - +applyPolyfills(); export function createExports(manifest: SSRManifest, options: Options) { const app = new NodeApp(manifest); return { diff --git a/packages/integrations/vercel/package.json b/packages/integrations/vercel/package.json index 137b7213e2bf..a287ac26bc3b 100644 --- a/packages/integrations/vercel/package.json +++ b/packages/integrations/vercel/package.json @@ -52,7 +52,6 @@ }, "dependencies": { "@astrojs/internal-helpers": "^0.1.1", - "@astrojs/webapi": "^2.2.0", "@vercel/analytics": "^0.1.11", "@vercel/nft": "^0.22.6", "esbuild": "^0.18.16", diff --git a/packages/integrations/vercel/src/serverless/entrypoint.ts b/packages/integrations/vercel/src/serverless/entrypoint.ts index 9e3cb1da0af1..f132d71f346c 100644 --- a/packages/integrations/vercel/src/serverless/entrypoint.ts +++ b/packages/integrations/vercel/src/serverless/entrypoint.ts @@ -1,14 +1,12 @@ -import { polyfill } from '@astrojs/webapi'; import type { SSRManifest } from 'astro'; import { App } from 'astro/app'; +import { applyPolyfills } from 'astro/app/node'; import type { IncomingMessage, ServerResponse } from 'node:http'; import { ASTRO_LOCALS_HEADER } from './adapter'; import { getRequest, setResponse } from './request-transform'; -polyfill(globalThis, { - exclude: 'window document', -}); +applyPolyfills(); export const createExports = (manifest: SSRManifest) => { const app = new App(manifest); diff --git a/packages/webapi/.gitignore b/packages/webapi/.gitignore deleted file mode 100644 index 7871d6ab1b8a..000000000000 --- a/packages/webapi/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -mod.js -mod.js.map diff --git a/packages/webapi/CHANGELOG.md b/packages/webapi/CHANGELOG.md deleted file mode 100644 index a90ba9b24086..000000000000 --- a/packages/webapi/CHANGELOG.md +++ /dev/null @@ -1,109 +0,0 @@ -# @astrojs/webapi - -## 2.2.0 - -### Minor Changes - -- [#6981](https://github.com/withastro/astro/pull/6981) [`bf63f615f`](https://github.com/withastro/astro/commit/bf63f615fc1b97d6fb84db55f7639084e3ada5af) Thanks [@andremralves](https://github.com/andremralves)! - Add polyfill for `crypto` - -## 2.1.1 - -### Patch Changes - -- [#6929](https://github.com/withastro/astro/pull/6929) [`ac57b5549`](https://github.com/withastro/astro/commit/ac57b5549f828a17bdbebdaca7ace075307a3c9d) Thanks [@bluwy](https://github.com/bluwy)! - Upgrade undici to v5.22.0 - -## 2.1.0 - -### Minor Changes - -- [#6213](https://github.com/withastro/astro/pull/6213) [`afbbc4d5b`](https://github.com/withastro/astro/commit/afbbc4d5bfafc1779bac00b41c2a1cb1c90f2808) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Updated compilation settings to disable downlevelling for Node 14 - -## 2.0.3 - -### Patch Changes - -- [#6413](https://github.com/withastro/astro/pull/6413) [`0abd1d3e4`](https://github.com/withastro/astro/commit/0abd1d3e42cf7bf5efb8c41f37e011b933fb0629) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Use undici's FormData instead of a polyfill - -## 2.0.2 - -### Patch Changes - -- [#6355](https://github.com/withastro/astro/pull/6355) [`5aa6580f7`](https://github.com/withastro/astro/commit/5aa6580f775405a4443835bf7eb81f0c65e5aed6) Thanks [@ematipico](https://github.com/ematipico)! - Update `undici` to v5.20.0 - -## 2.0.1 - -### Patch Changes - -- [#6282](https://github.com/withastro/astro/pull/6282) [`bb1801013`](https://github.com/withastro/astro/commit/bb1801013708d9efdbbcebc53a564ac375bf4b26) Thanks [@matthewp](https://github.com/matthewp)! - Temporarily pin undici to fix Header regression - -## 2.0.0 - -### Major Changes - -- [#5814](https://github.com/withastro/astro/pull/5814) [`c55fbcb8e`](https://github.com/withastro/astro/commit/c55fbcb8edca1fe118a44f68c9f9436a4719d171) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Moved target to Node 16. Removed polyfills for `AbortController`, `AbortSignal`, `atob`, `btoa`, `Object.hasOwn`, `Promise.all`, `Array.at` and `String.replaceAll` - -- [#5782](https://github.com/withastro/astro/pull/5782) [`1f92d64ea`](https://github.com/withastro/astro/commit/1f92d64ea35c03fec43aff64eaf704dc5a9eb30a) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Replace `node-fetch`'s polyfill with `undici`. - - Since `undici` does not support it, this change also removes custom support for the `file:` protocol - -### Patch Changes - -- [#5930](https://github.com/withastro/astro/pull/5930) [`46ecd5de3`](https://github.com/withastro/astro/commit/46ecd5de34df619e2ee73ccea39a57acd37bc0b8) Thanks [@h3y6e](https://github.com/h3y6e)! - Update magic-string from 0.25.9 to 0.27.0 - -## 2.0.0-beta.1 - -
-See changes in 2.0.0-beta.1 - -### Patch Changes - -- [#5930](https://github.com/withastro/astro/pull/5930) [`46ecd5de3`](https://github.com/withastro/astro/commit/46ecd5de34df619e2ee73ccea39a57acd37bc0b8) Thanks [@h3y6e](https://github.com/h3y6e)! - Update magic-string from 0.25.9 to 0.27.0 - -
- -## 2.0.0-beta.0 - -
-See changes in 2.0.0-beta.0 - -### Major Changes - -- [#5814](https://github.com/withastro/astro/pull/5814) [`c55fbcb8e`](https://github.com/withastro/astro/commit/c55fbcb8edca1fe118a44f68c9f9436a4719d171) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Moved target to Node 16. Removed polyfills for `AbortController`, `AbortSignal`, `atob`, `btoa`, `Object.hasOwn`, `Promise.all`, `Array.at` and `String.replaceAll` - -- [#5782](https://github.com/withastro/astro/pull/5782) [`1f92d64ea`](https://github.com/withastro/astro/commit/1f92d64ea35c03fec43aff64eaf704dc5a9eb30a) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Replace `node-fetch`'s polyfill with `undici`. - - Since `undici` does not support it, this change also removes custom support for the `file:` protocol - -
- -## 1.1.1 - -### Patch Changes - -- [#5235](https://github.com/withastro/astro/pull/5235) [`b6a478f37`](https://github.com/withastro/astro/commit/b6a478f37648491321077750bfca7bddf3cafadd) Thanks [@ba55ie](https://github.com/ba55ie)! - Fix CustomElementRegistry for Node SSR Adapter - -## 1.1.0 - -### Minor Changes - -- [#4676](https://github.com/withastro/astro/pull/4676) [`5e4c5252b`](https://github.com/withastro/astro/commit/5e4c5252bd80cbaf6a7ee4d4503ece007664410f) Thanks [@zicklag](https://github.com/zicklag)! - Add HTTP Proxy Support to `fetch` Polyfill - -## 1.0.0 - -### Major Changes - -- [`04ad44563`](https://github.com/withastro/astro/commit/04ad445632c67bdd60c1704e1e0dcbcaa27b9308) - > Astro v1.0 is out! Read the [official announcement post](https://astro.build/blog/astro-1/). - - **No breaking changes**. This package is now officially stable and compatible with `astro@1.0.0`! - -## 0.12.0 - -### Minor Changes - -- [#3417](https://github.com/withastro/astro/pull/3417) [`4de53ecc`](https://github.com/withastro/astro/commit/4de53eccef346bed843b491b7ab93987d7d85655) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Fix: support FormData object on fetch body - -## 0.11.1 - -### Patch Changes - -- [#3095](https://github.com/withastro/astro/pull/3095) [`5acf77dd`](https://github.com/withastro/astro/commit/5acf77dd22be95e33ff838383a2c1790f484e380) Thanks [@matthewp](https://github.com/matthewp)! - Fixes rendering of "undefined" on custom element children diff --git a/packages/webapi/LICENSE b/packages/webapi/LICENSE deleted file mode 100644 index d513f83db92c..000000000000 --- a/packages/webapi/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -MIT License Copyright (c) 2022 The Astro Technology Company - -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 -(including the next paragraph) 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. - ---- - -Code from [@astrocommunity/webapi](https://www.npmjs.com/@astrocommunity/webapi) is licensed under the CC0-1.0 License. - -Code from [event-target-shim](https://www.npmjs.com/package/event-target-shim) is licensed under the MIT License (MIT), Copyright Toru Nagashima. diff --git a/packages/webapi/README.md b/packages/webapi/README.md deleted file mode 100644 index 695c8be8ed28..000000000000 --- a/packages/webapi/README.md +++ /dev/null @@ -1,155 +0,0 @@ -# WebAPI - -**WebAPI** lets you use Web APIs not present in Node v16 and later. - -```sh -npm install @astrojs/webapi -``` - -```js -import { polyfill } from '@astrojs/webapi' - -polyfill(globalThis) - -const t = new EventTarget() -const e = new CustomEvent('hello') - -t.addEventListener('hello', console.log) - -t.dispatchEvent(e) // logs `e` event from `t` -``` - -These APIs are combined from popular open source projects and configured to share implementation details. This allows their behavior to match browser expectations as well as reduce their combined memory footprint. - -## Features - -- [ByteLengthQueuingStrategy](https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy) -- [CanvasRenderingContext2D](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) -- [CSSStyleSheet](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet) -- [CountQueuingStrategy](https://developer.mozilla.org/en-US/docs/Web/API/CountQueuingStrategy) -- [CustomElementRegistry](https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry) -- [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) -- [DOMException](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) -- [Document](https://developer.mozilla.org/en-US/docs/Web/API/Document) -- [DocumentFragment](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) -- [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) -- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) -- [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) -- [File](https://developer.mozilla.org/en-US/docs/Web/API/File) -- [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) -- [HTMLDocument](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDocument) -- [HTMLElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) -- [HTMLBodyElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement) -- [HTMLCanvasElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) -- [HTMLDivElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement) -- [HTMLHeadElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadElement) -- [HTMLHtmlElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHtmlElement) -- [HTMLImageElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement) -- [HTMLSpanElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement) -- [HTMLStyleElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLStyleElement) -- [HTMLTemplateElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement) -- [HTMLUnknownElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLUnknownElement) -- [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) -- [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) -- [Image](https://developer.mozilla.org/en-US/docs/Web/API/Image) -- [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) -- [MediaQueryList](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList) -- [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) -- [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node) -- [NodeIterator](https://developer.mozilla.org/en-US/docs/Web/API/NodeIterator) -- [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) -- [ReadableByteStreamController](https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController) -- [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) -- [ReadableStreamBYOBReader](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader) -- [ReadableStreamBYOBRequest](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBRequest) -- [ReadableStreamDefaultController](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController) -- [ReadableStreamDefaultReader](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) -- [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) -- [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) -- [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot) -- [Storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage) -- [StyleSheet](https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet) -- [TransformStream](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) -- [TreeWalker](https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker) -- [WritableStream](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) -- [WritableStreamDefaultController](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultController) -- [WritableStreamDefaultWriter](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter) -- [Window](https://developer.mozilla.org/en-US/docs/Web/API/Window) -- [cancelAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame) -- [cancelIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/cancelIdleCallback) -- [clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) -- [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) -- [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/localStorage) -- [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/requestAnimationFrame) -- [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/requestIdleCallback) -- [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) -- [structuredClone](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) -- [URLPattern](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) - -## Usage - -You can use WebAPIs as individual exports. - -```js -import { Event, EventTarget, File, fetch, Response } from '@astrojs/webapi' -``` - -You can apply WebAPIs to an object, like `globalThis`. - -```js -import { polyfill } from '@astrojs/webapi' - -polyfill(globalThis) -``` - -## Polyfill Options - -The `exclude` option receives a list of WebAPIs to exclude from polyfilling. - -```js -polyfill(globalThis, { - // disables polyfills for setTimeout clearTimeout - exclude: 'setTimeout clearTimeout', -}) -``` - -The `exclude` option accepts shorthands to exclude multiple polyfills. These shorthands end with the plus sign (`+`). - -```js -polyfill(globalThis, { - // disables polyfills for setTimeout clearTimeout - exclude: 'Timeout+', -}) -``` - -```js -polyfill(globalThis, { - // disables polyfills for Node, Window, Document, HTMLElement, etc. - exclude: 'Node+', -}) -``` - -```js -polyfill(globalThis, { - // disables polyfills for Event, EventTarget, Node, Window, Document, HTMLElement, etc. - exclude: 'Event+', -}) -``` - -| Shorthand | Excludes | -| :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `Document+` | `Document`, `HTMLDocument` | -| `Element+` | `Element`, and exclusions from `HTMLElement+` | -| `Event+` | `Event`, `CustomEvent`, `EventTarget`, `MediaQueryList`, `Window`, and exclusions from `Node+` | -| `EventTarget+` | `Event`, `CustomEvent`, `EventTarget`, `MediaQueryList`, `Window`, and exclusions from `Node+` | -| `HTMLElement+` | `CustomElementsRegistry`, `HTMLElement`, `HTMLBodyElement`, `HTMLCanvasElement`, `HTMLDivElement`, `HTMLHeadElement`, `HTMLHtmlElement`, `HTMLImageElement`, `HTMLStyleElement`, `HTMLTemplateElement`, `HTMLUnknownElement`, `Image` | -| `Node+` | `Node`, `DocumentFragment`, `ShadowRoot`, `Document`, `HTMLDocument`, and exclusions from `Element+` | -| `StyleSheet+` | `StyleSheet`, `CSSStyleSheet` | - ---- - -## License & Attribution - -Thank you to Jon Neal for his work on the original [webapi](https://github.com/astro-community/webapi) project that this package is forked from. Licensed under the CC0-1.0 License. - -Code from [event-target-shim](https://www.npmjs.com/package/event-target-shim) is licensed under the MIT License (MIT), Copyright Toru Nagashima. diff --git a/packages/webapi/apply.js b/packages/webapi/apply.js deleted file mode 100644 index 4efd06fe1790..000000000000 --- a/packages/webapi/apply.js +++ /dev/null @@ -1,5 +0,0 @@ -import { polyfill } from './mod.js' - -export * from './mod.js' - -polyfill(globalThis) diff --git a/packages/webapi/mod.d.ts b/packages/webapi/mod.d.ts deleted file mode 100644 index 60bdbab37796..000000000000 --- a/packages/webapi/mod.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// organize-imports-ignore -export { pathToPosix } from './lib/utils'; -export { alert, ByteLengthQueuingStrategy, cancelAnimationFrame, cancelIdleCallback, CanvasRenderingContext2D, CharacterData, clearTimeout, Comment, CountQueuingStrategy, crypto, CSSStyleSheet, CustomElementRegistry, CustomEvent, Document, DocumentFragment, DOMException, Element, Event, EventTarget, fetch, File, FormData, Headers, HTMLBodyElement, HTMLCanvasElement, HTMLDivElement, HTMLDocument, HTMLElement, HTMLHeadElement, HTMLHtmlElement, HTMLImageElement, HTMLSpanElement, HTMLStyleElement, HTMLTemplateElement, HTMLUnknownElement, Image, ImageData, IntersectionObserver, MediaQueryList, MutationObserver, Node, NodeFilter, NodeIterator, OffscreenCanvas, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, Request, requestAnimationFrame, requestIdleCallback, ResizeObserver, Response, setTimeout, ShadowRoot, structuredClone, StyleSheet, Text, TransformStream, TreeWalker, URLPattern, Window, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter, } from './mod.js'; -export declare const polyfill: { - (target: any, options?: PolyfillOptions): any; - internals(target: any, name: string): any; -}; -interface PolyfillOptions { - exclude?: string | string[]; - override?: Record; -} \ No newline at end of file diff --git a/packages/webapi/package.json b/packages/webapi/package.json deleted file mode 100644 index e65796fd8ccf..000000000000 --- a/packages/webapi/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "name": "@astrojs/webapi", - "description": "Use Web APIs in Node", - "version": "2.2.0", - "type": "module", - "exports": { - ".": { - "import": "./mod.js", - "types": "./mod.d.ts" - }, - "./apply": { - "import": "./apply.js" - } - }, - "main": "mod.js", - "types": "mod.d.ts", - "files": [ - "apply.js", - "mod.d.ts", - "mod.js", - "mod.js.map" - ], - "keywords": [ - "astro", - "api", - "cancelAnimationFrame", - "clearImmediate", - "clearInterval", - "fetch", - "requestAnimationFrame", - "setImmediate", - "setInterval", - "web" - ], - "repository": { - "type": "git", - "url": "https://github.com/withastro/astro.git", - "directory": "packages/webapi" - }, - "author": "withastro", - "license": "MIT", - "contributors": [ - "Jonathan Neal (https://github.com/jonathantneal)", - "Toru Nagashima (https://github.com/mysticatea)", - "Jimmy Wärting (https://github.com/jimmywarting)", - "David Frank (https://github.com/bitinn)", - "Mattias Buelens (https://github.com/MattiasBuelens)", - "Diwank Singh (https://github.com/creatorrr)" - ], - "bugs": "https://github.com/withastro/astro/issues", - "homepage": "https://github.com/withastro/astro/tree/main/packages/webapi#readme", - "dependencies": { - "undici": "^5.22.1" - }, - "devDependencies": { - "@rollup/plugin-alias": "^3.1.9", - "@rollup/plugin-inject": "^4.0.4", - "@rollup/plugin-node-resolve": "^13.3.0", - "@rollup/plugin-typescript": "^8.5.0", - "@types/chai": "^4.3.5", - "@types/mocha": "^9.1.1", - "@types/node": "^18.16.18", - "@ungap/structured-clone": "^0.3.4", - "chai": "^4.3.7", - "event-target-shim": "^6.0.2", - "magic-string": "^0.30.2", - "mocha": "^9.2.2", - "rollup": "^2.79.1", - "tslib": "^2.5.3", - "typescript": "~5.1.6", - "urlpattern-polyfill": "^1.0.0-rc5" - }, - "scripts": { - "build": "node run/build.js", - "build:ci": "node run/build.js", - "dev": "node run/build.js", - "release": "node run/build.js && npm publish --access public", - "test": "mocha --parallel --timeout 15000" - }, - "prettier": { - "semi": false, - "singleQuote": true, - "trailingComma": "es5", - "useTabs": true, - "overrides": [ - { - "files": [ - ".stackblitzrc", - "*.json" - ], - "options": { - "useTabs": false - } - } - ] - } -} diff --git a/packages/webapi/run/build.js b/packages/webapi/run/build.js deleted file mode 100644 index 01782074639c..000000000000 --- a/packages/webapi/run/build.js +++ /dev/null @@ -1,224 +0,0 @@ -import { default as alias } from '@rollup/plugin-alias' -import { default as inject } from '@rollup/plugin-inject' -import { nodeResolve } from '@rollup/plugin-node-resolve' -import { default as typescript } from '@rollup/plugin-typescript' -import { default as MagicString } from 'magic-string' -import { - readFile as nodeReadFile, - rename, - rm, - writeFile, -} from 'node:fs/promises' -import { createRequire } from 'node:module' -import path from 'node:path' -import { rollup } from 'rollup' - -const readFileCache = Object.create(null) -const require = createRequire(import.meta.url) - -const readFile = (/** @type {string} */ id) => - readFileCache[id] || (readFileCache[id] = nodeReadFile(id, 'utf8')) - -const pathToDOMException = path.resolve('src', 'lib', 'DOMException.js') -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 }, - { - 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({ - dedupe: ['net', 'node:net'], - }), - inject({ - // import { Promise as P } from 'es6-promise' - // P: [ 'es6-promise', 'Promise' ], - 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: ['node:stream/web', 'ReadableStream'], - ShadowRoot: ['./Node', 'ShadowRoot'], - Window: ['./Window', 'Window'], - 'globalThis.ReadableStream': ['node:stream/web', 'ReadableStream'], - }), - { - async load(id) { - const pathToEsm = id - const pathToMap = `${pathToEsm}.map` - - const code = await readFile(pathToEsm, 'utf8') - - const indexes = [] - - const replacements = [ - // remove unused imports - [/(^|\n)import\s+[^']+'node:(buffer|fs|path|worker_threads)'/g, ``], - [/const \{ stat \} = fs/g, ``], - - // remove unused polyfill utils - [/\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 - [/\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 - [/ 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 - [/\nBody\.prototype\.buffer[^\n]+/g, ``], - - // remove Body.prototype.data deprecation notice - [/\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 - - indexes.unshift([leadIndex, tailIndex, replacer]) - } - } - - if (indexes.length) { - const magicString = new MagicString(code) - - indexes.sort(([leadOfA], [leadOfB]) => leadOfA - leadOfB) - - for (const [leadIndex, tailindex, replacer] of indexes) { - magicString.overwrite(leadIndex, tailindex, replacer) - } - - 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, - external: ['undici'], - 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('inheritance.d.ts', { force: true, recursive: true }) - await rm('inheritance.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') - - writeFile( - 'mod.d.ts', - '// organize-imports-ignore\n' + - 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() diff --git a/packages/webapi/src/exclusions.ts b/packages/webapi/src/exclusions.ts deleted file mode 100644 index a664483dc026..000000000000 --- a/packages/webapi/src/exclusions.ts +++ /dev/null @@ -1,57 +0,0 @@ -const exclusionsForHTMLElement = [ - 'CustomElementsRegistry', - 'HTMLElement', - 'HTMLBodyElement', - 'HTMLCanvasElement', - 'HTMLDivElement', - 'HTMLHeadElement', - 'HTMLHtmlElement', - 'HTMLImageElement', - 'HTMLStyleElement', - 'HTMLTemplateElement', - 'HTMLUnknownElement', - 'Image', -] -const exclusionsForElement = ['Element', ...exclusionsForHTMLElement] as const -const exclusionsForDocument = [ - 'CustomElementsRegistry', - 'Document', - 'HTMLDocument', - 'document', - 'customElements', -] as const -const exclusionsForNode = [ - 'Node', - 'DocumentFragment', - 'ShadowRoot', - ...exclusionsForDocument, - ...exclusionsForElement, -] as const -const exclusionsForEventTarget = [ - 'Event', - 'CustomEvent', - 'EventTarget', - 'OffscreenCanvas', - 'MediaQueryList', - 'Window', - ...exclusionsForNode, -] as const -const exclusionsForEvent = [ - 'Event', - 'CustomEvent', - 'EventTarget', - 'MediaQueryList', - 'OffscreenCanvas', - 'Window', - ...exclusionsForNode, -] as const - -export const exclusions = { - 'Document+': exclusionsForDocument, - 'Element+': exclusionsForElement, - 'Event+': exclusionsForEvent, - 'EventTarget+': exclusionsForEventTarget, - 'HTMLElement+': exclusionsForHTMLElement, - 'Node+': exclusionsForNode, - 'StyleSheet+': ['StyleSheet', 'CSSStyleSheet'], -} diff --git a/packages/webapi/src/inheritance.ts b/packages/webapi/src/inheritance.ts deleted file mode 100644 index 6e3165633681..000000000000 --- a/packages/webapi/src/inheritance.ts +++ /dev/null @@ -1,26 +0,0 @@ -export const inheritance = { - CSSStyleSheet: 'StyleSheet', - CustomEvent: 'Event', - DOMException: 'Error', - Document: 'Node', - DocumentFragment: 'Node', - Element: 'Node', - HTMLDocument: 'Document', - HTMLElement: 'Element', - HTMLBodyElement: 'HTMLElement', - HTMLCanvasElement: 'HTMLElement', - HTMLDivElement: 'HTMLElement', - HTMLHeadElement: 'HTMLElement', - HTMLHtmlElement: 'HTMLElement', - HTMLImageElement: 'HTMLElement', - HTMLSpanElement: 'HTMLElement', - HTMLStyleElement: 'HTMLElement', - HTMLTemplateElement: 'HTMLElement', - HTMLUnknownElement: 'HTMLElement', - Image: 'HTMLElement', - MediaQueryList: 'EventTarget', - Node: 'EventTarget', - OffscreenCanvas: 'EventTarget', - ShadowRoot: 'DocumentFragment', - Window: 'EventTarget', -} as const diff --git a/packages/webapi/src/lib/Alert.ts b/packages/webapi/src/lib/Alert.ts deleted file mode 100644 index 0aacd645f523..000000000000 --- a/packages/webapi/src/lib/Alert.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function alert(...messages: any[]) { - console.log(...messages) -} diff --git a/packages/webapi/src/lib/AnimationFrame.ts b/packages/webapi/src/lib/AnimationFrame.ts deleted file mode 100644 index e29d3cabf7ba..000000000000 --- a/packages/webapi/src/lib/AnimationFrame.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - clearTimeout as nodeClearTimeout, - setTimeout as nodeSetTimeout, -} from 'node:timers' -import * as _ from './utils.js' - -const INTERNAL = { tick: 0, pool: new Map() } - -export function requestAnimationFrame< - TArgs extends any[], - TFunc extends (...args: TArgs) => any ->(callback: TFunc): number { - if (!INTERNAL.pool.size) { - nodeSetTimeout(() => { - const next = _.__performance_now() - - for (const func of INTERNAL.pool.values()) { - func(next) - } - - INTERNAL.pool.clear() - }, 1000 / 16) - } - - const func = _.__function_bind(callback, undefined) - const tick = ++INTERNAL.tick - - INTERNAL.pool.set(tick, func) - - return tick -} - -export function cancelAnimationFrame(requestId: number): void { - const timeout = INTERNAL.pool.get(requestId) - - if (timeout) { - nodeClearTimeout(timeout) - - INTERNAL.pool.delete(requestId) - } -} diff --git a/packages/webapi/src/lib/CanvasRenderingContext2D.ts b/packages/webapi/src/lib/CanvasRenderingContext2D.ts deleted file mode 100644 index 147a80ca9861..000000000000 --- a/packages/webapi/src/lib/CanvasRenderingContext2D.ts +++ /dev/null @@ -1,222 +0,0 @@ -import type { HTMLCanvasElement } from './HTMLCanvasElement' -import type { OffscreenCanvas } from './OffscreenCanvas' - -import { ImageData } from './ImageData' -import * as _ from './utils' - -export class CanvasRenderingContext2D { - get canvas(): HTMLCanvasElement | OffscreenCanvas | null { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'canvas').canvas - } - - get direction(): 'ltr' | 'rtl' | 'inherit' { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'direction') - .direction - } - - get fillStyle(): string { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'fillStyle') - .fillStyle - } - - get filter(): string { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'filter').filter - } - - get globalAlpha(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'globalAlpha') - .globalAlpha - } - - get globalCompositeOperation(): string { - return _.internalsOf( - this, - 'CanvasRenderingContext2D', - 'globalCompositeOperation' - ).globalCompositeOperation - } - - get font(): string { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'font').font - } - - get imageSmoothingEnabled(): boolean { - return _.internalsOf( - this, - 'CanvasRenderingContext2D', - 'imageSmoothingEnabled' - ).imageSmoothingEnabled - } - - get imageSmoothingQuality(): 'low' | 'medium' | 'high' { - return _.internalsOf( - this, - 'CanvasRenderingContext2D', - 'imageSmoothingQuality' - ).imageSmoothingQuality - } - - get lineCap(): 'butt' | 'round' | 'square' { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'lineCap').lineCap - } - - get lineDashOffset(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'lineDashOffset') - .lineDashOffset - } - - get lineJoin(): 'bevel' | 'round' | 'miter' { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'lineJoin').lineJoin - } - - get lineWidth(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'lineWidth') - .lineWidth - } - - get miterLimit(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'miterLimit') - .miterLimit - } - - get strokeStyle(): string { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'strokeStyle') - .strokeStyle - } - - get shadowOffsetX(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'shadowOffsetX') - .shadowOffsetX - } - - get shadowOffsetY(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'shadowOffsetY') - .shadowOffsetY - } - - get shadowBlur(): number { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'shadowBlur') - .shadowBlur - } - - get shadowColor(): string { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'shadowColor') - .shadowColor - } - - get textAlign(): 'left' | 'right' | 'center' | 'start' | 'end' { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'textAlign') - .textAlign - } - - get textBaseline(): - | 'top' - | 'hanging' - | 'middle' - | 'alphabetic' - | 'ideographic' - | 'bottom' { - return _.internalsOf(this, 'CanvasRenderingContext2D', 'textBaseline') - .textBaseline - } - - arc() {} - arcTo() {} - beginPath() {} - bezierCurveTo() {} - clearRect() {} - clip() {} - closePath() {} - - createImageData(width: number, height: number): void - createImageData(imagedata: ImageData): void - - createImageData(arg0: number | ImageData, arg1?: void | number) { - /** Whether ImageData is provided. */ - const hasData = _.__object_isPrototypeOf(ImageData.prototype, arg0) - - const w = hasData ? (arg0 as ImageData).width : (arg0 as number) - const h = hasData ? (arg0 as ImageData).height : (arg1 as number) - const d = hasData - ? (arg0 as ImageData).data - : new Uint8ClampedArray(w * h * 4) - - return new ImageData(d, w, h) - } - - createLinearGradient() {} - createPattern() {} - createRadialGradient() {} - drawFocusIfNeeded() {} - drawImage() {} - ellipse() {} - fill() {} - fillRect() {} - fillText() {} - getContextAttributes() {} - getImageData() {} - getLineDash() {} - getTransform() {} - isPointInPath() {} - isPointInStroke() {} - lineTo() {} - measureText() {} - moveTo() {} - putImageData() {} - quadraticCurveTo() {} - rect() {} - resetTransform() {} - restore() {} - rotate() {} - save() {} - scale() {} - setLineDash() {} - setTransform() {} - stroke() {} - strokeRect() {} - strokeText() {} - transform() {} - translate() {} -} - -_.allowStringTag(CanvasRenderingContext2D) - -export const __createCanvasRenderingContext2D = ( - canvas: EventTarget -): CanvasRenderingContext2D => { - const renderingContext2D = Object.create( - CanvasRenderingContext2D.prototype - ) as CanvasRenderingContext2D - - _.INTERNALS.set(renderingContext2D, { - canvas, - direction: 'inherit', - fillStyle: '#000', - filter: 'none', - font: '10px sans-serif', - globalAlpha: 0, - globalCompositeOperation: 'source-over', - imageSmoothingEnabled: false, - imageSmoothingQuality: 'high', - lineCap: 'butt', - lineDashOffset: 0.0, - lineJoin: 'miter', - lineWidth: 1.0, - miterLimit: 10.0, - shadowBlur: 0, - shadowColor: '#000', - shadowOffsetX: 0, - shadowOffsetY: 0, - strokeStyle: '#000', - textAlign: 'start', - textBaseline: 'alphabetic', - }) - - return renderingContext2D -} - -/** Returns whether the value is an instance of ImageData. */ -const isImageData = (value: T) => - (Object(value).data instanceof Uint8ClampedArray) as T extends ImageData - ? true - : false diff --git a/packages/webapi/src/lib/CharacterData.ts b/packages/webapi/src/lib/CharacterData.ts deleted file mode 100644 index 430657ffb3c7..000000000000 --- a/packages/webapi/src/lib/CharacterData.ts +++ /dev/null @@ -1,45 +0,0 @@ -import * as _ from './utils' - -export class CharacterData extends Node { - constructor(data: string) { - _.INTERNALS.set(super(), { - data: String(data), - } as CharacterDataInternals) - } - get data(): string { - return _.internalsOf(this, 'CharacterData', 'data') - .data - } - - get textContent(): string { - return _.internalsOf( - this, - 'CharacterData', - 'textContent' - ).data - } -} - -export class Comment extends CharacterData {} - -export class Text extends CharacterData { - get assignedSlot(): HTMLSlotElement | null { - return null - } - - get wholeText(): string { - return _.internalsOf( - this, - 'CharacterData', - 'textContent' - ).data - } -} - -_.allowStringTag(CharacterData) -_.allowStringTag(Text) -_.allowStringTag(Comment) - -interface CharacterDataInternals { - data: string -} diff --git a/packages/webapi/src/lib/CustomElementRegistry.ts b/packages/webapi/src/lib/CustomElementRegistry.ts deleted file mode 100644 index 21f775d5e527..000000000000 --- a/packages/webapi/src/lib/CustomElementRegistry.ts +++ /dev/null @@ -1,92 +0,0 @@ -import * as _ from './utils' - -export class CustomElementRegistry { - /** Defines a new custom element using the given tag name and HTMLElement constructor. */ - define( - name: string, - constructor: Function, - options?: ElementDefinitionOptions - ) { - const internals = _.internalsOf( - this, - 'CustomElementRegistry', - 'define' - ) - - name = String(name) - - if (/[A-Z]/.test(name)) - throw new SyntaxError( - 'Custom element name cannot contain an uppercase ASCII letter' - ) - if (!/^[a-z]/.test(name)) - throw new SyntaxError( - 'Custom element name must have a lowercase ASCII letter as its first character' - ) - if (!/-/.test(name)) - throw new SyntaxError('Custom element name must contain a hyphen') - - _.INTERNALS.set(constructor, { - attributes: {}, - localName: name, - } as any) - - internals.constructorByName.set(name, constructor) - internals.nameByConstructor.set(constructor, name) - - void options - } - - /** Returns the constructor associated with the given tag name. */ - get(name: string) { - const internals = _.internalsOf( - this, - 'CustomElementRegistry', - 'get' - ) - - name = String(name).toLowerCase() - - return internals.constructorByName.get(name) - } - - getName(constructor: Function) { - const internals = _.internalsOf( - this, - 'CustomElementRegistry', - 'getName' - ) - - return internals.nameByConstructor.get(constructor) - } -} - -_.allowStringTag(CustomElementRegistry) - -interface CustomElementRegistryInternals { - constructorByName: Map - nameByConstructor: Map -} - -interface ElementDefinitionOptions { - extends?: string | undefined -} - -export const initCustomElementRegistry = ( - target: Record, - exclude: Set -) => { - if (exclude.has('customElements')) return - - const CustomElementRegistry = - target.CustomElementRegistry || globalThis.CustomElementRegistry - - const customElements: CustomElementRegistry = - target.customElements || - (target.customElements = new CustomElementRegistry()) - - _.INTERNALS.set(customElements, { - constructorByName: new Map(), - nameByConstructor: new Map(), - } as CustomElementRegistryInternals) -} diff --git a/packages/webapi/src/lib/CustomEvent.ts b/packages/webapi/src/lib/CustomEvent.ts deleted file mode 100644 index 1269b72169c1..000000000000 --- a/packages/webapi/src/lib/CustomEvent.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Event } from 'event-target-shim' -import * as _ from './utils' - -class CustomEvent< - TEventType extends string = string -> extends Event { - constructor(type: TEventType, params?: CustomEventInit) { - params = Object(params) as Required - - super(type, params) - - if ('detail' in params) this.detail = params.detail - } - - detail!: any -} - -_.allowStringTag(CustomEvent) - -export { CustomEvent } - -interface CustomEventInit { - bubbles?: boolean - cancelable?: false - detail?: any -} diff --git a/packages/webapi/src/lib/DOMException.ts b/packages/webapi/src/lib/DOMException.ts deleted file mode 100644 index 539871c6ba61..000000000000 --- a/packages/webapi/src/lib/DOMException.ts +++ /dev/null @@ -1,40 +0,0 @@ -import * as _ from './utils' - -export class DOMException extends Error { - constructor(message = '', name = 'Error') { - super(message) - - this.code = 0 - this.name = name - } - - code!: number - - static INDEX_SIZE_ERR = 1 - static DOMSTRING_SIZE_ERR = 2 - static HIERARCHY_REQUEST_ERR = 3 - static WRONG_DOCUMENT_ERR = 4 - static INVALID_CHARACTER_ERR = 5 - static NO_DATA_ALLOWED_ERR = 6 - static NO_MODIFICATION_ALLOWED_ERR = 7 - static NOT_FOUND_ERR = 8 - static NOT_SUPPORTED_ERR = 9 - static INUSE_ATTRIBUTE_ERR = 10 - static INVALID_STATE_ERR = 11 - static SYNTAX_ERR = 12 - static INVALID_MODIFICATION_ERR = 13 - static NAMESPACE_ERR = 14 - static INVALID_ACCESS_ERR = 15 - static VALIDATION_ERR = 16 - static TYPE_MISMATCH_ERR = 17 - static SECURITY_ERR = 18 - static NETWORK_ERR = 19 - static ABORT_ERR = 20 - static URL_MISMATCH_ERR = 21 - static QUOTA_EXCEEDED_ERR = 22 - static TIMEOUT_ERR = 23 - static INVALID_NODE_TYPE_ERR = 24 - static DATA_CLONE_ERR = 25 -} - -_.allowStringTag(DOMException) diff --git a/packages/webapi/src/lib/Document.ts b/packages/webapi/src/lib/Document.ts deleted file mode 100644 index b9c30b3a3955..000000000000 --- a/packages/webapi/src/lib/Document.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { Text } from './CharacterData' -import { TreeWalker } from './TreeWalker' -import * as _ from './utils' - -export class Document extends Node { - createElement(name: string) { - const internals = _.internalsOf( - this, - 'Document', - 'createElement' - ) - - const customElementInternals: CustomElementRegistryInternals = - _.INTERNALS.get(internals.target.customElements) - - name = String(name).toLowerCase() - - const TypeOfHTMLElement = - internals.constructorByName.get(name) || - (customElementInternals && - customElementInternals.constructorByName.get(name)) || - HTMLUnknownElement - - const element = Object.setPrototypeOf( - new EventTarget(), - TypeOfHTMLElement.prototype - ) as HTMLElement - - _.INTERNALS.set(element, { - attributes: {}, - localName: name, - ownerDocument: this, - shadowInit: null as unknown as ShadowRootInit, - shadowRoot: null as unknown as ShadowRoot, - } as ElementInternals) - - return element - } - - createNodeIterator( - root: Node, - whatToShow: number = NodeFilter.SHOW_ALL, - filter?: NodeIteratorInternals['filter'] - ) { - const target = Object.create(NodeIterator.prototype) - - _.INTERNALS.set(target, { - filter, - pointerBeforeReferenceNode: false, - referenceNode: root, - root, - whatToShow, - } as NodeIteratorInternals) - - return target - } - - createTextNode(data: string) { - return new Text(data) - } - - createTreeWalker( - root: Node, - whatToShow: number = NodeFilter.SHOW_ALL, - filter?: NodeFilter, - expandEntityReferences?: boolean - ) { - const target = Object.create(TreeWalker.prototype) - - _.INTERNALS.set(target, { - filter, - currentNode: root, - root, - whatToShow, - } as TreeWalkerInternals) - - return target - } - - get adoptedStyleSheets(): StyleSheet[] { - return [] - } - - get styleSheets(): StyleSheet[] { - return [] - } - - body!: HTMLBodyElement - documentElement!: HTMLHtmlElement - head!: HTMLHeadElement -} - -export class HTMLDocument extends Document {} - -_.allowStringTag(Document) -_.allowStringTag(HTMLDocument) - -export const initDocument = (target: Target, exclude: Set) => { - if (exclude.has('document')) return - - const EventTarget = target.EventTarget || globalThis.EventTarget - const HTMLDocument = target.HTMLDocument || globalThis.HTMLDocument - - const document: HTMLDocument = (target.document = Object.setPrototypeOf( - new EventTarget(), - HTMLDocument.prototype - )) - - _.INTERNALS.set(document, { - target, - constructorByName: new Map([ - ['body', target.HTMLBodyElement], - ['canvas', target.HTMLCanvasElement], - ['div', target.HTMLDivElement], - ['head', target.HTMLHeadElement], - ['html', target.HTMLHtmlElement], - ['img', target.HTMLImageElement], - ['span', target.HTMLSpanElement], - ['style', target.HTMLStyleElement], - ]), - nameByConstructor: new Map(), - } as DocumentInternals) - - const initElement = (name: string, Class: Function) => { - const target = Object.setPrototypeOf(new EventTarget(), Class.prototype) - - _.INTERNALS.set(target, { - attributes: {}, - localName: name, - ownerDocument: document, - shadowRoot: null as unknown as ShadowRoot, - shadowInit: null as unknown as ShadowRootInit, - } as ElementInternals) - - return target - } - - document.body = initElement('body', target.HTMLBodyElement) as HTMLBodyElement - document.head = initElement('head', target.HTMLHeadElement) as HTMLHeadElement - document.documentElement = initElement( - 'html', - target.HTMLHtmlElement - ) as HTMLHtmlElement -} - -interface DocumentInternals { - body: HTMLBodyElement - documentElement: HTMLHtmlElement - head: HTMLHeadElement - constructorByName: Map - nameByConstructor: Map - target: Target -} - -interface CustomElementRegistryInternals { - constructorByName: Map - nameByConstructor: Map -} - -interface ElementInternals { - attributes: { [name: string]: string } - localName: string - ownerDocument: Document - shadowRoot: ShadowRoot - shadowInit: ShadowRootInit -} - -interface ShadowRootInit extends Record { - mode?: string -} - -interface Target extends Record { - HTMLBodyElement: typeof HTMLBodyElement - HTMLDivElement: typeof HTMLDivElement - HTMLElement: typeof HTMLElement - HTMLHeadElement: typeof HTMLHeadElement - HTMLHtmlElement: typeof HTMLHtmlElement - HTMLSpanElement: typeof HTMLSpanElement - HTMLStyleElement: typeof HTMLStyleElement - customElements: CustomElementRegistry - document: DocumentInternals -} - -interface NodeIteratorInternals { - filter: NodeFilter - pointerBeforeReferenceNode: boolean - referenceNode: Node - root: Node - whatToShow: number -} - -interface TreeWalkerInternals { - filter: NodeFilter - currentNode: Node - root: Node - whatToShow: number -} diff --git a/packages/webapi/src/lib/Element.ts b/packages/webapi/src/lib/Element.ts deleted file mode 100644 index 013571e63802..000000000000 --- a/packages/webapi/src/lib/Element.ts +++ /dev/null @@ -1,166 +0,0 @@ -import * as _ from './utils' - -export class Element extends Node { - constructor() { - super() - - if (_.INTERNALS.has(new.target)) { - const internals = _.internalsOf(new.target, 'Element', 'localName') - _.INTERNALS.set(this, { - attributes: {}, - localName: (internals as unknown as Element).localName, - ownerDocument: this.ownerDocument, - shadowInit: null as unknown as ShadowRootInit, - shadowRoot: null as unknown as ShadowRoot, - } as ElementInternals) - } - } - - hasAttribute(name: string): boolean { - void name - - return false - } - - getAttribute(name: string): string | null { - return null - } - - setAttribute(name: string, value: string): void { - void name - void value - } - - removeAttribute(name: string): void { - void name - } - - attachShadow(init: Partial) { - if (arguments.length < 1) - throw new TypeError( - `Failed to execute 'attachShadow' on 'Element': 1 argument required, but only 0 present.` - ) - - if (init !== Object(init)) - throw new TypeError( - `Failed to execute 'attachShadow' on 'Element': The provided value is not of type 'ShadowRootInit'.` - ) - - if (init.mode !== 'open' && init.mode !== 'closed') - throw new TypeError( - `Failed to execute 'attachShadow' on 'Element': Failed to read the 'mode' property from 'ShadowRootInit': The provided value '${init.mode}' is not a valid enum value of type ShadowRootMode.` - ) - - const internals = _.internalsOf( - this, - 'Element', - 'attachShadow' - ) - - if (internals.shadowRoot) throw new Error('The operation is not supported.') - - internals.shadowInit = internals.shadowInit || { - mode: init.mode, - delegatesFocus: Boolean(init.delegatesFocus), - } - - internals.shadowRoot = - internals.shadowRoot || - (/^open$/.test(internals.shadowInit.mode as string) - ? (Object.setPrototypeOf( - new EventTarget(), - ShadowRoot.prototype - ) as ShadowRoot) - : null) - - return internals.shadowRoot - } - - get assignedSlot(): HTMLSlotElement | null { - return null - } - - get innerHTML(): string { - _.internalsOf(this, 'Element', 'innerHTML') - - return '' - } - - set innerHTML(value) { - _.internalsOf(this, 'Element', 'innerHTML') - - void value - } - - get shadowRoot(): ShadowRoot | null { - const internals = _.internalsOf( - this, - 'Element', - 'shadowRoot' - ) - - return Object(internals.shadowInit).mode === 'open' - ? internals.shadowRoot - : null - } - - get localName(): string { - return _.internalsOf(this, 'Element', 'localName') - .localName as string - } - - get nodeName(): string { - return ( - _.internalsOf(this, 'Element', 'nodeName') - .localName as string - ).toUpperCase() - } - - get tagName(): string { - return ( - _.internalsOf(this, 'Element', 'tagName') - .localName as string - ).toUpperCase() - } -} - -export class HTMLElement extends Element {} - -export class HTMLBodyElement extends HTMLElement {} - -export class HTMLDivElement extends HTMLElement {} - -export class HTMLHeadElement extends HTMLElement {} - -export class HTMLHtmlElement extends HTMLElement {} - -export class HTMLSpanElement extends HTMLElement {} - -export class HTMLStyleElement extends HTMLElement {} - -export class HTMLTemplateElement extends HTMLElement {} - -export class HTMLUnknownElement extends HTMLElement {} - -_.allowStringTag(Element) -_.allowStringTag(HTMLElement) -_.allowStringTag(HTMLBodyElement) -_.allowStringTag(HTMLDivElement) -_.allowStringTag(HTMLHeadElement) -_.allowStringTag(HTMLHtmlElement) -_.allowStringTag(HTMLSpanElement) -_.allowStringTag(HTMLStyleElement) -_.allowStringTag(HTMLTemplateElement) -_.allowStringTag(HTMLUnknownElement) - -export interface ElementInternals { - attributes: { [name: string]: string } - localName?: string - shadowRoot: ShadowRoot | null - shadowInit: ShadowRootInit | void -} - -export interface ShadowRootInit { - mode: 'open' | 'closed' - delegatesFocus: boolean -} diff --git a/packages/webapi/src/lib/HTMLCanvasElement.ts b/packages/webapi/src/lib/HTMLCanvasElement.ts deleted file mode 100644 index a38471498f90..000000000000 --- a/packages/webapi/src/lib/HTMLCanvasElement.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { CanvasRenderingContext2D } from './CanvasRenderingContext2D' - -import { __createCanvasRenderingContext2D } from './CanvasRenderingContext2D' -import * as _ from './utils' - -export class HTMLCanvasElement extends HTMLElement { - get height(): number { - return _.internalsOf(this, 'HTMLCanvasElement', 'height').height - } - - set height(value) { - _.internalsOf(this, 'HTMLCanvasElement', 'height').height = - Number(value) || 0 - } - - get width(): number { - return _.internalsOf(this, 'HTMLCanvasElement', 'width').width - } - - set width(value) { - _.internalsOf(this, 'HTMLCanvasElement', 'width').width = Number(value) || 0 - } - - captureStream(): null { - return null - } - - getContext( - contextType: PredefinedContextId - ): CanvasRenderingContext2D | null { - const internals = _.internalsOf( - this, - 'HTMLCanvasElement', - 'getContext' - ) - - switch (contextType) { - case '2d': - if (internals.renderingContext2D) return internals.renderingContext2D - - internals.renderingContext2D = __createCanvasRenderingContext2D(this) - - return internals.renderingContext2D - default: - return null - } - } - - toBlob() {} - - toDataURL() {} - - transferControlToOffscreen() {} -} - -_.allowStringTag(HTMLCanvasElement) - -interface HTMLCanvasElementInternals { - width: number - height: number - renderingContext2D: CanvasRenderingContext2D -} - -type PredefinedContextId = - | '2d' - | 'bitmaprenderer' - | 'webgl' - | 'webgl2' - | 'webgpu' diff --git a/packages/webapi/src/lib/HTMLImageElement.ts b/packages/webapi/src/lib/HTMLImageElement.ts deleted file mode 100644 index fd9e5f6059a1..000000000000 --- a/packages/webapi/src/lib/HTMLImageElement.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { HTMLElement } from './Element' -import * as _ from './utils' - -export class HTMLImageElement extends HTMLElement { - get src(): string { - return _.internalsOf(this, 'HTMLImageElement', 'src').src - } - - set src(value) { - const internals = _.internalsOf(this, 'HTMLImageElement', 'src') - - internals.src = String(value) - } -} - -_.allowStringTag(HTMLImageElement) diff --git a/packages/webapi/src/lib/IdleCallback.ts b/packages/webapi/src/lib/IdleCallback.ts deleted file mode 100644 index bc73f22f1392..000000000000 --- a/packages/webapi/src/lib/IdleCallback.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - clearTimeout as nodeClearTimeout, - setTimeout as nodeSetTimeout, -} from 'node:timers' -import * as _ from './utils.js' - -const INTERNAL = { tick: 0, pool: new Map() } - -export function requestIdleCallback< - TArgs extends any[], - TFunc extends (...args: TArgs) => any ->(callback: TFunc): number { - if (!INTERNAL.pool.size) { - nodeSetTimeout(() => { - const next = _.__performance_now() - - for (const func of INTERNAL.pool.values()) { - func(next) - } - - INTERNAL.pool.clear() - }, 1000 / 16) - } - - const func = _.__function_bind(callback, undefined) - const tick = ++INTERNAL.tick - - INTERNAL.pool.set(tick, func) - - return tick -} - -export function cancelIdleCallback(requestId: number): void { - const timeout = INTERNAL.pool.get(requestId) - - if (timeout) { - nodeClearTimeout(timeout) - - INTERNAL.pool.delete(requestId) - } -} diff --git a/packages/webapi/src/lib/Image.ts b/packages/webapi/src/lib/Image.ts deleted file mode 100644 index c2e0a10fb357..000000000000 --- a/packages/webapi/src/lib/Image.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { HTMLImageElement } from './HTMLImageElement' -import * as _ from './utils' - -export function Image() { - // @ts-expect-error - _.INTERNALS.set(this, { - attributes: {}, - localName: 'img', - innerHTML: '', - shadowRoot: null, - shadowInit: null, - }) -} - -Image.prototype = HTMLImageElement.prototype diff --git a/packages/webapi/src/lib/ImageData.ts b/packages/webapi/src/lib/ImageData.ts deleted file mode 100644 index 595b5023fe5e..000000000000 --- a/packages/webapi/src/lib/ImageData.ts +++ /dev/null @@ -1,111 +0,0 @@ -import * as _ from './utils' - -export class ImageData { - constructor(width: number, height: number) - constructor(width: number, height: number, settings: ImageDataSettings) - constructor(data: Uint8ClampedArray, width: number) - constructor(data: Uint8ClampedArray, width: number, height: number) - constructor( - data: Uint8ClampedArray, - width: number, - height: number, - settings: ImageDataSettings - ) - - constructor( - arg0: number | Uint8ClampedArray, - arg1: number, - ...args: [] | [number] | [ImageDataSettings] | [number, ImageDataSettings] - ) { - if (arguments.length < 2) - throw new TypeError( - `Failed to construct 'ImageData': 2 arguments required.` - ) - - /** Whether Uint8ClampedArray data is provided. */ - const hasData = _.__object_isPrototypeOf(Uint8ClampedArray.prototype, arg0) - - /** Image data, either provided or calculated. */ - const d = hasData - ? (arg0 as Uint8ClampedArray) - : new Uint8ClampedArray( - asNumber(arg0, 'width') * asNumber(arg1, 'height') * 4 - ) - - /** Image width. */ - const w = asNumber(hasData ? arg1 : arg0, 'width') - - /** Image height. */ - const h = d.length / w / 4 - - /** Image color space. */ - const c = String( - Object(hasData ? args[1] : args[0]).colorSpace || 'srgb' - ) as PredefinedColorSpace - - // throw if a provided height does not match the calculated height - if (args.length && asNumber(args[0], 'height') !== h) - throw new DOMException( - 'height is not equal to (4 * width * height)', - 'IndexSizeError' - ) - - // throw if a provided colorspace does not match a known colorspace - if (c !== 'srgb' && c !== 'rec2020' && c !== 'display-p3') - throw new TypeError('colorSpace is not known value') - - Object.defineProperty(this, 'data', { - configurable: true, - enumerable: true, - value: d, - }) - - _.INTERNALS.set(this, { - width: w, - height: h, - colorSpace: c, - } as ImageDataInternals) - } - - get data(): Uint8ClampedArray { - _.internalsOf(this, 'ImageData', 'data') - - return ( - Object.getOwnPropertyDescriptor(this, 'data') as { - value: Uint8ClampedArray - } - ).value - } - - get width(): ImageDataInternals['width'] { - return _.internalsOf(this, 'ImageData', 'width').width - } - - get height(): ImageDataInternals['height'] { - return _.internalsOf(this, 'ImageData', 'height').height - } -} - -_.allowStringTag(ImageData) - -/** Returns a coerced number, optionally throwing if the number is zero-ish. */ -const asNumber = (value: any, axis: string): number => { - value = Number(value) || 0 - - if (value === 0) - throw new TypeError(`The source ${axis} is zero or not a number.`) - - return value -} - -interface ImageDataInternals { - colorSpace: PredefinedColorSpace - height: number - width: number -} - -interface ImageDataSettings { - colorSpace?: PredefinedColorSpace -} - -type PredefinedColorSpace = 'srgb' | 'rec2020' | 'display-p3' diff --git a/packages/webapi/src/lib/MediaQueryList.ts b/packages/webapi/src/lib/MediaQueryList.ts deleted file mode 100644 index cc9137183330..000000000000 --- a/packages/webapi/src/lib/MediaQueryList.ts +++ /dev/null @@ -1,40 +0,0 @@ -import * as _ from './utils' - -export class MediaQueryList extends EventTarget { - get matches(): boolean { - return _.internalsOf(this, 'MediaQueryList', 'matches').matches - } - - get media(): string { - return _.internalsOf(this, 'MediaQueryList', 'media').media - } -} - -_.allowStringTag(MediaQueryList) - -export const initMediaQueryList = (target: Target, exclude: Set) => { - if (exclude.has('MediaQueryList') || exclude.has('matchMedia')) return - - const EventTarget = target.EventTarget || globalThis.EventTarget - const MediaQueryList = target.MediaQueryList || globalThis.MediaQueryList - - target.matchMedia = function matchMedia(media: string) { - const mql = Object.setPrototypeOf( - new EventTarget(), - MediaQueryList.prototype - ) as MediaQueryList - - _.INTERNALS.set(mql, { - matches: false, - media, - }) - - return mql - } -} - -interface Target extends Record { - matchMedia: { - (media: string): MediaQueryList - } -} diff --git a/packages/webapi/src/lib/Node.ts b/packages/webapi/src/lib/Node.ts deleted file mode 100644 index 464404b34870..000000000000 --- a/packages/webapi/src/lib/Node.ts +++ /dev/null @@ -1,192 +0,0 @@ -import * as _ from './utils' - -export class Node extends EventTarget { - append(...nodesOrDOMStrings: NodeOrString[]): void { - void nodesOrDOMStrings - } - - appendChild(childNode: Node): Node { - return childNode - } - - after(...nodesOrDOMStrings: NodeOrString[]): void { - void nodesOrDOMStrings - } - - before(...nodesOrDOMStrings: NodeOrString[]): void { - void nodesOrDOMStrings - } - - prepend(...nodesOrDOMStrings: NodeOrString[]): void { - void nodesOrDOMStrings - } - - replaceChild(newChild: Node, oldChild: Node): Node { - void newChild - - return oldChild - } - - removeChild(childNode: Node): Node { - return childNode - } - - get attributes(): object { - return {} - } - - get childNodes(): Node[] { - return [] - } - - get children(): Element[] { - return [] - } - - get ownerDocument(): Node | null { - return null - } - - get nodeValue(): string { - return '' - } - - set nodeValue(value: string) { - void value - } - - get textContent(): string { - return '' - } - - set textContent(value: string) { - void value - } - - get previousElementSibling(): Node | null { - return null - } - - get nextElementSibling(): Node | null { - return null - } - - [Symbol.for('nodejs.util.inspect.custom')]( - depth: number, - options: Record - ) { - return `${this.constructor.name}` - } -} - -export class DocumentFragment extends Node {} - -export class ShadowRoot extends DocumentFragment { - get innerHTML() { - return '' - } - - set innerHTML(value: string) { - void value - } -} - -export const NodeFilter = Object.assign( - { - NodeFilter() { - throw new TypeError('Illegal constructor') - }, - }.NodeFilter, - { - FILTER_ACCEPT: 1, - FILTER_REJECT: 2, - FILTER_SKIP: 3, - SHOW_ALL: 4294967295, - SHOW_ELEMENT: 1, - SHOW_ATTRIBUTE: 2, - SHOW_TEXT: 4, - SHOW_CDATA_SECTION: 8, - SHOW_ENTITY_REFERENCE: 16, - SHOW_ENTITY: 32, - SHOW_PROCESSING_INSTRUCTION: 64, - SHOW_COMMENT: 128, - SHOW_DOCUMENT: 256, - SHOW_DOCUMENT_TYPE: 512, - SHOW_DOCUMENT_FRAGMENT: 1024, - SHOW_NOTATION: 2048, - } -) - -export class NodeIterator { - nextNode(): Node | null { - return null - } - - previousNode(): Node | null { - return null - } - - get filter(): NodeFilter { - const internals = _.internalsOf( - this, - 'NodeIterator', - 'filter' - ) - return internals.filter - } - - get pointerBeforeReferenceNode(): boolean { - const internals = _.internalsOf( - this, - 'NodeIterator', - 'pointerBeforeReferenceNode' - ) - return internals.pointerBeforeReferenceNode - } - - get referenceNode(): Node { - const internals = _.internalsOf( - this, - 'NodeIterator', - 'referenceNode' - ) - return internals.referenceNode - } - - get root(): Node { - const internals = _.internalsOf( - this, - 'NodeIterator', - 'root' - ) - return internals.root - } - - get whatToShow(): number { - const internals = _.internalsOf( - this, - 'NodeIterator', - 'whatToShow' - ) - return internals.whatToShow - } -} - -_.allowStringTag(Node) -_.allowStringTag(NodeIterator) -_.allowStringTag(DocumentFragment) -_.allowStringTag(ShadowRoot) - -type NodeOrString = string | Node - -export interface NodeFilter { - acceptNode(node: Node): number -} - -export interface NodeIteratorInternals { - filter: NodeFilter - pointerBeforeReferenceNode: boolean - referenceNode: Node - root: Node - whatToShow: number -} diff --git a/packages/webapi/src/lib/Observer.ts b/packages/webapi/src/lib/Observer.ts deleted file mode 100644 index 845de13127ad..000000000000 --- a/packages/webapi/src/lib/Observer.ts +++ /dev/null @@ -1,41 +0,0 @@ -import * as _ from './utils' - -export class IntersectionObserver { - disconnect() {} - - observe() {} - - takeRecords() { - return [] - } - - unobserve() {} -} - -export class MutationObserver { - disconnect() {} - - observe() {} - - takeRecords() { - return [] - } - - unobserve() {} -} - -export class ResizeObserver { - disconnect() {} - - observe() {} - - takeRecords() { - return [] - } - - unobserve() {} -} - -_.allowStringTag(MutationObserver) -_.allowStringTag(IntersectionObserver) -_.allowStringTag(ResizeObserver) diff --git a/packages/webapi/src/lib/OffscreenCanvas.ts b/packages/webapi/src/lib/OffscreenCanvas.ts deleted file mode 100644 index e799f72105bc..000000000000 --- a/packages/webapi/src/lib/OffscreenCanvas.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type { CanvasRenderingContext2D } from './CanvasRenderingContext2D' - -import { __createCanvasRenderingContext2D } from './CanvasRenderingContext2D' -import * as _ from './utils' - -export class OffscreenCanvas extends EventTarget { - constructor(width: number, height: number) { - super() - - if (arguments.length < 2) - throw new TypeError( - `Failed to construct 'OffscreenCanvas': 2 arguments required.` - ) - - width = Number(width) || 0 - height = Number(height) || 0 - - _.INTERNALS.set(this, { width, height } as OffscreenCanvasInternals) - } - - get height(): number { - return _.internalsOf(this, 'OffscreenCanvas', 'height').height - } - - set height(value) { - _.internalsOf(this, 'OffscreenCanvas', 'height').height = Number(value) || 0 - } - - get width(): number { - return _.internalsOf(this, 'OffscreenCanvas', 'width').width - } - - set width(value) { - _.internalsOf(this, 'OffscreenCanvas', 'width').width = Number(value) || 0 - } - - getContext( - contextType: PredefinedContextId - ): CanvasRenderingContext2D | null { - const internals = _.internalsOf( - this, - 'HTMLCanvasElement', - 'getContext' - ) - - switch (contextType) { - case '2d': - if (internals.renderingContext2D) return internals.renderingContext2D - - internals.renderingContext2D = __createCanvasRenderingContext2D(this) - - return internals.renderingContext2D - default: - return null - } - } - - convertToBlob(options: Partial) { - options = Object(options) - - const quality = Number(options.quality) || 0 - const type = getImageType(String(options.type).trim().toLowerCase()) - - void quality - - return Promise.resolve(new Blob([], { type })) - } -} - -_.allowStringTag(OffscreenCanvas) - -const getImageType = (type: string): PredefinedImageType => - type === 'image/avif' || - type === 'image/jpeg' || - type === 'image/png' || - type === 'image/webp' - ? type - : 'image/png' - -interface OffscreenCanvasInternals { - height: number - renderingContext2D: CanvasRenderingContext2D - width: number -} - -interface ConvertToBlobOptions { - quality: number - type: PredefinedImageType -} - -type PredefinedContextId = - | '2d' - | 'bitmaprenderer' - | 'webgl' - | 'webgl2' - | 'webgpu' - -type PredefinedImageType = - | 'image/avif' - | 'image/jpeg' - | 'image/png' - | 'image/webp' diff --git a/packages/webapi/src/lib/Storage.ts b/packages/webapi/src/lib/Storage.ts deleted file mode 100644 index 7f9426552677..000000000000 --- a/packages/webapi/src/lib/Storage.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as _ from './utils' - -export class Storage { - clear(): void { - _.internalsOf(this, 'Storage', 'clear').storage.clear() - } - - getItem(key: string): string | null { - return getStringOrNull( - _.internalsOf(this, 'Storage', 'getItem').storage.get( - String(key) - ) - ) - } - - key(index: number): string | null { - return getStringOrNull( - [ - ..._.internalsOf( - this, - 'Storage', - 'key' - ).storage.keys(), - ][Number(index) || 0] - ) - } - - removeItem(key: string): void { - _.internalsOf(this, 'Storage', 'getItem').storage.delete( - String(key) - ) - } - - setItem(key: string, value: any): void { - _.internalsOf(this, 'Storage', 'getItem').storage.set( - String(key), - String(value) - ) - } - - get length() { - return _.internalsOf(this, 'Storage', 'size').storage.size - } -} - -const getStringOrNull = (value: string | void) => - typeof value === 'string' ? value : null - -export const initStorage = (target: Target, exclude: Set) => { - if (exclude.has('Storage') || exclude.has('localStorage')) return - - target.localStorage = Object.create(Storage.prototype) - - const storageInternals = new Map() - - _.INTERNALS.set(target.localStorage, { - storage: storageInternals, - } as StorageInternals) -} - -interface StorageInternals { - storage: Map -} - -interface Target { - localStorage: Storage -} diff --git a/packages/webapi/src/lib/StyleSheet.ts b/packages/webapi/src/lib/StyleSheet.ts deleted file mode 100644 index d4b2d9e338fc..000000000000 --- a/packages/webapi/src/lib/StyleSheet.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as _ from './utils' - -export class StyleSheet {} - -export class CSSStyleSheet extends StyleSheet { - async replace(text: string) { - void text - - return new CSSStyleSheet() - } - - replaceSync(text: string) { - void text - - return new CSSStyleSheet() - } - - get cssRules() { - return [] - } -} - -_.allowStringTag(StyleSheet) -_.allowStringTag(CSSStyleSheet) diff --git a/packages/webapi/src/lib/Timeout.ts b/packages/webapi/src/lib/Timeout.ts deleted file mode 100644 index 2ad4f153e7e1..000000000000 --- a/packages/webapi/src/lib/Timeout.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - clearTimeout as nodeClearTimeout, - setTimeout as nodeSetTimeout, -} from 'node:timers' -import * as _ from './utils.js' - -const INTERNAL = { tick: 0, pool: new Map() } - -export function setTimeout< - TArgs extends any[], - TFunc extends (...args: TArgs) => any ->(callback: TFunc, delay = 0, ...args: TArgs): number { - const func = _.__function_bind(callback, globalThis) - const tick = ++INTERNAL.tick - const timeout = nodeSetTimeout(func as any, delay, ...args) - - INTERNAL.pool.set(tick, timeout) - - return tick -} - -export function clearTimeout(timeoutId: number): void { - const timeout = INTERNAL.pool.get(timeoutId) - - if (timeout) { - nodeClearTimeout(timeout) - - INTERNAL.pool.delete(timeoutId) - } -} diff --git a/packages/webapi/src/lib/TreeWalker.ts b/packages/webapi/src/lib/TreeWalker.ts deleted file mode 100644 index 4233970226a7..000000000000 --- a/packages/webapi/src/lib/TreeWalker.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as _ from './utils' - -export class TreeWalker { - parentNode(): Node | null { - return null - } - - firstChild(): Node | null { - return null - } - - lastChild(): Node | null { - return null - } - - previousSibling(): Node | null { - return null - } - - nextSibling(): Node | null { - return null - } - - previousNode(): Node | null { - return null - } - - nextNode(): Node | null { - return null - } - - get currentNode(): Node { - const internals = _.internalsOf( - this, - 'TreeWalker', - 'currentNode' - ) - return internals.currentNode - } - - get root(): Node { - const internals = _.internalsOf( - this, - 'TreeWalker', - 'root' - ) - return internals.root - } - - get whatToShow(): number { - const internals = _.internalsOf( - this, - 'TreeWalker', - 'whatToShow' - ) - return internals.whatToShow - } -} - -_.allowStringTag(TreeWalker) - -export interface TreeWalkerInternals { - filter: NodeFilter - currentNode: Node - root: Node - whatToShow: number -} diff --git a/packages/webapi/src/lib/Window.ts b/packages/webapi/src/lib/Window.ts deleted file mode 100644 index ac3312c93b86..000000000000 --- a/packages/webapi/src/lib/Window.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as _ from './utils' - -export class Window extends EventTarget { - get self(): this { - return this - } - - get top(): this { - return this - } - - get window(): this { - return this - } - - get innerHeight(): number { - return 0 - } - - get innerWidth(): number { - return 0 - } - - get scrollX(): number { - return 0 - } - - get scrollY(): number { - return 0 - } -} - -_.allowStringTag(Window) - -export const initWindow = (target: Target, exclude: Set) => { - if (exclude.has('Window') || exclude.has('window')) return - - target.window = target -} - -export interface WindowInternals { - document: null - location: URL - window: this -} - -interface Target extends Record { - window: this -} diff --git a/packages/webapi/src/lib/structuredClone.ts b/packages/webapi/src/lib/structuredClone.ts deleted file mode 100644 index f51fb529f851..000000000000 --- a/packages/webapi/src/lib/structuredClone.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { deserialize } from '@ungap/structured-clone/esm/deserialize.js' -import { serialize } from '@ungap/structured-clone/esm/serialize.js' - -export default (any: any, options: any) => deserialize(serialize(any, options)) diff --git a/packages/webapi/src/lib/utils.ts b/packages/webapi/src/lib/utils.ts deleted file mode 100644 index 63a6bba7bb3e..000000000000 --- a/packages/webapi/src/lib/utils.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { performance } from 'node:perf_hooks' - -/** Returns the function bound to the given object. */ -export const __function_bind = Function.bind.bind( - Function.call as unknown as any -) as any>( - callback: TFunc, - thisArg: unknown, - ...args: TArgs -) => TFunc - -/** Returns whether the object prototype exists in another object. */ -export const __object_isPrototypeOf = Function.call.bind( - Object.prototype.isPrototypeOf -) as { (p: T1, v: T2): T2 extends T1 ? true : false } - -/** Current high resolution millisecond timestamp. */ -export const __performance_now = performance.now as () => number - -// @ts-expect-error -export const INTERNALS = new WeakMap() - -export const internalsOf = ( - target: T | object, - className: string, - propName: string -): T => { - const internals: T = INTERNALS.get(target) - - if (!internals) - throw new TypeError( - `${className}.${propName} can only be used on instances of ${className}` - ) - - return internals -} - -export const allowStringTag = (value: any) => - (value.prototype[Symbol.toStringTag] = value.name) - -/** Returns any kind of path as a posix path. */ -export const pathToPosix = (pathname: any) => - String(pathname == null ? '' : pathname) - .replace( - // convert slashes - /\\+/g, - '/' - ) - .replace( - // prefix a slash to drive letters - /^(?=[A-Za-z]:\/)/, - '/' - ) - .replace( - // encode path characters - /%/g, - '%25' - ) - .replace(/\n/g, '%0A') - .replace(/\r/g, '%0D') - .replace(/\t/g, '%09') diff --git a/packages/webapi/src/polyfill.ts b/packages/webapi/src/polyfill.ts deleted file mode 100644 index 5fadd5a686e7..000000000000 --- a/packages/webapi/src/polyfill.ts +++ /dev/null @@ -1,325 +0,0 @@ -import { - alert, - ByteLengthQueuingStrategy, - cancelAnimationFrame, - cancelIdleCallback, - CanvasRenderingContext2D, - CharacterData, - clearTimeout, - Comment, - CountQueuingStrategy, - crypto, - CSSStyleSheet, - CustomElementRegistry, - CustomEvent, - Document, - DocumentFragment, - DOMException, - Element, - Event, - EventTarget, - fetch, - File, - FormData, - Headers, - HTMLBodyElement, - HTMLCanvasElement, - HTMLDivElement, - HTMLDocument, - HTMLElement, - HTMLHeadElement, - HTMLHtmlElement, - HTMLImageElement, - HTMLSpanElement, - HTMLStyleElement, - HTMLTemplateElement, - HTMLUnknownElement, - Image, - ImageData, - initCustomElementRegistry, - initDocument, - initMediaQueryList, - initStorage, - initWindow, - IntersectionObserver, - MediaQueryList, - MutationObserver, - Node, - NodeFilter, - NodeIterator, - OffscreenCanvas, - ReadableByteStreamController, - ReadableStream, - ReadableStreamBYOBReader, - ReadableStreamBYOBRequest, - ReadableStreamDefaultController, - ReadableStreamDefaultReader, - Request, - requestAnimationFrame, - requestIdleCallback, - ResizeObserver, - Response, - setTimeout, - ShadowRoot, - Storage, - structuredClone, - StyleSheet, - Text, - TransformStream, - TreeWalker, - URLPattern, - Window, - WritableStream, - WritableStreamDefaultController, - WritableStreamDefaultWriter, -} from './ponyfill' - -import { exclusions } from './exclusions' -import { inheritance } from './inheritance' - -export { pathToPosix } from './lib/utils' -export { - alert, - ByteLengthQueuingStrategy, - cancelAnimationFrame, - cancelIdleCallback, - CanvasRenderingContext2D, - CharacterData, - clearTimeout, - Comment, - CountQueuingStrategy, - crypto, - CSSStyleSheet, - CustomElementRegistry, - CustomEvent, - Document, - DocumentFragment, - DOMException, - Element, - Event, - EventTarget, - fetch, - File, - FormData, - Headers, - HTMLBodyElement, - HTMLCanvasElement, - HTMLDivElement, - HTMLDocument, - HTMLElement, - HTMLHeadElement, - HTMLHtmlElement, - HTMLImageElement, - HTMLSpanElement, - HTMLStyleElement, - HTMLTemplateElement, - HTMLUnknownElement, - Image, - ImageData, - IntersectionObserver, - MediaQueryList, - MutationObserver, - Node, - NodeFilter, - NodeIterator, - OffscreenCanvas, - ReadableByteStreamController, - ReadableStream, - ReadableStreamBYOBReader, - ReadableStreamBYOBRequest, - ReadableStreamDefaultController, - ReadableStreamDefaultReader, - Request, - requestAnimationFrame, - requestIdleCallback, - ResizeObserver, - Response, - setTimeout, - ShadowRoot, - structuredClone, - StyleSheet, - Text, - TransformStream, - TreeWalker, - URLPattern, - Window, - WritableStream, - WritableStreamDefaultController, - WritableStreamDefaultWriter, -} from './ponyfill.js' - -export const polyfill = (target: any, options?: PolyfillOptions) => { - const webAPIs = { - ByteLengthQueuingStrategy, - CanvasRenderingContext2D, - CharacterData, - Comment, - CountQueuingStrategy, - CSSStyleSheet, - CustomElementRegistry, - CustomEvent, - Document, - DocumentFragment, - DOMException, - Element, - Event, - EventTarget, - File, - FormData, - HTMLDocument, - HTMLElement, - HTMLBodyElement, - HTMLCanvasElement, - HTMLDivElement, - HTMLHeadElement, - HTMLHtmlElement, - HTMLImageElement, - HTMLSpanElement, - HTMLStyleElement, - HTMLTemplateElement, - HTMLUnknownElement, - Headers, - IntersectionObserver, - Image, - ImageData, - MediaQueryList, - MutationObserver, - Node, - NodeFilter, - NodeIterator, - OffscreenCanvas, - ReadableByteStreamController, - ReadableStream, - ReadableStreamBYOBReader, - ReadableStreamBYOBRequest, - ReadableStreamDefaultController, - ReadableStreamDefaultReader, - Request, - ResizeObserver, - Response, - ShadowRoot, - Storage, - StyleSheet, - Text, - TransformStream, - TreeWalker, - URLPattern, - WritableStream, - WritableStreamDefaultController, - WritableStreamDefaultWriter, - Window, - - alert, - cancelAnimationFrame, - cancelIdleCallback, - clearTimeout, - crypto, - fetch, - requestAnimationFrame, - requestIdleCallback, - setTimeout, - structuredClone, - } - - // initialize exclude options - const excludeOptions = new Set( - typeof Object(options).exclude === 'string' - ? String(Object(options).exclude).trim().split(/\s+/) - : Array.isArray(Object(options).exclude) - ? Object(options).exclude.reduce( - (array: string[], entry: unknown) => - array.splice( - array.length, - 0, - ...(typeof entry === 'string' ? entry.trim().split(/\s+/) : []) - ) && array, - [] - ) - : [] - ) as Set - - // expand exclude options using exclusion shorthands - for (const excludeOption of excludeOptions) { - if (excludeOption in exclusions) { - for (const exclusion of exclusions[ - excludeOption as keyof typeof exclusions - ]) { - excludeOptions.add(exclusion) - } - } - } - - // apply each WebAPI - for (const name of Object.keys(webAPIs)) { - // skip WebAPIs that are excluded - if (excludeOptions.has(name)) continue - - // skip WebAPIs that are built-in - if (Object.hasOwnProperty.call(target, name)) continue - - // define WebAPIs on the target - Object.defineProperty(target, name, { - configurable: true, - enumerable: true, - writable: true, - value: webAPIs[name as keyof typeof webAPIs], - }) - } - - // ensure WebAPIs correctly inherit other WebAPIs - for (const name of Object.keys(webAPIs)) { - // skip WebAPIs that are excluded - if (excludeOptions.has(name)) continue - - // skip WebAPIs that do not extend other WebAPIs - if (!Object.hasOwnProperty.call(inheritance, name)) continue - - const Class = target[name] - const Super = target[inheritance[name as keyof typeof inheritance]] - - // skip WebAPIs that are not available - if (!Class || !Super) continue - - // skip WebAPIs that are already inherited correctly - if (Object.getPrototypeOf(Class.prototype) === Super.prototype) continue - - // define WebAPIs inheritance - Object.setPrototypeOf(Class.prototype, Super.prototype) - } - - if ( - !excludeOptions.has('HTMLDocument') && - !excludeOptions.has('HTMLElement') - ) { - initDocument(target, excludeOptions) - - if (!excludeOptions.has('CustomElementRegistry')) { - initCustomElementRegistry(target, excludeOptions) - } - } - - initMediaQueryList(target, excludeOptions) - initStorage(target, excludeOptions) - initWindow(target, excludeOptions) - - return target -} - -polyfill.internals = (target: any, name: string) => { - const init = { - CustomElementRegistry: initCustomElementRegistry, - Document: initDocument, - MediaQueryList: initMediaQueryList, - Storage: initStorage, - Window: initWindow, - } - - init[name as keyof typeof init](target, new Set()) - - return target -} - -interface PolyfillOptions { - exclude?: string | string[] - override?: Record -} diff --git a/packages/webapi/src/ponyfill.ts b/packages/webapi/src/ponyfill.ts deleted file mode 100644 index fcad54ebedbf..000000000000 --- a/packages/webapi/src/ponyfill.ts +++ /dev/null @@ -1,148 +0,0 @@ -// @ts-check -import { Event, EventTarget } from 'event-target-shim' // Look into removing when Node 18 is dropped for Node 20 -import { webcrypto as crypto } from 'node:crypto' // Remove when Node 18 is dropped for Node 20 -import { - ByteLengthQueuingStrategy, - CountQueuingStrategy, - ReadableByteStreamController, - ReadableStream, - ReadableStreamBYOBReader, - ReadableStreamBYOBRequest, - ReadableStreamDefaultController, - ReadableStreamDefaultReader, - TransformStream, - WritableStream, - WritableStreamDefaultController, - WritableStreamDefaultWriter, -} from 'node:stream/web' // Remove when Node 16 is dropped for Node 18. -import { File, FormData, Headers, Request, Response, fetch } from 'undici' // Remove when Node 16 is dropped for Node 18. -import { URLPattern } from 'urlpattern-polyfill' -import { - cancelAnimationFrame, - requestAnimationFrame, -} from './lib/AnimationFrame' -import { CharacterData, Comment, Text } from './lib/CharacterData' -import { CustomEvent } from './lib/CustomEvent' // Look into removing when Node 18 is dropped for Node 20 -import { DOMException } from './lib/DOMException' -import { cancelIdleCallback, requestIdleCallback } from './lib/IdleCallback' -import { clearTimeout, setTimeout } from './lib/Timeout' -import { TreeWalker } from './lib/TreeWalker' -import structuredClone from './lib/structuredClone' // Remove when Node 16 is dropped for Node 18. - -import { CanvasRenderingContext2D } from './lib/CanvasRenderingContext2D' -import { - CustomElementRegistry, - initCustomElementRegistry, -} from './lib/CustomElementRegistry' -import { Document, HTMLDocument, initDocument } from './lib/Document' -import { - Element, - HTMLBodyElement, - HTMLDivElement, - HTMLElement, - HTMLHeadElement, - HTMLHtmlElement, - HTMLSpanElement, - HTMLStyleElement, - HTMLTemplateElement, - HTMLUnknownElement, -} from './lib/Element' -import { HTMLCanvasElement } from './lib/HTMLCanvasElement' -import { HTMLImageElement } from './lib/HTMLImageElement' -import { Image } from './lib/Image' -import { ImageData } from './lib/ImageData' -import { MediaQueryList, initMediaQueryList } from './lib/MediaQueryList' -import { - DocumentFragment, - Node, - NodeFilter, - NodeIterator, - ShadowRoot, -} from './lib/Node' -import { - IntersectionObserver, - MutationObserver, - ResizeObserver, -} from './lib/Observer' -import { OffscreenCanvas } from './lib/OffscreenCanvas' -import { Storage, initStorage } from './lib/Storage' -import { CSSStyleSheet, StyleSheet } from './lib/StyleSheet' -import { Window, initWindow } from './lib/Window' - -import { alert } from './lib/Alert' - -export { - ByteLengthQueuingStrategy, - CSSStyleSheet, - CanvasRenderingContext2D, - CharacterData, - Comment, - CountQueuingStrategy, - CustomElementRegistry, - CustomEvent, - DOMException, - Document, - DocumentFragment, - Element, - Event, - EventTarget, - File, - FormData, - HTMLBodyElement, - HTMLCanvasElement, - HTMLDivElement, - HTMLDocument, - HTMLElement, - HTMLHeadElement, - HTMLHtmlElement, - HTMLImageElement, - HTMLSpanElement, - HTMLStyleElement, - HTMLTemplateElement, - HTMLUnknownElement, - Headers, - Image, - ImageData, - IntersectionObserver, - MediaQueryList, - MutationObserver, - Node, - NodeFilter, - NodeIterator, - OffscreenCanvas, - ReadableByteStreamController, - ReadableStream, - ReadableStreamBYOBReader, - ReadableStreamBYOBRequest, - ReadableStreamDefaultController, - ReadableStreamDefaultReader, - Request, - ResizeObserver, - Response, - ShadowRoot, - Storage, - StyleSheet, - Text, - TransformStream, - TreeWalker, - URLPattern, - Window, - WritableStream, - WritableStreamDefaultController, - WritableStreamDefaultWriter, - alert, - cancelAnimationFrame, - cancelIdleCallback, - clearTimeout, - crypto, - fetch, - initCustomElementRegistry, - initDocument, - initMediaQueryList, - initStorage, - initWindow, - requestAnimationFrame, - requestIdleCallback, - setTimeout, - structuredClone, -} diff --git a/packages/webapi/src/types.d.ts b/packages/webapi/src/types.d.ts deleted file mode 100644 index 3592b7d5af40..000000000000 --- a/packages/webapi/src/types.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare module 'node:*' -declare module '@ungap/structured-clone/esm/index.js' -declare module '@ungap/structured-clone/esm/deserialize.js' -declare module '@ungap/structured-clone/esm/serialize.js' diff --git a/packages/webapi/test/basic.js b/packages/webapi/test/basic.js deleted file mode 100644 index 9eb5864d59ad..000000000000 --- a/packages/webapi/test/basic.js +++ /dev/null @@ -1,87 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('Basic', () => { - before(() => polyfill(globalThis)) - - it('Globals exist', () => { - const webAPIs = [ - 'ByteLengthQueuingStrategy', - 'CSSStyleSheet', - 'CountQueuingStrategy', - 'CustomElementRegistry', - 'CustomEvent', - 'DOMException', - 'Document', - 'DocumentFragment', - 'Element', - 'Event', - 'EventTarget', - 'File', - 'FormData', - 'HTMLDocument', - 'HTMLElement', - 'HTMLDivElement', - 'HTMLHeadElement', - 'HTMLHtmlElement', - 'HTMLImageElement', - 'HTMLStyleElement', - 'HTMLTemplateElement', - 'HTMLUnknownElement', - 'Headers', - 'IntersectionObserver', - 'Image', - 'MediaQueryList', - 'MutationObserver', - 'Node', - 'ReadableByteStreamController', - 'ReadableStream', - 'ReadableStreamBYOBReader', - 'ReadableStreamBYOBRequest', - 'ReadableStreamDefaultController', - 'ReadableStreamDefaultReader', - 'Request', - 'Response', - 'ShadowRoot', - 'StyleSheet', - 'TransformStream', - 'WritableStream', - 'WritableStreamDefaultController', - 'WritableStreamDefaultWriter', - 'Window', - 'cancelAnimationFrame', - 'cancelIdleCallback', - 'clearTimeout', - 'fetch', - 'requestAnimationFrame', - 'requestIdleCallback', - 'setTimeout', - ] - - for (const name of webAPIs) { - expect(globalThis[name]).to.be.a('function') - } - }) - - it('Classes extend as expected', () => { - expect(HTMLElement.prototype).to.be.an.instanceof(Element) - expect(Element.prototype).to.be.an.instanceof(Node) - expect(Node.prototype).to.be.an.instanceof(EventTarget) - }) - - it('DOM Methods have no effect', () => { - const element = document.createElement('div') - - expect(element.innerHTML).to.be.empty - element.innerHTML = 'frozen' - expect(element.innerHTML).to.be.empty - - expect(element.textContent).to.be.empty - element.textContent = 'frozen' - expect(element.textContent).to.be.empty - }) - - it('globalThis.window === globalThis', () => { - expect(globalThis.window).to.equal(globalThis) - }) -}) diff --git a/packages/webapi/test/characterdata.js b/packages/webapi/test/characterdata.js deleted file mode 100644 index b9973db9fb19..000000000000 --- a/packages/webapi/test/characterdata.js +++ /dev/null @@ -1,42 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('CharacterData', () => { - const target = {} - - before(() => polyfill(target)) - - it('Includes CharacterData functionality', () => { - expect(target).to.have.property('CharacterData') - expect(target).to.have.property('Text') - expect(target).to.have.property('Comment') - }) - - it('Supports new Comment', () => { - expect(() => { - new target.Comment() - }).not.to.throw() - - expect(new target.Comment().constructor.name).to.equal('Comment') - expect(Object.prototype.toString.call(new target.Comment())).to.equal( - '[object Comment]' - ) - - expect(new target.Comment('hello').data).to.equal('hello') - expect(new target.Comment('hello').textContent).to.equal('hello') - }) - - it('Supports new Text', () => { - expect(() => { - new target.Text() - }).not.to.throw() - - expect(new target.Text().constructor.name).to.equal('Text') - expect(Object.prototype.toString.call(new target.Text())).to.equals( - '[object Text]' - ) - - expect(new target.Text('hello').data).to.equal('hello') - expect(new target.Text('hello').textContent).to.equal('hello') - }) -}) diff --git a/packages/webapi/test/elements.js b/packages/webapi/test/elements.js deleted file mode 100644 index f758559a5a65..000000000000 --- a/packages/webapi/test/elements.js +++ /dev/null @@ -1,70 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('Custom Elements', () => { - const target = {} - - beforeEach(() => polyfill(target)) - - it('Includes Custom Element functionality', () => { - expect(target).to.have.property('CustomElementRegistry') - expect(target).to.have.property('customElements') - expect(target).to.have.property('HTMLElement') - }) - - it('Supports Custom Element creation', () => { - const CustomElement = class HTMLCustomElement extends target.HTMLElement {} - - target.customElements.define('custom-element', CustomElement) - - expect(target.customElements.get('custom-element')).to.equal(CustomElement) - expect(target.customElements.getName(CustomElement)).to.equal( - 'custom-element' - ) - }) - - it('Supports Custom Elements created from Document', () => { - expect(target.document.body.localName).to.equal('body') - expect(target.document.body.tagName).to.equal('BODY') - - expect( - target.document.createElement('custom-element').constructor.name - ).to.equal('HTMLUnknownElement') - - const CustomElement = class HTMLCustomElement extends target.HTMLElement {} - - target.customElements.define('custom-element', CustomElement) - - expect( - target.document.createElement('custom-element').constructor.name - ).to.equal('HTMLCustomElement') - }) - - it('Supports Custom Elements with properties', () => { - const testSymbol = Symbol.for('webapi.test') - - const CustomElement = class HTMLCustomElement extends target.HTMLElement { - otherMethod = () => testSymbol - - method() { - return this.otherMethod() - } - - static method() { - return this.otherMethod() - } - - static otherMethod() { - return testSymbol - } - } - - target.customElements.define('custom-element', CustomElement) - - expect(CustomElement.method()).to.equal(testSymbol) - - const customElement = new CustomElement() - - expect(customElement.method()).to.equal(testSymbol) - }) -}) diff --git a/packages/webapi/test/fetch.js b/packages/webapi/test/fetch.js deleted file mode 100644 index ce0a2e700336..000000000000 --- a/packages/webapi/test/fetch.js +++ /dev/null @@ -1,40 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('Fetch', () => { - const target = {} - - before(() => polyfill(target)) - - it('Fetch functionality', () => { - expect(target).to.have.property('fetch').that.is.a('function') - }) - - it('Fetch with https', async () => { - const { fetch } = target - - const response = await fetch('https://astro.build') - - expect(response.constructor).to.equal(target.Response) - - const html = await response.text() - - expect(html).to.include(' { - const { fetch } = target - - const jsonURI = `data:application/json,${encodeURIComponent( - JSON.stringify({ - name: '@astrojs/webapi', - }) - )}` - - const response = await fetch(jsonURI) - - const json = await response.json() - - expect(json.name).to.equal('@astrojs/webapi') - }) -}) diff --git a/packages/webapi/test/imagedata.js b/packages/webapi/test/imagedata.js deleted file mode 100644 index b386a18d6f57..000000000000 --- a/packages/webapi/test/imagedata.js +++ /dev/null @@ -1,54 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('ImageData', () => { - const target = {} - - before(() => polyfill(target)) - - it('Supports ImageData', () => { - expect(target).to.have.property('ImageData').that.is.a('function') - }) - - it('Supports new (data: Uint8ClampedArray, width: number, height: number): ImageData', () => { - const w = 640 - const h = 480 - const d = new Uint8ClampedArray(w * h * 4) - - const id = new target.ImageData(d, w, h) - - expect(id.data).to.equal(d) - expect(id.width).to.equal(w) - expect(id.height).to.equal(h) - }) - - it('Supports new (data: Uint8ClampedArray, width: number): ImageData', () => { - const w = 640 - const h = 480 - const d = new Uint8ClampedArray(w * h * 4) - - const id = new target.ImageData(d, w) - - expect(id.data).to.equal(d) - expect(id.width).to.equal(w) - expect(id.height).to.equal(h) - }) - - it('Supports new (width: number, height: number): ImageData', () => { - const w = 640 - const h = 480 - - const id = new target.ImageData(w, h) - - expect(id.data).to.have.lengthOf(w * h * 4) - expect(id.width).to.equal(w) - expect(id.height).to.equal(h) - }) - - it('Supports Object.keys(new ImageData(640, 480))', () => { - const keys = Object.keys(new target.ImageData(640, 480)) - - expect(keys).to.have.lengthOf(1) - expect(keys[0]).to.equal('data') - }) -}) diff --git a/packages/webapi/test/internals.js b/packages/webapi/test/internals.js deleted file mode 100644 index 054b7e488faa..000000000000 --- a/packages/webapi/test/internals.js +++ /dev/null @@ -1,26 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -it('Includes polyfill.internals functionality', () => { - const target = {} - - polyfill(target, { exclude: 'window document' }) - - const pseudo = { ...target } - - expect(pseudo).to.not.have.property('document') - - const CustomElement = class extends pseudo.HTMLElement {} - - pseudo.customElements.define('custom-element', CustomElement) - - polyfill.internals(pseudo, 'Document') - - expect(pseudo).to.have.property('document') - - expect( - CustomElement.prototype.isPrototypeOf( - pseudo.document.createElement('custom-element') - ) - ).to.equal(true) -}) diff --git a/packages/webapi/test/media.js b/packages/webapi/test/media.js deleted file mode 100644 index e6e7b82d4103..000000000000 --- a/packages/webapi/test/media.js +++ /dev/null @@ -1,20 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('Media', () => { - const target = {} - - before(() => polyfill(target)) - - it('Includes MediaQueryList functionality', () => { - expect(target).to.have.property('MediaQueryList') - expect(target).to.have.property('matchMedia') - }) - - it('Supports matchMedia creation', () => { - const mql = target.matchMedia('(min-width: 640px)') - - expect(mql.matches).to.equal(false) - expect(mql.media).to.equal('(min-width: 640px)') - }) -}) diff --git a/packages/webapi/test/offscreencanvas.js b/packages/webapi/test/offscreencanvas.js deleted file mode 100644 index 6223e78e87d4..000000000000 --- a/packages/webapi/test/offscreencanvas.js +++ /dev/null @@ -1,39 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('OffscreenCanvas', () => { - const target = {} - - before(() => polyfill(target)) - - it('Supports OffscreenCanvas', () => { - expect(target).to.have.property('OffscreenCanvas').that.is.a('function') - }) - - it('Supports new (width: number, height: number): OffscreenCanvas', () => { - const w = 640 - const h = 480 - - const canvas = new target.OffscreenCanvas(w, h) - - expect(canvas.width).to.equal(w) - expect(canvas.height).to.equal(h) - }) - - it('Supports OffscreenCanvas#getContext', () => { - const w = 640 - const h = 480 - - const canvas = new target.OffscreenCanvas(w, h) - - const context = canvas.getContext('2d') - - expect(context.canvas).to.equal(canvas) - - const imageData = context.createImageData(w, h) - - expect(imageData.width).to.equal(w) - expect(imageData.height).to.equal(h) - expect(imageData.data).to.have.lengthOf(w * h * 4) - }) -}) diff --git a/packages/webapi/test/options.js b/packages/webapi/test/options.js deleted file mode 100644 index 0db1cbfe3e1f..000000000000 --- a/packages/webapi/test/options.js +++ /dev/null @@ -1,44 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('Options', () => { - it('Can exclude HTMLElement+', () => { - const target = {} - - polyfill(target, { - exclude: 'HTMLElement+', - }) - - expect(target).to.have.property('Event') - expect(target).to.have.property('EventTarget') - expect(target).to.have.property('Element') - expect(target).to.not.have.property('HTMLElement') - expect(target).to.not.have.property('HTMLDivElement') - }) - - it('Can exclude Event+', () => { - const target = {} - - polyfill(target, { - exclude: 'Event+', - }) - - expect(target).to.not.have.property('Event') - expect(target).to.not.have.property('EventTarget') - expect(target).to.not.have.property('Element') - expect(target).to.not.have.property('HTMLElement') - expect(target).to.not.have.property('HTMLDivElement') - }) - - it('Can exclude document', () => { - const target = {} - - polyfill(target, { - exclude: 'document', - }) - - expect(target).to.have.property('Document') - expect(target).to.have.property('HTMLDocument') - expect(target).to.not.have.property('document') - }) -}) diff --git a/packages/webapi/test/storage.js b/packages/webapi/test/storage.js deleted file mode 100644 index 9a185644a37e..000000000000 --- a/packages/webapi/test/storage.js +++ /dev/null @@ -1,32 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('Storage', () => { - const target = {} - - before(() => polyfill(target)) - - it('Includes Storage functionality', () => { - expect(target).to.have.property('Storage').that.is.a('function') - expect(target).to.have.property('localStorage').that.is.an('object') - }) - - it('Supports Storage methods', () => { - expect(target.localStorage.setItem('hello', 'world')).to.equal(undefined) - expect(target.localStorage.getItem('hello')).to.equal('world') - expect(target.localStorage.key(0)).to.equal('hello') - expect(target.localStorage.key(1)).to.equal(null) - expect(target.localStorage.length).to.equal(1) - expect(target.localStorage.setItem('world', 'hello')).to.equal(undefined) - expect(target.localStorage.key(1)).to.equal('world') - expect(target.localStorage.key(2)).to.equal(null) - expect(target.localStorage.length).to.equal(2) - expect(target.localStorage.removeItem('hello')).to.equal(undefined) - expect(target.localStorage.key(0)).to.equal('world') - expect(target.localStorage.key(1)).to.equal(null) - expect(target.localStorage.length).to.equal(1) - expect(target.localStorage.clear()).to.equal(undefined) - expect(target.localStorage.key(0)).to.equal(null) - expect(target.localStorage.length).to.equal(0) - }) -}) diff --git a/packages/webapi/test/structuredclone.js b/packages/webapi/test/structuredclone.js deleted file mode 100644 index 0503cf904109..000000000000 --- a/packages/webapi/test/structuredclone.js +++ /dev/null @@ -1,28 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('structuredClone', () => { - const target = {} - - before(() => polyfill(target)) - - it('Includes structuredClone', () => { - expect(target).to.have.property('structuredClone').that.is.a('function') - }) - - it('Supports structuredClone usage', () => { - const obj = { - foo: 'bar', - baz: { - qux: 'quux', - }, - } - - const clone = target.structuredClone(obj) - - expect(obj).to.not.equal(clone) - expect(obj.baz).to.not.equal(clone.baz) - - expect(obj.baz.qux).to.equal(clone.baz.qux) - }) -}) diff --git a/packages/webapi/test/urlpattern.js b/packages/webapi/test/urlpattern.js deleted file mode 100644 index b9ef6b31f50e..000000000000 --- a/packages/webapi/test/urlpattern.js +++ /dev/null @@ -1,19 +0,0 @@ -import { expect } from 'chai' -import { polyfill } from '../mod.js' - -describe('URLPattern', () => { - const target = {} - - before(() => polyfill(target)) - - it('Includes URLPattern', () => { - expect(target).to.have.property('URLPattern').that.is.a('function') - }) - - it('Supports URLPattern usage', () => { - const pattern = new target.URLPattern({ pathname: '/hello/:name' }) - const match = pattern.exec('https://example.com/hello/Deno') - - expect(match.pathname.groups).to.deep.equal({ name: 'Deno' }) - }) -}) diff --git a/packages/webapi/tsconfig.json b/packages/webapi/tsconfig.json deleted file mode 100644 index 2348c6bfb0d9..000000000000 --- a/packages/webapi/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "include": ["src/*"], - "exclude": ["node_modules"], - "compilerOptions": { - "target": "ES2022", - "module": "ES2022", - "moduleResolution": "node", - "esModuleInterop": true, - "declaration": true, - "declarationDir": ".", - "strict": true, - "sourceMap": true, - "declarationMap": true - } -} diff --git a/scripts/package.json b/scripts/package.json index 8a962b5c7fbd..e6b97f60fa71 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -8,7 +8,6 @@ "astro-scripts": "./index.js" }, "dependencies": { - "@astrojs/webapi": "workspace:*", "arg": "^5.0.2", "esbuild": "^0.18.16", "globby": "^12.2.0", diff --git a/scripts/smoke/cleanup.js b/scripts/smoke/cleanup.js index 0d7db79f3694..3b03951f938f 100644 --- a/scripts/smoke/cleanup.js +++ b/scripts/smoke/cleanup.js @@ -3,11 +3,8 @@ // @ts-check import { execa } from 'execa'; -import { polyfill } from '@astrojs/webapi'; -import { fileURLToPath } from 'node:url'; import { promises as fs } from 'node:fs'; - -polyfill(globalThis, { exclude: 'window document' }); +import { fileURLToPath } from 'node:url'; /* Configuration /* ========================================================================== */ diff --git a/scripts/smoke/index.js b/scripts/smoke/index.js index 9bdaff82045d..7ab78e286eb3 100644 --- a/scripts/smoke/index.js +++ b/scripts/smoke/index.js @@ -3,11 +3,8 @@ // @ts-check import { execa } from 'execa'; -import { polyfill } from '@astrojs/webapi'; -import { fileURLToPath } from 'node:url'; import { promises as fs } from 'node:fs'; - -polyfill(globalThis, { exclude: 'window document' }); +import { fileURLToPath } from 'node:url'; /** URL directory containing the entire project. */ const rootDir = new URL('../../', import.meta.url);