@lark-apaas/coding-html-devserver 0.1.7-beta.0 → 0.1.8-alpha.20260818172600

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/dev.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- import type { ViteDevServer } from 'vite';
1
+ import type { ViteDevServer } from 'vite' with { 'resolution-mode': 'import' };
2
2
  import { type HtmlViteOptions } from './vite-config';
3
+ /**
4
+ * vite 7/8 的 Node API 是 ESM-only。`module: Node16` 会在 CommonJS 产物中保留
5
+ * 原生动态 import,避免将它降级成无法加载 Vite 的 require。
6
+ */
3
7
  /**
4
8
  * 起 html stack 的 dev server(vite 封装在内,用户不感知)。
5
9
  * 热更新走 vite 原生 HMR/WS。
package/lib/dev.js CHANGED
@@ -3,18 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.startDevServer = startDevServer;
4
4
  const vite_config_1 = require("./vite-config");
5
5
  /**
6
- * vite 7/8 的 Node API 是 ESM-only(package `exports` 无 CJS 入口)。本包编译为
7
- * CommonJS,而 tsc 在 `module: CommonJS` 下会把字面 `import()` 降级成 `require()`
8
- * —— 对 ESM-only 的 vite 会 `ERR_REQUIRE_ESM`。用 `new Function` 包一层,让 tsc
9
- * 看不到这是 import(),从而保留运行时真正的动态 ESM import。
6
+ * vite 7/8 的 Node API 是 ESM-only。`module: Node16` 会在 CommonJS 产物中保留
7
+ * 原生动态 import,避免将它降级成无法加载 Vite 的 require。
10
8
  */
11
- const importESM = new Function('specifier', 'return import(specifier)');
12
9
  /**
13
10
  * 起 html stack 的 dev server(vite 封装在内,用户不感知)。
14
11
  * 热更新走 vite 原生 HMR/WS。
15
12
  */
16
13
  async function startDevServer(opts = {}) {
17
- const { createServer } = await importESM('vite');
14
+ const { createServer } = await import('vite');
18
15
  const server = await createServer((0, vite_config_1.createHtmlViteConfig)(opts));
19
16
  await server.listen();
20
17
  server.printUrls();
package/lib/minify.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.minifyHtmlWithHbsProtection = minifyHtmlWithHbsProtection;
4
- const html_minifier_terser_1 = require("html-minifier-terser");
5
4
  /**
6
5
  * 压缩 HTML,同时保护 HBS(Handlebars)占位符。
7
6
  *
@@ -12,13 +11,14 @@ const html_minifier_terser_1 = require("html-minifier-terser");
12
11
  * 行为对齐 `@lark-apaas/coding-preset-vite-react` 的 minifyHtmlWithHbsProtection。
13
12
  */
14
13
  async function minifyHtmlWithHbsProtection(html) {
14
+ const { minify } = await import('html-minifier-terser');
15
15
  const placeholders = [];
16
- let processed = html.replace(/\{\{\{?.+?\}\}\}?/g, (match) => {
16
+ let processed = html.replace(/\{\{\{?.+?\}\}\}?/g, match => {
17
17
  const i = placeholders.length;
18
18
  placeholders.push(match);
19
19
  return `__HBS_${i}__`;
20
20
  });
21
- processed = await (0, html_minifier_terser_1.minify)(processed, {
21
+ processed = await minify(processed, {
22
22
  collapseWhitespace: true,
23
23
  removeComments: true,
24
24
  removeRedundantAttributes: true,
@@ -1,4 +1,4 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with { 'resolution-mode': 'import' };
2
2
  /**
3
3
  * base path 归一(dev only)。
4
4
  *
@@ -1,4 +1,6 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with {
2
+ 'resolution-mode': 'import'
3
+ };
2
4
  /**
3
5
  * 妙搭沙箱外壳探活接口。协议对齐 `@lark-apaas/coding-preset-vite-react`:
4
6
  * - connection refused / timeout → dev server 没起来 → 外壳重启沙箱
@@ -1,4 +1,4 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with { 'resolution-mode': 'import' };
2
2
  export interface PlatformInjectPluginOptions {
3
3
  /** appId override,透传给 view-context(dev 拼真值字面量)。 */
4
4
  appId?: string;
@@ -1,4 +1,4 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with { 'resolution-mode': 'import' };
2
2
  /**
3
3
  * .jsx 走客户端编译,在 Vite transform 管线前原样返回。
4
4
  *
@@ -23,7 +23,9 @@ function rawJsxPlugin(opts) {
23
23
  const url = (req.url ?? '').split('?')[0];
24
24
  if (!url.endsWith('.jsx'))
25
25
  return next();
26
- const stripped = clientBasePath && url.startsWith(clientBasePath) ? url.slice(clientBasePath.length) : url;
26
+ const stripped = clientBasePath && url.startsWith(clientBasePath)
27
+ ? url.slice(clientBasePath.length)
28
+ : url;
27
29
  const filePath = node_path_1.default.join(root, stripped);
28
30
  try {
29
31
  const content = node_fs_1.default.readFileSync(filePath, 'utf-8');
@@ -1,4 +1,6 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with {
2
+ 'resolution-mode': 'import'
3
+ };
2
4
  /**
3
5
  * dev 期在 `${clientBasePath}/routes.json` 提供路由清单(与 build 一致):源根有 routes.json
4
6
  * 则透传,没有则扫描 `*.html` 生成 `[{path}]`。
@@ -1,4 +1,4 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with { 'resolution-mode': 'import' };
2
2
  /**
3
3
  * 撕掉 Vite 给「运行时/后端绝对 URL」误加的 base 前缀(dev only)。
4
4
  *
@@ -1,3 +1,3 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with { 'resolution-mode': 'import' };
2
2
  export declare function viteClientPatchPlugin(): Plugin;
3
3
  export default viteClientPatchPlugin;
@@ -9,28 +9,15 @@ exports.viteClientPatchPlugin = viteClientPatchPlugin;
9
9
  * 但 reload 用的是浏览器 HTTP/2 连接池里复用的休眠前死连接,
10
10
  * 导致 ~18s `ERR_CONNECTION_TIMED_OUT` 白屏。
11
11
  *
12
- * 解:transform 拦截 `vite/dist/client/client.mjs`,把 reload 换成 WS 重连——重连与
13
- * 探活同为 WebSocket 通道,不碰 HTTP/2 连接池,上述白屏不再触发;失败只打 warn,
14
- * 由用户决定是否刷新。顺带保住探活地址上的 `sandbox_token`:Vite 原本 `url.search = ""`
15
- * 会把它一起抹掉,导致探活恒被沙箱网关 401(`ws_proxy_service.go` 的 `token == ""`)。
12
+ * 解:transform 拦截 `vite/dist/client/client.mjs`,直接删掉 reload 那一行。
13
+ * 用户需要新代码时手动刷新。
16
14
  *
17
15
  * 仅 dev(`apply: 'serve'`)。
18
16
  *
19
17
  * 行为对齐 `@lark-apaas/coding-preset-vite-react` 的同名插件 —— html stack 跑在
20
18
  * 同一套沙箱反代链路里,重连白屏与 WS 鉴权两个问题同样成立。
21
19
  */
22
- const DISCONNECT_RECOVERY_PATTERN = /url\.search = "";\r?\n(\s*)await waitForSuccessfulPing\(url\.href\);\r?\n\s*location\.reload\(\);/;
23
- /**
24
- * 匹配 transport 里的 HMR 心跳定时器:
25
- * pingIntervalId = setInterval(() => { ... }, pingInterval);
26
- * Vite 被动断开只走 close → `onDisconnection()`,不清定时器;且 `pingIntervalId` 被下次
27
- * connect 覆盖后再也清不掉,重连后每断一次泄漏一个。改成 IIFE 内的局部 id 自清(不能清
28
- * 共享变量,会误杀新连接的心跳;用 IIFE 而非 `const` 声明,避免注入点落在无大括号的
29
- * 语句位置时产生语法错误)。已实测 Vite 7.3.x / 8.0.x 文本一致。
30
- *
31
- * 本包没有其它 preset 的 patch 3,此处仍编号 patch 4 以便跨包对齐。
32
- */
33
- const PING_INTERVAL_LEAK_PATTERN = /pingIntervalId = setInterval\(\(\) => \{\s*if \(socket\.readyState === socket\.OPEN\) socket\.send\(JSON\.stringify\(\{ type: "ping" \}\)\);\s*\}, pingInterval\);/;
20
+ const RECONNECT_RELOAD_PATTERN = /(await waitForSuccessfulPing\(url\.href\);)\r?\n(\s*)location\.reload\(\);/;
34
21
  function viteClientPatchPlugin() {
35
22
  return {
36
23
  name: 'miaoda-html-vite-client-patch',
@@ -40,19 +27,12 @@ function viteClientPatchPlugin() {
40
27
  if (!id.includes('vite/dist/client/client.mjs'))
41
28
  return;
42
29
  let patched = code;
43
- // patch 1: 重写断线恢复——探活保住 sandbox_token,探活成功后重连(失败只打 warn)
44
- if (DISCONNECT_RECOVERY_PATTERN.test(patched)) {
45
- patched = patched.replace(DISCONNECT_RECOVERY_PATTERN, (_, indent) => 'const __st = url.searchParams.get("sandbox_token");\n' +
46
- indent +
47
- 'url.search = __st ? "?sandbox_token=" + encodeURIComponent(__st) : "";\n' +
48
- indent +
49
- 'await waitForSuccessfulPing(url.href);\n' +
50
- indent +
51
- 'transport.connect(createHMRHandler(handleMessage)).catch((e) => { ' +
52
- "console.warn('[miaoda-html-vite-client-patch] HMR reconnect failed (ignored):', e); });");
30
+ // patch 1: 删掉 WS 重连后的 location.reload()
31
+ if (RECONNECT_RELOAD_PATTERN.test(patched)) {
32
+ patched = patched.replace(RECONNECT_RELOAD_PATTERN, (_, pingLine) => pingLine);
53
33
  }
54
34
  else {
55
- console.warn('[miaoda-html-vite-client-patch] disconnect-recovery pattern not found in @vite/client. ' +
35
+ console.warn('[miaoda-html-vite-client-patch] reconnect-reload pattern not found in @vite/client. ' +
56
36
  'patch NOT applied — Vite client.mjs may have changed.');
57
37
  }
58
38
  // patch 2: HMR 长链追加沙箱鉴权 token(gated on MIAODA_HMR_WS_TOKEN)
@@ -67,17 +47,6 @@ function viteClientPatchPlugin() {
67
47
  'sandbox_token NOT injected — Vite client.mjs may have changed.');
68
48
  }
69
49
  }
70
- // patch 4: 心跳定时器自清,修 patch 1 自动重连放大的 Vite 定时器泄漏
71
- // (本包无 patch 3,编号与其它 preset 对齐,见上方常量注释)
72
- if (PING_INTERVAL_LEAK_PATTERN.test(patched)) {
73
- patched = patched.replace(PING_INTERVAL_LEAK_PATTERN, 'pingIntervalId = (() => { const id = setInterval(() => { ' +
74
- 'if (socket.readyState === socket.OPEN) socket.send(JSON.stringify({ type: "ping" })); ' +
75
- 'else clearInterval(id); }, pingInterval); return id; })();');
76
- }
77
- else {
78
- console.warn('[miaoda-html-vite-client-patch] ping-interval pattern not found in @vite/client; ' +
79
- 'stale heartbeat timers will leak on reconnect — Vite client.mjs may have changed.');
80
- }
81
50
  return patched === code ? undefined : { code: patched };
82
51
  },
83
52
  };
@@ -1,4 +1,6 @@
1
- import type { Plugin } from 'vite';
1
+ import type { Plugin } from 'vite' with {
2
+ 'resolution-mode': 'import'
3
+ };
2
4
  /**
3
5
  * 检测沙箱代理链路下的 WebSocket 僵尸连接。
4
6
  *
@@ -42,7 +42,7 @@ function resolveClientRuntimePath() {
42
42
  path.resolve(__dirname, '../../src/runtime/ws-watchdog-client.mjs'), // lib/plugins → src/runtime
43
43
  path.resolve(__dirname, '../runtime/ws-watchdog-client.mjs'), // src/plugins → src/runtime
44
44
  ];
45
- return candidates.find((p) => fs.existsSync(p)) ?? null;
45
+ return candidates.find(p => fs.existsSync(p)) ?? null;
46
46
  }
47
47
  function wsWatchdogPlugin(options = {}) {
48
48
  const { pingEvent = 'ws-watchdog:ping', pongEvent = 'ws-watchdog:pong', clientBasePath = '', } = options;
@@ -1,4 +1,4 @@
1
- import type { InlineConfig } from 'vite';
1
+ import type { InlineConfig } from 'vite' with { 'resolution-mode': 'import' };
2
2
  export interface HtmlViteOptions {
3
3
  /** 静态根目录(相对 cwd),默认 'src'。 */
4
4
  root?: string;
@@ -37,7 +37,9 @@ const normalize_base_path_1 = require("./normalize-base-path");
37
37
  function createHtmlViteConfig(opts = {}) {
38
38
  const root = node_path_1.default.resolve(opts.root ?? 'src');
39
39
  // Number.isFinite 兜底:?? 只挡 null/undefined,挡不住 NaN(防 opts.port 传入脏值)
40
- const port = Number.isFinite(opts.port) ? opts.port : Number(process.env.CLIENT_DEV_PORT) || 8001;
40
+ const port = Number.isFinite(opts.port)
41
+ ? opts.port
42
+ : Number(process.env.CLIENT_DEV_PORT) || 8001;
41
43
  const host = opts.host ?? '0.0.0.0';
42
44
  // 沙箱网关把 `/app/<id>` 前缀透传给 vite 时,watchdog 的 <script src>、middleware
43
45
  // 匹配路径、以及客户端 import 的 `/@vite/client` 都必须带同一前缀;空串退化到裸路径。
@@ -63,7 +65,13 @@ function createHtmlViteConfig(opts = {}) {
63
65
  // overlay: false —— 关掉 vite 的错误红屏遮罩(JS 解析/编译失败时的全屏弹窗)。
64
66
  // 沙箱场景不给终端用户看红屏,报错仍保留在浏览器 console。
65
67
  hmr: process.env.MIAODA_WS_HOST
66
- ? { protocol: 'wss', host: process.env.MIAODA_WS_HOST, clientPort: 443, path: '/ws', overlay: false }
68
+ ? {
69
+ protocol: 'wss',
70
+ host: process.env.MIAODA_WS_HOST,
71
+ clientPort: 443,
72
+ path: '/ws',
73
+ overlay: false,
74
+ }
67
75
  : { path: '/ws', overlay: false },
68
76
  },
69
77
  plugins: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/coding-html-devserver",
3
- "version": "0.1.7-beta.0",
3
+ "version": "0.1.8-alpha.20260818172600",
4
4
  "description": "Dev/build toolchain for the miaoda-coding html (pure HTML) stack. Wraps vite (dev + HMR) behind a bin so the template never sees vite; build is pure-copy + platform-script injection + optional minify.",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",