Skip to content

Commit

Permalink
Merge pull request #1071 from capricorn86/task/1069-upgrading-from-11…
Browse files Browse the repository at this point in the history
…02-1200-referenceerror-__dirname-is-not-defined

#1069@trivial: Fixes __dirname not defined error when using ESM.
capricorn86 authored Sep 15, 2023
2 parents 9c64001 + 1d965f9 commit 89e4f76
Showing 11 changed files with 70 additions and 66 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -89,15 +89,15 @@ jobs:
run: |
npm ci --ignore-scripts
- name: Set version
run: node ./bin/set-version.js --version=${{needs.check-next-version.outputs.next_version }}

- name: Compile packages
run: npm run compile

- name: Run tests
run: npm run test

- name: Set version
run: node ./bin/set-version.js --version=${{needs.check-next-version.outputs.next_version }}

- name: Configures Git
run: |
git config --global user.name "${{ github.actor }}"
18 changes: 6 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions packages/happy-dom/bin/build-version-file.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable no-console*/

const Path = require('path');
const FS = require('fs');
const packageJson = require('../package.json');

async function main() {
await Promise.all([
FS.promises.writeFile(
Path.resolve(Path.join('.', 'lib', 'version.js')),
`export default { version: '${packageJson.version}' };`
),
FS.promises.writeFile(
Path.resolve(Path.join('.', 'cjs', 'version.cjs')),
`module.exports = { default: { version: '${packageJson.version}' } };`
)
]);
}

main();
13 changes: 7 additions & 6 deletions packages/happy-dom/bin/change-file-extension.cjs
Original file line number Diff line number Diff line change
@@ -55,9 +55,13 @@ async function readDirectory(directory) {
}

async function renameFiles(files, args) {
const fromExtEscaped = args.fromExt.replace('.', '\\.');
const newFiles = files.map((file) => ({
oldPath: file,
newPath: file.replace(args.fromExt, args.toExt)
newPath: file.replace(
new RegExp(`${fromExtEscaped}$|${fromExtEscaped}(\\.)`),
`${args.toExt}$1`
)
}));
const writePromises = [];

@@ -66,11 +70,8 @@ async function renameFiles(files, args) {
FS.promises.readFile(file.oldPath).then((content) => {
const oldContent = content.toString();
const newContent = oldContent
.replace(
new RegExp(`${args.fromExt.replace('.', '\\.')}\\.map`, 'g'),
`${args.toExt}.map`
)
.replace(new RegExp(`${args.fromExt.replace('.', '\\.')}(["'])`, 'g'), `${args.toExt}$1`);
.replace(new RegExp(`${fromExtEscaped}\\.map`, 'g'), `${args.toExt}.map`)
.replace(new RegExp(`${fromExtEscaped}(["'])`, 'g'), `${args.toExt}$1`);
return FS.promises.writeFile(file.newPath, newContent).then(() => {
if (file.oldPath !== file.newPath) {
return FS.promises.unlink(file.oldPath);
3 changes: 2 additions & 1 deletion packages/happy-dom/package.json
Original file line number Diff line number Diff line change
@@ -65,8 +65,9 @@
"access": "public"
},
"scripts": {
"compile": "tsc && tsc --module CommonJS --outDir cjs && npm run change-cjs-file-extension",
"compile": "tsc && tsc --module CommonJS --outDir cjs && npm run change-cjs-file-extension && npm run build-version-file",
"change-cjs-file-extension": "node ./bin/change-file-extension.cjs --dir=./cjs --fromExt=.js --toExt=.cjs",
"build-version-file": "node ./bin/build-version-file.cjs",
"watch": "tsc -w --preserveWatchOutput",
"lint": "eslint --ignore-path .gitignore --max-warnings 0 .",
"lint:fix": "eslint --ignore-path .gitignore --max-warnings 0 --fix .",
29 changes: 0 additions & 29 deletions packages/happy-dom/src/navigator/NavigatorUtility.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -27,7 +27,7 @@ export default class HTMLUnknownElement extends HTMLElement implements IHTMLElem

// This element can potentially be a custom element that has not been defined yet
// Therefore we need to register a callback for when it is defined in CustomElementRegistry and replace it with the registered element (see #404)
if (tagName.includes('-')) {
if (tagName.includes('-') && this.ownerDocument.defaultView.customElements._callbacks) {
const callbacks = this.ownerDocument.defaultView.customElements._callbacks;

if (parentNode && !this._customElementDefineCallback) {
1 change: 1 addition & 0 deletions packages/happy-dom/src/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default { version: '0.0.0' };
6 changes: 4 additions & 2 deletions packages/happy-dom/src/window/Window.ts
Original file line number Diff line number Diff line change
@@ -140,7 +140,7 @@ import WindowErrorUtility from './WindowErrorUtility.js';
import VirtualConsole from '../console/VirtualConsole.js';
import VirtualConsolePrinter from '../console/VirtualConsolePrinter.js';
import IHappyDOMSettings from './IHappyDOMSettings.js';
import NavigatorUtility from '../navigator/NavigatorUtility.js';
import PackageVersion from '../version.js';

const ORIGINAL_SET_TIMEOUT = setTimeout;
const ORIGINAL_CLEAR_TIMEOUT = clearTimeout;
@@ -212,7 +212,9 @@ export default class Window extends EventTarget implements IWindow {
disableComputedStyleRendering: false,
enableFileSystemHttpRequests: false,
navigator: {
userAgent: `Mozilla/5.0 (${NavigatorUtility.getPlatform()}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${NavigatorUtility.getHappyDOMVersion()}`
userAgent: `Mozilla/5.0 (X11; ${
process.platform.charAt(0).toUpperCase() + process.platform.slice(1) + ' ' + process.arch
}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${PackageVersion.version}`
},
device: {
prefersColorScheme: 'light',
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import IDocument from '../../../src/nodes/document/IDocument.js';
import HTMLUnknownElement from '../../../src/nodes/html-unknown-element/HTMLUnknownElement.js';
import CustomElement from '../../CustomElement.js';
import { beforeEach, describe, it, expect } from 'vitest';
import CustomElementRegistry from '../../../src/custom-element/CustomElementRegistry.js';

describe('HTMLUnknownElement', () => {
let window: IWindow;
@@ -72,7 +73,7 @@ describe('HTMLUnknownElement', () => {
expect(customElement instanceof CustomElement).toBe(true);

expect(customElement.isConnected).toBe(true);
expect(customElement.shadowRoot.children.length).toBe(2);
expect(customElement.shadowRoot?.children.length).toBe(2);

expect(customElement.childNodes === childNodes).toBe(true);
expect(customElement.children === children).toBe(true);
@@ -85,5 +86,18 @@ describe('HTMLUnknownElement', () => {
expect(customElement.attributes.length).toBe(1);
expect(customElement.attributes[0] === attribute1).toBe(true);
});

it('Does nothing if the property "_callback" doesn\'t exist on Window.customElements.', () => {
(<CustomElementRegistry>window.customElements) = <CustomElementRegistry>(<unknown>{
get: () => undefined
});

const element = <HTMLUnknownElement>document.createElement('custom-element');
const parent = document.createElement('div');

expect(() => {
parent.appendChild(element);
}).not.toThrow();
});
});
});
22 changes: 11 additions & 11 deletions packages/happy-dom/test/window/Window.test.ts
Original file line number Diff line number Diff line change
@@ -26,14 +26,16 @@ import '../types.d.js';
import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
import VirtualConsole from '../../src/console/VirtualConsole.js';
import VirtualConsolePrinter from '../../src/console/VirtualConsolePrinter.js';
import NavigatorUtility from '../../src/navigator/NavigatorUtility.js';
import PackageJson from '../../package.json';
import PackageVersion from '../../src/version.js';

const GET_NAVIGATOR_PLATFORM = (): string => {
const processPlatform = process.platform;
const processPlatformCapitalized =
processPlatform.charAt(0).toUpperCase() + processPlatform.slice(1);
return 'X11; ' + processPlatformCapitalized + ' ' + process.arch;
return (
'X11; ' +
process.platform.charAt(0).toUpperCase() +
process.platform.slice(1) +
' ' +
process.arch
);
};

describe('Window', () => {
@@ -151,7 +153,7 @@ describe('Window', () => {
expect(windowWithoutOptions.happyDOM.settings.enableFileSystemHttpRequests).toBe(false);
expect(windowWithoutOptions.happyDOM.settings.navigator.userAgent).toBe(
`Mozilla/5.0 (${GET_NAVIGATOR_PLATFORM()}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${
PackageJson.version
PackageVersion.version
}`
);
expect(windowWithoutOptions.happyDOM.settings.device.prefersColorScheme).toBe('light');
@@ -457,9 +459,7 @@ describe('Window', () => {
const referenceValues = {
appCodeName: 'Mozilla',
appName: 'Netscape',
appVersion: `5.0 (${NavigatorUtility.getPlatform()}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${
PackageJson.version
}`,
appVersion: `5.0 (${platform}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${PackageVersion.version}`,
cookieEnabled: true,
credentials: null,
doNotTrack: 'unspecified',
@@ -480,7 +480,7 @@ describe('Window', () => {
},
product: 'Gecko',
productSub: '20100101',
userAgent: `Mozilla/5.0 (${platform}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${PackageJson.version}`,
userAgent: `Mozilla/5.0 (${platform}) AppleWebKit/537.36 (KHTML, like Gecko) HappyDOM/${PackageVersion.version}`,
vendor: '',
vendorSub: '',
webdriver: true

0 comments on commit 89e4f76

Please sign in to comment.