Implement fetch API and Promise polyfills for ES5 JavaScript engine #141
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Enables modern JavaScript patterns (fetch, Promise, async/await via compilation) in the ES5 Nashorn engine without requiring Node.js, bridging to the existing Vert.x HTTP client infrastructure.
Implementation
Core Polyfills (
fetch-runtime.js)then,catch,finally,all,race,resolve,rejectBridge Layer (
JsFetchBridge.java)JsHttpClientJsHttpResponseobjects for seamless integrationAuto-Injection
JsParserExecutorandJsPlaygroundExecutorto load fetch runtime on engine initializationhttpobject (no breaking changes)Usage
Users can now write:
With frontend TypeScript compilation (documented but not implemented), this enables:
Files
New:
parser/src/main/resources/fetch-runtime.js- Promise + fetch polyfillsparser/src/main/java/cn/qaiu/parser/customjs/JsFetchBridge.java- Java bridgeparser/src/main/resources/custom-parsers/fetch-demo.js- Example usageparser/src/test/java/cn/qaiu/parser/customjs/JsFetchBridgeTest.java- Testsparser/doc/TYPESCRIPT_*.md- DocumentationModified:
JsParserExecutor.java- Auto-inject fetch runtimeJsPlaygroundExecutor.java- Auto-inject fetch runtimeOriginal prompt
可以实现,而且不需要 Node 环境,整体可以做成纯前端编译 + 后端保持 ES5 引擎 + 适配已有 Vert.x JS 兼容层的方案。
我先用一句话总结,再分步骤说实现思路,最后单独讲
fetch→Vert.x client 的适配。总体方案概览
typescript.js(官方 tsc 编译器浏览器版)。async/await和标准fetch。fetch调用,最终走你已经实现的 Vert.x HTTP 客户端。核心要点有三个:
fetch封装成“你后端已经实现的 HTTP 接口调用”。一、浏览器引入纯 JS 版 tsc(TypeScript 官方编译器)
1. 引入方式
最简单做法:用官方打包好的
typescript.js或自己用 bundler 打包一份,放在webroot之类的静态目录中:2. 在浏览器内编译 TS/ES6 → ES5
示例代码:
用户在页面上写脚本,比如 textarea / Monaco 编辑器,然后:
二、fetch 与 Vert.x client JS 兼容层的衔接
你现在有“vertx client js 兼容层”,本质上应该是:
httpClient.get(url, callback)VertxHttp.request(method, url, options, callback)你想做到的是:
这里有两个可行路线,建议用第 1 种:
方案 1:后端注入 fetch,前端 TS 只当它是浏览器 API
流程:
lib配置中包含dom,TS 会认为全局有fetch:fetch调用还是fetch(...),保持原样。fetch函数,内部调用 Vert.x client。示例(Java 伪码):
在 JS 引擎里注入:
fetchRuntimeJs(用 ES5 写,适配你引擎只支持 ES5):