openprototype 1.5.0 → 1.7.0

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/README.md CHANGED
@@ -248,15 +248,18 @@ When Playwright or Chromium is missing, do not rely on browser-layer results; in
248
248
  "products": [
249
249
  {
250
250
  "id": "demo",
251
- "roots": ["pc"],
252
- "lanAddress": "http://192.168.1.23:8082/product/demo/pc/index.html"
251
+ "roots": ["pc", "h5"],
252
+ "lanAddress": {
253
+ "pc": "http://192.168.1.23:8082/product/demo/pc/index.html",
254
+ "h5": "http://192.168.1.23:8082/product/demo/h5/index.html"
255
+ }
253
256
  }
254
257
  ]
255
258
  }
256
259
  ```
257
260
 
258
261
  `host` defaults to `127.0.0.1`. Setting it to `0.0.0.0` exposes static file reads to the LAN, so review the security boundary above first. A long-running background service also requires an explicit `npx openprototype service install --allow-lan`.
259
- “Copy LAN address” in the product navigator copies that product's `lanAddress` verbatim. The downstream business using openprototype owns this value; the framework does not infer it from the current browser URL. Restart the background service with `npx openprototype service restart` after changing it.
262
+ “Copy LAN address” in the product navigator reads the matching key from the product's `lanAddress` object for the current surface; for example, PC reads `lanAddress.pc` and H5 reads `lanAddress.h5`. The legacy string form remains supported and shares one address across all surfaces. The downstream business using openprototype owns these values; the framework does not infer them from the current browser URL. Restart the background service with `npx openprototype service restart` after changing it.
260
263
 
261
264
  Environment variables can override temporarily: `PROTO_KIT_PORT` · `PROTO_KIT_HOST` · `OPENCODE_BIN` · `OPENCODE_MODEL` · `OPENCODE_PORT`.
262
265
  You can also use `npx openprototype serve --port 9000 --host 0.0.0.0` to specify the port / listen address ad hoc.
package/README.zh-CN.md CHANGED
@@ -250,15 +250,18 @@ npx playwright install chromium
250
250
  "products": [
251
251
  {
252
252
  "id": "demo",
253
- "roots": ["pc"],
254
- "lanAddress": "http://192.168.1.23:8082/product/demo/pc/index.html"
253
+ "roots": ["pc", "h5"],
254
+ "lanAddress": {
255
+ "pc": "http://192.168.1.23:8082/product/demo/pc/index.html",
256
+ "h5": "http://192.168.1.23:8082/product/demo/h5/index.html"
257
+ }
255
258
  }
256
259
  ]
257
260
  }
258
261
  ```
259
262
 
260
263
  `host` 默认为 `127.0.0.1`。设为 `0.0.0.0` 会向局域网开放静态文件读取,请先阅读上面的安全边界;长期运行的常驻服务还需显式执行 `npx openprototype service install --allow-lan`。
261
- 产品导航中的“复制局域网地址”会原样复制该产品的 `lanAddress`;地址由引用 openprototype 的业务配置,框架不会根据当前浏览器地址自动推断。修改后,常驻服务需执行一次 `npx openprototype service restart`。
264
+ 产品导航中的“复制局域网地址”会按当前端读取该产品 `lanAddress` 下的同名配置;例如 PC 端读取 `lanAddress.pc`,H5 端读取 `lanAddress.h5`。旧版字符串写法仍兼容,表示该产品所有端共用一个地址。地址由引用 openprototype 的业务配置,框架不会根据当前浏览器地址自动推断。修改后,常驻服务需执行一次 `npx openprototype service restart`。
262
265
 
263
266
  环境变量可临时覆盖:`PROTO_KIT_PORT` · `PROTO_KIT_HOST` · `OPENCODE_BIN` · `OPENCODE_MODEL` · `OPENCODE_PORT`。
264
267
  也可用 `npx openprototype serve --port 9000 --host 0.0.0.0` 临时指定端口 / 监听地址。
package/bin/cli.js CHANGED
@@ -111,6 +111,75 @@ const ONBOARDING_BODY = [
111
111
  '<script src="/_kit/shell/onboarding.js"></script>',
112
112
  '<!-- onboarding:end -->'
113
113
  ].join('\n');
114
+ const LAN_ADDRESS_HELPER_MARK = 'async function loadLanAddress()';
115
+ const LAN_ADDRESS_HELPER = `async function loadLanAddress() {
116
+ const parts = window.location.pathname.split('/').filter(Boolean);
117
+ const productAt = parts.indexOf('product');
118
+ const productId = productAt >= 0 ? decodeURIComponent(parts[productAt + 1] || '') : '';
119
+ const surface = productAt >= 0 ? decodeURIComponent(parts[productAt + 2] || '') : '';
120
+ const params = new URLSearchParams({ productId, surface });
121
+ const res = await fetch('/api/lan-address?' + params.toString(), { cache: 'no-store' });
122
+ const data = await res.json().catch(() => ({}));
123
+ if (!res.ok || !data.ok) throw new Error(data.error || '局域网地址读取失败');
124
+ return String(data.lanAddress || '').trim();
125
+ }`;
126
+ const LAN_ADDRESS_CLICK = ` document.getElementById('copyAddressBtn').addEventListener('click', async () => {
127
+ try {
128
+ const lanAddress = await loadLanAddress();
129
+ if (!lanAddress) {
130
+ showToast('请先在 proto-kit.config.json 配置该产品当前端的 lanAddress');
131
+ return;
132
+ }
133
+ copyText(lanAddress, '局域网地址已复制到剪贴板');
134
+ } catch (err) {
135
+ showToast(err.message || '局域网地址读取失败');
136
+ }
137
+ });`;
138
+ const LEGACY_LAN_ADDRESS_MARK = 'openprototype:lan-address:start';
139
+ const LEGACY_LAN_ADDRESS_BLOCK = `<!-- openprototype:lan-address:start -->
140
+ <script>
141
+ (() => {
142
+ const button = document.getElementById('prototypeCopyAddress');
143
+ const toast = document.getElementById('prototypeToast');
144
+ if (!button || !toast) return;
145
+ const showToast = message => {
146
+ toast.textContent = message;
147
+ toast.classList.add('is-visible');
148
+ window.setTimeout(() => toast.classList.remove('is-visible'), 1800);
149
+ };
150
+ button.addEventListener('click', async event => {
151
+ event.preventDefault();
152
+ event.stopImmediatePropagation();
153
+ try {
154
+ const parts = window.location.pathname.split('/').filter(Boolean);
155
+ const productAt = parts.indexOf('product');
156
+ const params = new URLSearchParams({
157
+ productId: productAt >= 0 ? decodeURIComponent(parts[productAt + 1] || '') : '',
158
+ surface: productAt >= 0 ? decodeURIComponent(parts[productAt + 2] || '') : ''
159
+ });
160
+ const res = await fetch('/api/lan-address?' + params.toString(), { cache: 'no-store' });
161
+ const data = await res.json().catch(() => ({}));
162
+ if (!res.ok || !data.ok) throw new Error(data.error || '局域网地址读取失败');
163
+ const lanAddress = String(data.lanAddress || '').trim();
164
+ if (!lanAddress) throw new Error('请先在 proto-kit.config.json 配置该产品当前端的 lanAddress');
165
+ try {
166
+ await navigator.clipboard.writeText(lanAddress);
167
+ } catch {
168
+ const textarea = document.createElement('textarea');
169
+ textarea.value = lanAddress;
170
+ document.body.appendChild(textarea);
171
+ textarea.select();
172
+ document.execCommand('copy');
173
+ textarea.remove();
174
+ }
175
+ showToast('局域网地址已复制到剪贴板');
176
+ } catch (err) {
177
+ showToast(err.message || '局域网地址读取失败');
178
+ }
179
+ }, true);
180
+ })();
181
+ </script>
182
+ <!-- openprototype:lan-address:end -->`;
114
183
 
115
184
  /** 列出 product/<id>/<root>/index.html —— 已生成的产品壳 */
116
185
  function listProductShells(projectRoot) {
@@ -161,6 +230,74 @@ function patchShellOnboarding(projectRoot) {
161
230
  return patched;
162
231
  }
163
232
 
233
+ /**
234
+ * 把旧产品壳的“复制地址”迁移到运行时 /api/lan-address。
235
+ * 只识别脚手架的 copyAddressBtn 和旧导航的 prototypeCopyAddress;其他定制壳不动。
236
+ */
237
+ function patchShellLanAddress(projectRoot) {
238
+ let patched = 0;
239
+ const oldClick = / document\.getElementById\('copyAddressBtn'\)\.addEventListener\('click', \(\) => \{\s*copyText\((?:window\.location\.href|NAVIGATOR_ADDRESS),\s*'[^']*'\);\s*\}\);/;
240
+ const initAnchor = "window.addEventListener('DOMContentLoaded', async () => {";
241
+
242
+ for (const shell of listProductShells(projectRoot)) {
243
+ const rel = path.relative(projectRoot, shell);
244
+ let html = fs.readFileSync(shell, 'utf8');
245
+
246
+ if (/id=(['"])prototypeCopyAddress\1/.test(html)) {
247
+ if (html.includes(LEGACY_LAN_ADDRESS_MARK)) {
248
+ info(C.dim(' 跳过(已有局域网复制): ') + rel);
249
+ continue;
250
+ }
251
+ const legacyScript = /<script\b[^>]*\bsrc=(['"])\/scripts\/prototype-agent\/prototype-navigator\.js[^'"]*\1[^>]*><\/script>/i;
252
+ const legacyMatch = html.match(legacyScript);
253
+ if (!legacyMatch) {
254
+ info(C.dim(' 跳过(旧导航结构不认识): ') + rel);
255
+ continue;
256
+ }
257
+ html = html.replace(
258
+ /(<button\b[^>]*\bid=(['"])prototypeCopyAddress\2[^>]*>)[\s\S]*?(<\/button>)/i,
259
+ '$1复制局域网地址$3'
260
+ );
261
+ html = html.replace(legacyMatch[0], legacyMatch[0] + '\n' + LEGACY_LAN_ADDRESS_BLOCK);
262
+ fs.writeFileSync(shell, html);
263
+ ok('已迁移局域网复制功能 ' + rel);
264
+ patched++;
265
+ continue;
266
+ }
267
+
268
+ if (!/id=(['"])copyAddressBtn\1/.test(html)) continue;
269
+
270
+ const nextLabel = html.replace(
271
+ /(<button\b[^>]*\bid=(['"])copyAddressBtn\2[^>]*>)[\s\S]*?(<\/button>)/i,
272
+ '$1复制局域网地址$3'
273
+ );
274
+ if (html.includes(LAN_ADDRESS_HELPER_MARK)) {
275
+ if (nextLabel !== html) {
276
+ fs.writeFileSync(shell, nextLabel);
277
+ ok('已更新局域网复制文案 ' + rel);
278
+ patched++;
279
+ } else {
280
+ info(C.dim(' 跳过(已有局域网复制): ') + rel);
281
+ }
282
+ continue;
283
+ }
284
+ if (!oldClick.test(html) || !html.includes(initAnchor)) {
285
+ info(C.dim(' 跳过(复制逻辑不是已知旧版本): ') + rel);
286
+ continue;
287
+ }
288
+
289
+ html = nextLabel.replace(initAnchor, LAN_ADDRESS_HELPER + '\n\n' + initAnchor);
290
+ html = html.replace(oldClick, LAN_ADDRESS_CLICK);
291
+ if (!html.includes('copyText(NAVIGATOR_ADDRESS')) {
292
+ html = html.replace(/^\s*const NAVIGATOR_ADDRESS = [^\n]+;\n/m, '');
293
+ }
294
+ fs.writeFileSync(shell, html);
295
+ ok('已迁移局域网复制功能 ' + rel);
296
+ patched++;
297
+ }
298
+ return patched;
299
+ }
300
+
164
301
  /** 新项目 package.json 里本框架的依赖版本(已发布 npm,语义化版本管理) */
165
302
  function kitDependencySpec() {
166
303
  const pkg = readJson(path.join(PKG_ROOT, 'package.json'), {});
@@ -243,6 +380,7 @@ async function cmdInit() {
243
380
  } else info(C.dim(' 跳过(已存在): ') + CONFIG_FILENAME);
244
381
 
245
382
  patchShellOnboarding(root);
383
+ patchShellLanAddress(root);
246
384
 
247
385
  // 合并 package.json 脚本(不覆盖用户已有脚本)
248
386
  const pkgPath = path.join(root, 'package.json');
@@ -312,7 +450,7 @@ function cmdAddProduct(argv) {
312
450
  const config = loadOrInitConfig(root);
313
451
  config.products = config.products || [];
314
452
  if (!config.products.some((p) => p.id === id)) {
315
- config.products.push({ id, roots: ['pc'], lanAddress: '' });
453
+ config.products.push({ id, roots: ['pc'], lanAddress: { pc: '' } });
316
454
  saveConfig(root, config);
317
455
  ok(`已在 ${CONFIG_FILENAME} 注册产品 ${id}`);
318
456
  } else info(C.dim(` 产品 ${id} 已在配置中`));
package/lib/config.js CHANGED
@@ -29,9 +29,9 @@ const DEFAULTS = {
29
29
  port: 4097,
30
30
  startTimeoutMs: 15000
31
31
  },
32
- // lanAddress 由引用 openprototype 的业务配置,导航壳的“复制局域网地址”会原样复制该值。
33
- // 每个产品一个入口目录;roots 目前只支持 'pc'('h5' 后续再加)
34
- products: [{ id: 'demo', roots: ['pc'], lanAddress: '' }]
32
+ // lanAddress 由引用 openprototype 的业务配置,可按 roots 中的端分别配置。
33
+ // 旧版字符串写法继续兼容,表示该产品所有端共用一个地址。
34
+ products: [{ id: 'demo', roots: ['pc'], lanAddress: { pc: '' } }]
35
35
  };
36
36
 
37
37
  function deepMerge(base, override) {
@@ -70,6 +70,16 @@ function loadRawConfig(rootDir) {
70
70
  }
71
71
  }
72
72
 
73
+ function resolveLanAddress(product, surface) {
74
+ const configured = product && product.lanAddress;
75
+ if (typeof configured === 'string') return configured.trim();
76
+ if (!configured || Array.isArray(configured) || typeof configured !== 'object') return '';
77
+
78
+ const root = String(surface || '').trim();
79
+ if (!root || !Array.isArray(product.roots) || !product.roots.includes(root)) return '';
80
+ return typeof configured[root] === 'string' ? configured[root].trim() : '';
81
+ }
82
+
73
83
  /**
74
84
  * 跨平台探测 opencode 可执行文件。
75
85
  * 顺序:显式路径 → PATH(which/where) → 常见安装位。找不到返回 null(由调用方给安装引导)。
@@ -166,4 +176,4 @@ function loadConfig(startDir) {
166
176
  };
167
177
  }
168
178
 
169
- module.exports = { loadConfig, detectOpenCodeBin, findProjectRoot, DEFAULTS, CONFIG_FILENAME };
179
+ module.exports = { loadConfig, detectOpenCodeBin, findProjectRoot, resolveLanAddress, DEFAULTS, CONFIG_FILENAME };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openprototype",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "本地原型工作台:左侧树形导航 + 中间原型预览 + 右侧 AI Agent(OpenCode)。PRD 与 HTML/JS 原型协作,含自动化检查。",
5
5
  "keywords": [
6
6
  "prototype",
@@ -1467,7 +1467,8 @@ function copyText(text, successMsg) {
1467
1467
 
1468
1468
  async function loadLanAddress() {
1469
1469
  const productId = window.PROTO_KIT && window.PROTO_KIT.productId;
1470
- const params = new URLSearchParams({ productId: productId || '' });
1470
+ const surface = PAGE_BASE.split('/').filter(Boolean).pop() || '';
1471
+ const params = new URLSearchParams({ productId: productId || '', surface });
1471
1472
  const res = await fetch('/api/lan-address?' + params.toString(), { cache: 'no-store' });
1472
1473
  const data = await res.json().catch(() => ({}));
1473
1474
  if (!res.ok || !data.ok) throw new Error(data.error || '局域网地址读取失败');
@@ -1537,7 +1538,7 @@ window.addEventListener('DOMContentLoaded', async () => {
1537
1538
  try {
1538
1539
  const lanAddress = await loadLanAddress();
1539
1540
  if (!lanAddress) {
1540
- showToast('请先在 proto-kit.config.json 配置该产品的 lanAddress');
1541
+ showToast('请先在 proto-kit.config.json 配置该产品当前端的 lanAddress');
1541
1542
  return;
1542
1543
  }
1543
1544
  copyText(lanAddress, '局域网地址已复制到剪贴板');
@@ -11,6 +11,6 @@
11
11
  "port": 4097
12
12
  },
13
13
  "products": [
14
- { "id": "demo", "roots": ["pc"], "lanAddress": "" }
14
+ { "id": "demo", "roots": ["pc"], "lanAddress": { "pc": "" } }
15
15
  ]
16
16
  }
package/runtime/server.js CHANGED
@@ -16,7 +16,7 @@ const http = require('http');
16
16
  const fs = require('fs');
17
17
  const path = require('path');
18
18
  const { spawn } = require('child_process');
19
- const { loadConfig } = require('../lib/config');
19
+ const { loadConfig, resolveLanAddress } = require('../lib/config');
20
20
 
21
21
  function resolveArg(name) {
22
22
  const i = process.argv.indexOf(name);
@@ -141,9 +141,18 @@ function handleLanAddress(req, res) {
141
141
  const productId = String(requestUrl.searchParams.get('productId') || '').trim();
142
142
  const product = CONFIG.products.find((item) => item.id === productId);
143
143
  if (!product) return sendJson(res, 404, { ok: false, error: '未找到对应产品的局域网地址配置' });
144
+
145
+ let surface = String(requestUrl.searchParams.get('surface') || '').trim();
146
+ if (!surface && req.headers.referer) {
147
+ try {
148
+ const segments = new URL(req.headers.referer).pathname.split('/').filter(Boolean).map(decodeURIComponent);
149
+ if (segments[0] === 'product' && segments[1] === productId) surface = segments[2] || '';
150
+ } catch {}
151
+ }
152
+
144
153
  return sendJson(res, 200, {
145
154
  ok: true,
146
- lanAddress: typeof product.lanAddress === 'string' ? product.lanAddress.trim() : ''
155
+ lanAddress: resolveLanAddress(product, surface)
147
156
  });
148
157
  }
149
158
 
@@ -2,6 +2,7 @@
2
2
  'use strict';
3
3
 
4
4
  const fs = require('fs');
5
+ const http = require('http');
5
6
  const net = require('net');
6
7
  const os = require('os');
7
8
  const path = require('path');
@@ -57,6 +58,21 @@ function status(projectRoot) {
57
58
  return JSON.parse(result.stdout);
58
59
  }
59
60
 
61
+ function getJson(port, pathname, headers) {
62
+ return new Promise((resolve, reject) => {
63
+ const req = http.get({ host: '127.0.0.1', port, path: pathname, headers }, (res) => {
64
+ let body = '';
65
+ res.setEncoding('utf8');
66
+ res.on('data', (chunk) => { body += chunk; });
67
+ res.on('end', () => {
68
+ try { resolve({ status: res.statusCode, body: JSON.parse(body) }); }
69
+ catch (err) { reject(new Error(`接口返回不是 JSON:${body || err.message}`)); }
70
+ });
71
+ });
72
+ req.on('error', reject);
73
+ });
74
+ }
75
+
60
76
  async function waitFor(projectRoot, predicate, timeoutMs) {
61
77
  const deadline = Date.now() + timeoutMs;
62
78
  let current;
@@ -105,7 +121,14 @@ async function main() {
105
121
  port,
106
122
  host: '127.0.0.1',
107
123
  service: { autoInstall: true },
108
- products: []
124
+ products: [{
125
+ id: 'demo',
126
+ roots: ['pc', 'h5'],
127
+ lanAddress: {
128
+ pc: 'http://192.168.1.23/example/pc',
129
+ h5: 'http://192.168.1.23/example/h5'
130
+ }
131
+ }]
109
132
  }, null, 2) + '\n');
110
133
 
111
134
  const installResult = npm(['install', '--foreground-scripts'], projectRoot, {
@@ -118,6 +141,17 @@ async function main() {
118
141
  const initial = await waitFor(projectRoot, (item) => item.running, 20000);
119
142
  if (!initial.registered || initial.port !== port || !initial.pid) throw new Error('自动安装后的服务状态不完整');
120
143
 
144
+ const pcAddress = await getJson(port, '/api/lan-address?productId=demo&surface=pc');
145
+ if (pcAddress.status !== 200 || pcAddress.body.lanAddress !== 'http://192.168.1.23/example/pc') {
146
+ throw new Error(`PC 局域网地址不正确:${JSON.stringify(pcAddress)}`);
147
+ }
148
+ const h5Address = await getJson(port, '/api/lan-address?productId=demo', {
149
+ Referer: `http://127.0.0.1:${port}/product/demo/h5/index.html`
150
+ });
151
+ if (h5Address.status !== 200 || h5Address.body.lanAddress !== 'http://192.168.1.23/example/h5') {
152
+ throw new Error(`H5 局域网地址不正确:${JSON.stringify(h5Address)}`);
153
+ }
154
+
121
155
  process.kill(initial.pid, 'SIGKILL');
122
156
  const restarted = await waitFor(projectRoot, (item) => item.running && item.pid !== initial.pid, process.platform === 'win32' ? 90000 : 30000);
123
157
  if (restarted.version !== require(path.join(PKG_ROOT, 'package.json')).version) throw new Error('服务版本不正确');
@@ -1467,7 +1467,8 @@ function copyText(text, successMsg) {
1467
1467
 
1468
1468
  async function loadLanAddress() {
1469
1469
  const productId = window.PROTO_KIT && window.PROTO_KIT.productId;
1470
- const params = new URLSearchParams({ productId: productId || '' });
1470
+ const surface = PAGE_BASE.split('/').filter(Boolean).pop() || '';
1471
+ const params = new URLSearchParams({ productId: productId || '', surface });
1471
1472
  const res = await fetch('/api/lan-address?' + params.toString(), { cache: 'no-store' });
1472
1473
  const data = await res.json().catch(() => ({}));
1473
1474
  if (!res.ok || !data.ok) throw new Error(data.error || '局域网地址读取失败');
@@ -1537,7 +1538,7 @@ window.addEventListener('DOMContentLoaded', async () => {
1537
1538
  try {
1538
1539
  const lanAddress = await loadLanAddress();
1539
1540
  if (!lanAddress) {
1540
- showToast('请先在 proto-kit.config.json 配置该产品的 lanAddress');
1541
+ showToast('请先在 proto-kit.config.json 配置该产品当前端的 lanAddress');
1541
1542
  return;
1542
1543
  }
1543
1544
  copyText(lanAddress, '局域网地址已复制到剪贴板');