Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix __dirname, __filename for CJS preview #6

Merged
merged 4 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
logFilters:
- level: discard
pattern: '@esbuild/*@* * is incompatible with this module, link skipped.'

nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-berry.cjs
8 changes: 8 additions & 0 deletions example/demo-node.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,11 @@ new Map([
['a', 1],
['b', 2],
])

// Node globals
__dirname
__filename
typeof require
typeof module
// skip bundling
eval('require')('./utils.cjs').now()
3 changes: 3 additions & 0 deletions example/node-react.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {createElement} from 'react'

createElement('div', null, 'Hello, world!')
1 change: 1 addition & 0 deletions example/utils.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.now = Date.now
15 changes: 8 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,25 @@
"commands": [
{
"command": "liveCode.choosePreviewToTheSide",
"title": "Choose Preview to the Side",
"title": "Choose Live Code Preview to the Side",
"category": "Live Code",
"icon": "images/logo-plain.svg"
},
{
"command": "liveCode.openBrowserPreviewToSide",
"title": "Open Browser Preview to the Side",
"title": "Open Live Code Preview in Browser to the Side",
"category": "Live Code",
"icon": "images/browser-plain.svg"
},
{
"command": "liveCode.openNodePreviewToSide",
"title": "Open Node.js Preview to the Side",
"title": "Open Live Code Preview in Node.js to the Side",
"category": "Live Code",
"icon": "images/node-plain.svg"
},
{
"command": "liveCode.changeCurrentRuntimeOfPreview",
"title": "Change Current Runtime of Preview",
"title": "Change Current Runtime of Live Code Preview",
"category": "Live Code",
"icon": "images/logo-plain.svg"
}
Expand Down Expand Up @@ -102,17 +102,17 @@
"liveCode.showChoosePreviewInTitle": {
"type": "boolean",
"default": false,
"description": "Wether to show the 'Choose Preview to the Side' button in the editor title"
"description": "Wether to show the 'Choose Live Code Preview to the Side' button in the editor title"
},
"liveCode.showBrowserPreviewInTitle": {
"type": "boolean",
"default": true,
"description": "Wether to show the 'Open Browser Preview to the Side' button in the editor title"
"description": "Wether to show the 'Open Live Code Preview in Browser to the Side' button in the editor title"
},
"liveCode.showNodePreviewInTitle": {
"type": "boolean",
"default": true,
"description": "Wether to show the 'Open Node.js Preview to the Side' button in the editor title"
"description": "Wether to show the 'Open Live Code Preview in Node.js to the Side' button in the editor title"
},
"liveCode.renderJSX": {
"type": "boolean",
Expand Down Expand Up @@ -181,6 +181,7 @@
"@vscode/webview-ui-toolkit": "^1.4.0",
"console-feed": "^3.6.0",
"es-jest": "^2.1.0",
"esbuild-node-externals": "^1.13.0",
"is-promise": "^4.0.0",
"jest": "^29.7.0",
"ldrs": "^1.0.1",
Expand Down
1 change: 1 addition & 0 deletions src/extension/__tests__/bundle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ describe('node', () => {
const opts: BundleOpts = {
platform: 'node',
sourcemap: false,
filename: __filename,
workspaceFolder: __dirname,
}

Expand Down
17 changes: 13 additions & 4 deletions src/extension/bundle.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'path'
import type * as Esbuild from 'esbuild'
import {fetchBuilder, MemoryCache} from 'node-fetch-cache'
import {nodeExternalsPlugin} from 'esbuild-node-externals'
// @ts-expect-error ESM
import httpPlugin from '../../scripts/httpPlugin.mjs'

Expand Down Expand Up @@ -99,10 +100,18 @@ export default async function bundle(
},
// ensure there is only one copy of React, see https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react
// external: isWeb ? ['react', 'react-dom'] : [],
plugins: [
isNode && httpPlugin({fetch}),
isWeb && externalGlobalPlugin({react: 'React', 'react-dom': 'ReactDOM'}),
].filter(Boolean),
plugins: isNode
? [
//
httpPlugin({fetch}) as unknown as Esbuild.Plugin,
nodeExternalsPlugin(),
]
: isWeb
? [
//
externalGlobalPlugin({react: 'React', 'react-dom': 'ReactDOM'}),
]
: [],
})
const outputs = result.outputFiles
const js = outputs.find((x) => x.path.endsWith('.js'))?.text
Expand Down
24 changes: 17 additions & 7 deletions src/sandbox/__tests__/nodeVM.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import {Message} from 'console-feed/src/definitions/Console'
import {Message} from 'console-feed/lib/definitions/Console'
import {create} from '../../utils/promise'
import * as nodeVM from '../nodeVM'
import transform from '../transform'

const opts = {
filename: __filename,
}

test('empty', async () => {
expect(await nodeVM.runInNewContext(transform(``))).toMatchInlineSnapshot(`
expect(await nodeVM.runInNewContext(transform(``), opts))
.toMatchInlineSnapshot(`
{
"logs": [],
"result": [],
Expand All @@ -13,7 +18,8 @@ test('empty', async () => {
})

test('expression', async () => {
expect(await nodeVM.runInNewContext(transform(`0`))).toMatchInlineSnapshot(`
expect(await nodeVM.runInNewContext(transform(`0`), opts))
.toMatchInlineSnapshot(`
{
"logs": [],
"result": [
Expand All @@ -32,7 +38,8 @@ test('expression', async () => {
test('no access to local scope', async () => {
expect(
await nodeVM.runInNewContext(
transform(`[typeof vm, typeof format, typeof result]`)
transform(`[typeof vm, typeof format, typeof result]`),
opts
)
).toMatchInlineSnapshot(`
{
Expand All @@ -55,14 +62,17 @@ test('no access to local scope', async () => {
})

test('reject', async () => {
await expect(nodeVM.runInNewContext(transform(`a`))).rejects.toThrow(
await expect(nodeVM.runInNewContext(transform(`a`), opts)).rejects.toThrow(
/a is not defined/
)
})

test('__filename', async () => {
expect(
await nodeVM.runInNewContext(transform(`[require, typeof __filename]`))
await nodeVM.runInNewContext(
transform(`[require, typeof __filename]`),
opts
)
).toMatchInlineSnapshot(`
{
"logs": [],
Expand Down Expand Up @@ -110,7 +120,7 @@ test('console', async () => {
console.timeEnd('fn')
})()
`),
{workerRef, onUpdate}
{...opts, workerRef, onUpdate}
)
).toMatchObject({logs: []})

Expand Down
2 changes: 1 addition & 1 deletion src/sandbox/nodeVM.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const runInNewContext = async (
) => {
return new Promise<Result>((resolve, reject) => {
const worker = new Worker(workerPath, {
// canot use `eval: true` due to scope bug in `vm.runInThisContext`
// cannot use `eval: true` due to scope bug in `vm.runInThisContext`
workerData: {code, filename},
})
if (workerRef) {
Expand Down
11 changes: 10 additions & 1 deletion src/sandbox/nodeWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const {workerData, parentPort} = require('worker_threads')
const {format} = require('pretty-format')
const Hook = require('console-feed/lib/Hook').default
const vm = require('vm')
const path = require('path')
const {createRequire} = require('module')

const {code, filename} = workerData
const result = []
Expand Down Expand Up @@ -39,7 +41,14 @@ Object.assign(globalThis, {
})

// https://nodejs.org/api/globals.html#global-objects
const globalObjects = {module, exports, require, __dirname, __filename}
const globalObjects = {
module,
exports,
require: createRequire(filename),
__dirname: path.dirname(filename),
__filename: filename,
}
// TODO: https://nodejs.org/api/vm.html#class-vmmodule
vm.runInThisContext(
`(({module, exports, require, __dirname, __filename}) => { ${code} })`,
{filename}
Expand Down
52 changes: 43 additions & 9 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2388,6 +2388,18 @@ __metadata:
languageName: node
linkType: hard

"esbuild-node-externals@npm:^1.13.0":
version: 1.13.0
resolution: "esbuild-node-externals@npm:1.13.0"
dependencies:
find-up: ^5.0.0
tslib: ^2.4.1
peerDependencies:
esbuild: 0.12 - 0.20
checksum: 516303edeb5b8124cbd2d9b33bcbeeb3fe0dfe38eb3183b253793862ecb889badcb87abde8ebb415e9c33292032c2c71bd0f9f713d38083c65d4ae6d615628fd
languageName: node
linkType: hard

"esbuild@npm:^0, esbuild@npm:^0.20.2":
version: 0.20.2
resolution: "esbuild@npm:0.20.2"
Expand Down Expand Up @@ -2783,6 +2795,16 @@ __metadata:
languageName: node
linkType: hard

"find-up@npm:^5.0.0":
version: 5.0.0
resolution: "find-up@npm:5.0.0"
dependencies:
locate-path: ^6.0.0
path-exists: ^4.0.0
checksum: 07955e357348f34660bde7920783204ff5a26ac2cafcaa28bace494027158a97b9f56faaf2d89a6106211a8174db650dd9f503f9c0d526b1202d5554a00b9095
languageName: node
linkType: hard

"fs-minipass@npm:^2.0.0":
version: 2.1.0
resolution: "fs-minipass@npm:2.1.0"
Expand Down Expand Up @@ -3868,6 +3890,7 @@ __metadata:
console-feed: ^3.6.0
es-jest: ^2.1.0
esbuild: ^0.20.2
esbuild-node-externals: ^1.13.0
is-promise: ^4.0.0
jest: ^29.7.0
ldrs: ^1.0.1
Expand All @@ -3893,6 +3916,15 @@ __metadata:
languageName: node
linkType: hard

"locate-path@npm:^6.0.0":
version: 6.0.0
resolution: "locate-path@npm:6.0.0"
dependencies:
p-locate: ^5.0.0
checksum: 72eb661788a0368c099a184c59d2fee760b3831c9c1c33955e8a19ae4a21b4116e53fa736dc086cdeb9fce9f7cc508f2f92d2d3aae516f133e16a2bb59a39f5a
languageName: node
linkType: hard

"locko@npm:0.0.3":
version: 0.0.3
resolution: "locko@npm:0.0.3"
Expand Down Expand Up @@ -4280,7 +4312,7 @@ __metadata:
languageName: node
linkType: hard

"p-limit@npm:^3.1.0":
"p-limit@npm:^3.0.2, p-limit@npm:^3.1.0":
version: 3.1.0
resolution: "p-limit@npm:3.1.0"
dependencies:
Expand All @@ -4298,6 +4330,15 @@ __metadata:
languageName: node
linkType: hard

"p-locate@npm:^5.0.0":
version: 5.0.0
resolution: "p-locate@npm:5.0.0"
dependencies:
p-limit: ^3.0.2
checksum: 1623088f36cf1cbca58e9b61c4e62bf0c60a07af5ae1ca99a720837356b5b6c5ba3eb1b2127e47a06865fee59dd0453cad7cc844cda9d5a62ac1a5a51b7c86d3
languageName: node
linkType: hard

"p-map@npm:^4.0.0":
version: 4.0.0
resolution: "p-map@npm:4.0.0"
Expand Down Expand Up @@ -5123,14 +5164,7 @@ __metadata:
languageName: node
linkType: hard

"tslib@npm:^2.0.1":
version: 2.3.1
resolution: "tslib@npm:2.3.1"
checksum: de17a98d4614481f7fcb5cd53ffc1aaf8654313be0291e1bfaee4b4bb31a20494b7d218ff2e15017883e8ea9626599b3b0e0229c18383ba9dce89da2adf15cb9
languageName: node
linkType: hard

"tslib@npm:^2.6.2":
"tslib@npm:^2.0.1, tslib@npm:^2.4.1, tslib@npm:^2.6.2":
version: 2.6.2
resolution: "tslib@npm:2.6.2"
checksum: 329ea56123005922f39642318e3d1f0f8265d1e7fcb92c633e0809521da75eeaca28d2cf96d7248229deb40e5c19adf408259f4b9640afd20d13aecc1430f3ad
Expand Down
Loading