feat: remove webapi in favor of a smaller polyfill (#7840)

* feat: remove webapi in favor of a smaller polyfill

* test: remove old test

* test: 🤦‍♀️

* chore: changeset
This commit is contained in:
Erika 2023-07-27 18:24:39 +02:00 committed by Emanuele Stoppa
parent 7d2f311d42
commit 148e61d249
84 changed files with 37 additions and 3775 deletions

View file

@ -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.

View file

@ -2,7 +2,6 @@
packages/**/*.min.js
packages/**/dist/**/*
packages/**/fixtures/**/*
packages/webapi/**/*
packages/astro/vendor/vite/**/*
examples/**/*
scripts/**/*

View file

@ -22,5 +22,4 @@ benchmark/results/
.changeset
# Files
packages/webapi/mod.d.ts
pnpm-lock.yaml

View file

@ -23,7 +23,6 @@
"dev": "astro-scripts dev \"src/**/*.ts\""
},
"dependencies": {
"@astrojs/webapi": "workspace:*",
"server-destroy": "^1.0.1"
},
"peerDependencies": {

View file

@ -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);

View file

@ -73,7 +73,6 @@
}
},
"dependencies": {
"@astrojs/webapi": "workspace:*",
"astro-benchmark": "workspace:*"
},
"devDependencies": {

View file

@ -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",

View file

@ -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');

View file

@ -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,
});
}
}

View file

@ -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);
});
});

View file

@ -1,6 +0,0 @@
import { defineConfig } from 'astro/config';
import ceIntegration from '@test/custom-element-renderer';
export default defineConfig({
integrations: [ceIntegration()],
})

View file

@ -1 +0,0 @@
globalThis.somePolyfillHere = '';

View file

@ -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(),
});
},
},
};
}

View file

@ -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"
}
}

View file

@ -1,2 +0,0 @@
console.log('this is a polyfill');
export default {};

View file

@ -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}><template shadowroot="open" shadowrootmode="open">${el.shadowRoot.innerHTML}</template>${el.innerHTML}</${el.localName}>`
return {
html
};
}
export default {
check,
renderToStaticMarkup
};

View file

@ -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;
}
};

View file

@ -1,9 +0,0 @@
{
"name": "@test/custom-elements",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*",
"@test/custom-element-renderer": "workspace:*"
}
}

View file

@ -1,13 +0,0 @@
export const tagName = 'my-element';
class MyElement extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `<span id="custom">Hello from a custom element!</span>`;
this.innerHTML = `<div id="custom-light">Light dom!</div>`
}
}
customElements.define(tagName, MyElement);
export default MyElement;

View file

@ -1,16 +0,0 @@
---
import MyElement from '../components/my-element.js';
const title = 'My App';
---
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<MyElement />
</body>
</html>

View file

@ -1,15 +0,0 @@
---
import '../components/my-element.js';
const title = 'My App';
---
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<my-element></my-element>
</body>
</html>

View file

@ -1,11 +0,0 @@
---
let show = true
---
<html>
<head>
<title>Custom element not imported but nested</title>
</head>
<body>
{show && <client-only-element></client-only-element>}
</body>
</html>

View file

@ -1,14 +0,0 @@
---
const title = 'My App';
---
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<client-element></client-element>
</body>
</html>

View file

@ -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;

View file

@ -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"
},

View file

@ -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;

View file

@ -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"
},

View file

@ -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 {

View file

@ -52,7 +52,6 @@
},
"dependencies": {
"@astrojs/internal-helpers": "^0.1.2",
"@astrojs/webapi": "^2.2.0",
"@vercel/analytics": "^0.1.11",
"@vercel/nft": "^0.22.6",
"esbuild": "^0.18.16",

View file

@ -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);

View file

@ -1,2 +0,0 @@
mod.js
mod.js.map

View file

@ -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
<details>
<summary>See changes in 2.0.0-beta.1</summary>
### 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
</details>
## 2.0.0-beta.0
<details>
<summary>See changes in 2.0.0-beta.0</summary>
### 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
</details>
## 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

View file

@ -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.

View file

@ -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.

View file

@ -1,5 +0,0 @@
import { polyfill } from './mod.js'
export * from './mod.js'
polyfill(globalThis)

View file

@ -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<string, {
(...args: any[]): any;
}>;
}

View file

@ -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
}
}
]
}
}

View file

@ -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()

View file

@ -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'],
}

View file

@ -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

View file

@ -1,3 +0,0 @@
export function alert(...messages: any[]) {
console.log(...messages)
}

View file

@ -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)
}
}

View file

@ -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 = <T>(value: T) =>
(Object(value).data instanceof Uint8ClampedArray) as T extends ImageData
? true
: false

View file

@ -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<CharacterDataInternals>(this, 'CharacterData', 'data')
.data
}
get textContent(): string {
return _.internalsOf<CharacterDataInternals>(
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<CharacterDataInternals>(
this,
'CharacterData',
'textContent'
).data
}
}
_.allowStringTag(CharacterData)
_.allowStringTag(Text)
_.allowStringTag(Comment)
interface CharacterDataInternals {
data: string
}

View file

@ -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<CustomElementRegistryInternals>(
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<CustomElementRegistryInternals>(
this,
'CustomElementRegistry',
'get'
)
name = String(name).toLowerCase()
return internals.constructorByName.get(name)
}
getName(constructor: Function) {
const internals = _.internalsOf<CustomElementRegistryInternals>(
this,
'CustomElementRegistry',
'getName'
)
return internals.nameByConstructor.get(constructor)
}
}
_.allowStringTag(CustomElementRegistry)
interface CustomElementRegistryInternals {
constructorByName: Map<string, Function>
nameByConstructor: Map<Function, string>
}
interface ElementDefinitionOptions {
extends?: string | undefined
}
export const initCustomElementRegistry = (
target: Record<any, any>,
exclude: Set<string>
) => {
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)
}

View file

@ -1,26 +0,0 @@
import { Event } from 'event-target-shim'
import * as _ from './utils'
class CustomEvent<
TEventType extends string = string
> extends Event<TEventType> {
constructor(type: TEventType, params?: CustomEventInit) {
params = Object(params) as Required<CustomEventInit>
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
}

View file

@ -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)

View file

@ -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<DocumentInternals>(
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<string>) => {
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<string, Function>([
['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<string, Function>
nameByConstructor: Map<Function, string>
target: Target
}
interface CustomElementRegistryInternals {
constructorByName: Map<string, Function>
nameByConstructor: Map<Function, string>
}
interface ElementInternals {
attributes: { [name: string]: string }
localName: string
ownerDocument: Document
shadowRoot: ShadowRoot
shadowInit: ShadowRootInit
}
interface ShadowRootInit extends Record<any, any> {
mode?: string
}
interface Target extends Record<any, any> {
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
}

View file

@ -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<ShadowRootInit>) {
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<ElementInternals>(
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<ElementInternals>(this, 'Element', 'innerHTML')
return ''
}
set innerHTML(value) {
_.internalsOf<ElementInternals>(this, 'Element', 'innerHTML')
void value
}
get shadowRoot(): ShadowRoot | null {
const internals = _.internalsOf<ElementInternals>(
this,
'Element',
'shadowRoot'
)
return Object(internals.shadowInit).mode === 'open'
? internals.shadowRoot
: null
}
get localName(): string {
return _.internalsOf<ElementInternals>(this, 'Element', 'localName')
.localName as string
}
get nodeName(): string {
return (
_.internalsOf<ElementInternals>(this, 'Element', 'nodeName')
.localName as string
).toUpperCase()
}
get tagName(): string {
return (
_.internalsOf<ElementInternals>(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
}

View file

@ -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<HTMLCanvasElementInternals>(
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'

View file

@ -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)

View file

@ -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)
}
}

View file

@ -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

View file

@ -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<ImageDataInternals>(this, 'ImageData', 'data')
return (
Object.getOwnPropertyDescriptor(this, 'data') as {
value: Uint8ClampedArray
}
).value
}
get width(): ImageDataInternals['width'] {
return _.internalsOf<ImageDataInternals>(this, 'ImageData', 'width').width
}
get height(): ImageDataInternals['height'] {
return _.internalsOf<ImageDataInternals>(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'

View file

@ -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<string>) => {
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<any, any> {
matchMedia: {
(media: string): MediaQueryList
}
}

View file

@ -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<string, any>
) {
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<NodeIteratorInternals>(
this,
'NodeIterator',
'filter'
)
return internals.filter
}
get pointerBeforeReferenceNode(): boolean {
const internals = _.internalsOf<NodeIteratorInternals>(
this,
'NodeIterator',
'pointerBeforeReferenceNode'
)
return internals.pointerBeforeReferenceNode
}
get referenceNode(): Node {
const internals = _.internalsOf<NodeIteratorInternals>(
this,
'NodeIterator',
'referenceNode'
)
return internals.referenceNode
}
get root(): Node {
const internals = _.internalsOf<NodeIteratorInternals>(
this,
'NodeIterator',
'root'
)
return internals.root
}
get whatToShow(): number {
const internals = _.internalsOf<NodeIteratorInternals>(
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
}

View file

@ -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)

View file

@ -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<OffscreenCanvasInternals>(
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<ConvertToBlobOptions>) {
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'

View file

@ -1,67 +0,0 @@
import * as _ from './utils'
export class Storage {
clear(): void {
_.internalsOf<StorageInternals>(this, 'Storage', 'clear').storage.clear()
}
getItem(key: string): string | null {
return getStringOrNull(
_.internalsOf<StorageInternals>(this, 'Storage', 'getItem').storage.get(
String(key)
)
)
}
key(index: number): string | null {
return getStringOrNull(
[
..._.internalsOf<StorageInternals>(
this,
'Storage',
'key'
).storage.keys(),
][Number(index) || 0]
)
}
removeItem(key: string): void {
_.internalsOf<StorageInternals>(this, 'Storage', 'getItem').storage.delete(
String(key)
)
}
setItem(key: string, value: any): void {
_.internalsOf<StorageInternals>(this, 'Storage', 'getItem').storage.set(
String(key),
String(value)
)
}
get length() {
return _.internalsOf<StorageInternals>(this, 'Storage', 'size').storage.size
}
}
const getStringOrNull = (value: string | void) =>
typeof value === 'string' ? value : null
export const initStorage = (target: Target, exclude: Set<string>) => {
if (exclude.has('Storage') || exclude.has('localStorage')) return
target.localStorage = Object.create(Storage.prototype)
const storageInternals = new Map<string, string>()
_.INTERNALS.set(target.localStorage, {
storage: storageInternals,
} as StorageInternals)
}
interface StorageInternals {
storage: Map<string, string>
}
interface Target {
localStorage: Storage
}

View file

@ -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)

View file

@ -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)
}
}

View file

@ -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<TreeWalkerInternals>(
this,
'TreeWalker',
'currentNode'
)
return internals.currentNode
}
get root(): Node {
const internals = _.internalsOf<TreeWalkerInternals>(
this,
'TreeWalker',
'root'
)
return internals.root
}
get whatToShow(): number {
const internals = _.internalsOf<TreeWalkerInternals>(
this,
'TreeWalker',
'whatToShow'
)
return internals.whatToShow
}
}
_.allowStringTag(TreeWalker)
export interface TreeWalkerInternals {
filter: NodeFilter
currentNode: Node
root: Node
whatToShow: number
}

View file

@ -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<string>) => {
if (exclude.has('Window') || exclude.has('window')) return
target.window = target
}
export interface WindowInternals {
document: null
location: URL
window: this
}
interface Target extends Record<any, any> {
window: this
}

View file

@ -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))

View file

@ -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 <TArgs extends any[], TFunc extends (...args: TArgs) => 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 { <T1 extends object, T2>(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<unknown, any>()
export const internalsOf = <T extends object>(
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')

View file

@ -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<string>
// 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<string>())
return target
}
interface PolyfillOptions {
exclude?: string | string[]
override?: Record<string, { (...args: any[]): any }>
}

View file

@ -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,
}

View file

@ -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'

View file

@ -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)
})
})

View file

@ -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')
})
})

View file

@ -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)
})
})

View file

@ -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('<html')
})
it('Fetch with data', async () => {
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')
})
})

View file

@ -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')
})
})

View file

@ -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)
})

View file

@ -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)')
})
})

View file

@ -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)
})
})

View file

@ -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')
})
})

View file

@ -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)
})
})

View file

@ -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)
})
})

View file

@ -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' })
})
})

View file

@ -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
}
}

View file

@ -8,7 +8,6 @@
"astro-scripts": "./index.js"
},
"dependencies": {
"@astrojs/webapi": "workspace:*",
"arg": "^5.0.2",
"esbuild": "^0.18.16",
"globby": "^12.2.0",

View file

@ -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
/* ========================================================================== */

View file

@ -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);