Commit 704bf34

Anton Golub <antongolub@antongolub.com>
2025-01-07 18:32:31
fix: enhance deno polyfill (#1061)
* refactor: rm dynamic load for repl module * fix(deno): add process polyfill fix(deno): fix internal esm > cjs reexport * chore: tweak up polyfill * chore: tweak up deno process polyfill * chore(deno): `process.version` polyfill * chore(deno): tweak up process polyfill * refactor: explicit process module ref * chore: deno process tweak ups * chore: byte shrinking * chore: build-js tweak up * test: tweak up flaky test
1 parent 3f36969
scripts/build-js.mjs
@@ -99,8 +99,15 @@ plugins.push(
         on: 'end',
         if: !hybrid,
         pattern: /\.js$/,
-        transform(contents) {
-          return injectCode(contents, `import './deno.js'`)
+        transform(contents, file) {
+          const { name } = path.parse(file)
+          const _contents = contents
+            .toString()
+            .replace(
+              '} = __module__',
+              `} = globalThis.Deno ? globalThis.require("./${name}.cjs") : __module__`
+            )
+          return injectCode(_contents, `import "./deno.js"`)
         },
       },
       {
scripts/deno.polyfill.js
@@ -1,13 +1,22 @@
 import { createRequire } from 'node:module'
+import * as process from 'node:process'
 
 const require = createRequire(import.meta.url)
 const __filename = new URL(import.meta.url).pathname
 const __dirname = new URL('.', import.meta.url).pathname
 
+// prettier-ignore
 if (globalThis.Deno) {
   globalThis.require = require
   globalThis.__filename = __filename
   globalThis.__dirname = __dirname
+  globalThis.module = new Proxy({}, { set() { return true } })
+
+  const p = globalThis.process = globalThis.process || process
+  p.version || (p.version = 'v18.0.0')
+  p.version || (p.version = { node: '18.0.0' })
+  p.env || (p.env = globalThis.Deno.env.toObject())
+  p.argv || (p.argv = [globalThis.Deno.execPath(), globalThis.Deno.mainModule.replace('file://', ''), ...globalThis.Deno.args])
 }
 
 export { require, __dirname, __filename }
src/cli.ts
@@ -29,6 +29,7 @@ import {
   VERSION,
 } from './index.js'
 import { installDeps, parseDeps } from './deps.js'
+import { startRepl } from './repl.js'
 import { randomId } from './util.js'
 import { createRequire } from './vendor.js'
 
@@ -109,7 +110,7 @@ export async function main() {
     return
   }
   if (argv.repl) {
-    await (await import('./repl.js')).startRepl()
+    await startRepl()
     return
   }
   if (argv.eval) {
src/goods.ts
@@ -14,7 +14,7 @@
 
 import assert from 'node:assert'
 import { createInterface } from 'node:readline'
-import { default as path } from 'node:path'
+import process from 'node:process'
 import { $, within, ProcessOutput } from './core.js'
 import {
   type Duration,
@@ -25,7 +25,6 @@ import {
   toCamelCase,
 } from './util.js'
 import {
-  fs,
   minimist,
   nodeFetch,
   type RequestInfo,
src/repl.ts
@@ -14,13 +14,14 @@
 
 import os from 'node:os'
 import path from 'node:path'
+import repl from 'node:repl'
 import { inspect } from 'node:util'
 import { ProcessOutput, defaults } from './core.js'
 import { chalk } from './vendor-core.js'
 
 export async function startRepl() {
   defaults.verbose = false
-  const r = (await import('node:repl')).start({
+  const r = repl.start({
     prompt: chalk.greenBright.bold('❯ '),
     useGlobal: true,
     preview: false,
src/vendor-core.ts
@@ -13,10 +13,10 @@
 // limitations under the License.
 
 export {
+  type TSpawnStore,
   exec,
   buildCmd,
   isStringLiteral,
-  type TSpawnStore,
   VoidStream,
 } from 'zurk/spawn'
 
test/smoke/bun.test.js
@@ -14,7 +14,8 @@
 
 import assert from 'node:assert'
 import { test, describe } from 'bun:test'
-import '../../build/globals.js'
+import { $, within, tmpdir } from '../../build/index.js'
+import '../../build/cli.js'
 
 describe('bun', () => {
   test('smoke test', async () => {
test/smoke/deno.test.js
@@ -13,7 +13,8 @@
 // limitations under the License.
 
 import { assert } from 'https://deno.land/std@0.224.0/assert/assert.ts'
-import '../../build/globals.js'
+import { $ } from '../../build/index.js'
+import '../../build/cli.js'
 
 Deno.test('deno smoke test', async () => {
   // smoke test
test/cli.test.js
@@ -268,23 +268,26 @@ describe('cli', () => {
     const oldPath = process.env.PATH
 
     const envPathSeparator = isWindows ? ';' : ':'
-    process.env.PATH += envPathSeparator + path.resolve('/tmp/')
+    const dir = tmpdir()
+    process.env.PATH += envPathSeparator + dir
 
     const toPOSIXPath = (_path) => _path.split(path.sep).join(path.posix.sep)
 
     const zxPath = path.resolve('./build/cli.js')
     const zxLocation = isWindows ? toPOSIXPath(zxPath) : zxPath
+    const scriptName = 'script-from-path'
     const scriptCode = `#!/usr/bin/env ${zxLocation}\nconsole.log('The script from path runs.')`
+    const scriptPath = path.join(dir, scriptName)
 
     try {
       await $`chmod +x ${zxLocation}`
-      await $({ stdio: ['inherit', 'pipe', 'pipe'] })`echo ${scriptCode}`.pipe(
-        fs.createWriteStream('/tmp/script-from-path', { mode: 0o744 })
+      await $`echo ${scriptCode}`.pipe(
+        fs.createWriteStream(scriptPath, { mode: 0o744 })
       )
-      await $`script-from-path`
+      await $`${scriptName}`
     } finally {
       process.env.PATH = oldPath
-      fs.rmSync('/tmp/script-from-path')
+      fs.rmSync(scriptPath)
     }
   })
 
test/export.test.js
@@ -84,7 +84,6 @@ describe('cli', () => {
     assert.equal(typeof cli.runScript, 'function', 'cli.runScript')
     assert.equal(typeof cli.scriptFromHttp, 'function', 'cli.scriptFromHttp')
     assert.equal(typeof cli.scriptFromStdin, 'function', 'cli.scriptFromStdin')
-    assert.equal(typeof cli.startRepl, 'undefined', 'cli.startRepl')
     assert.equal(typeof cli.transformMarkdown, 'function', 'cli.transformMarkdown')
     assert.equal(typeof cli.writeAndImport, 'function', 'cli.writeAndImport')
   })
.size-limit.json
@@ -9,7 +9,7 @@
   {
     "name": "zx/index",
     "path": "build/*.{js,cjs}",
-    "limit": "807 kB",
+    "limit": "808 kB",
     "brotli": false,
     "gzip": false
   },
@@ -30,7 +30,7 @@
   {
     "name": "all",
     "path": "build/*",
-    "limit": "844 kB",
+    "limit": "846 kB",
     "brotli": false,
     "gzip": false
   }