@heybox/hb-sdk 0.9.6-alpha.9 → 0.9.6

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +8 -1
  3. package/THIRD_PARTY_NOTICES.md +472 -48
  4. package/dist/cli-chunks/{artifact-BPntCpxe.cjs → artifact-D63EGQx9.cjs} +6 -5
  5. package/dist/cli-chunks/{build-C-u_43nO.cjs → build-fyHfi216.cjs} +6 -5
  6. package/dist/cli-chunks/{create-HUynjFAz.cjs → create-B-EnCHjU.cjs} +322 -4
  7. package/dist/cli-chunks/{dev-Dpg4MIoV.cjs → dev-Zb0pMdzr.cjs} +309 -39
  8. package/dist/cli-chunks/{dev-context-BBInsRLS.cjs → dev-context-DYFBVQ_C.cjs} +22 -14
  9. package/dist/cli-chunks/{doctor-qjPdtMIj.cjs → doctor-DmkHu1Hk.cjs} +1 -1
  10. package/dist/cli-chunks/{games-B7ckiLkr.cjs → games-CeCLFeTt.cjs} +1 -1
  11. package/dist/cli-chunks/{index-SB2iukXP.cjs → index-C696i2DY.cjs} +1 -1
  12. package/dist/cli-chunks/{index-D0fPJhtR.cjs → index-It90_ScC.cjs} +210 -38
  13. package/dist/cli-chunks/index.esm-CvMA_ppV.cjs +7977 -0
  14. package/dist/cli-chunks/{index.esm-jOc0zgE7.cjs → index.esm-YDTVatz_.cjs} +7 -6
  15. package/dist/cli-chunks/{login-DDKJA4pj.cjs → login-BGJz7JZV.cjs} +1 -1
  16. package/dist/cli-chunks/{project-vite-B_yd6m3R.cjs → project-vite-DybH-3Qp.cjs} +1 -1
  17. package/dist/cli-chunks/{remote-CSmfJpqd.cjs → remote-D9-2nonN.cjs} +13 -8
  18. package/dist/cli-chunks/{runtime-permission-env-Bbc5KS3u.cjs → runtime-permission-env-BrSofQNz.cjs} +52 -6990
  19. package/dist/cli-chunks/{skill-BTKQpM8e.cjs → skill-D6ebJn5J.cjs} +2 -2
  20. package/dist/cli-chunks/{version-Blqp4J3r.cjs → version-CtGTgNGb.cjs} +1 -1
  21. package/dist/cli.cjs +1 -1
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DsmreI9p.js +228 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-CLikLiNS.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-1VVyBeMq.js +567 -0
  25. package/dist/devtools/browser-dev-host/assets/index-ophYZqpX.css +1 -0
  26. package/dist/devtools/browser-dev-host/assets/linux-DwJAcUeD.svg +1 -0
  27. package/dist/devtools/browser-dev-host/index.html +6 -4
  28. package/dist/index.cjs.js +1201 -156
  29. package/dist/index.esm.js +1201 -156
  30. package/dist/miniapp-publish.cjs.js +1072 -131
  31. package/dist/miniapp-publish.esm.js +1072 -131
  32. package/dist/protocol.cjs.js +732 -158
  33. package/dist/protocol.esm.js +716 -159
  34. package/dist/templates/vanilla-vite-js/README.md.ejs +27 -0
  35. package/dist/templates/vanilla-vite-js/package.json.ejs +1 -1
  36. package/dist/templates/vanilla-vite-js/src/user-game-data.js.ejs +1 -0
  37. package/dist/vite.cjs.js +1087 -150
  38. package/dist/vite.esm.js +1087 -150
  39. package/docs/appreciation-code.md +4 -8
  40. package/package.json +8 -9
  41. package/skill/SKILL.md +4 -0
  42. package/skill/skill.json +5 -5
  43. package/types/index.d.ts +492 -77
  44. package/types/miniapp-publish/index.d.ts +18 -2
  45. package/types/protocol.d.ts +1 -1
  46. package/types/vite/index.d.ts +10 -16
  47. package/dist/devtools/browser-dev-host/assets/browser-dev-host-sU7AkNvZ.js +0 -100
  48. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-CRHmhFwH.js +0 -6
  49. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +0 -1
  50. package/dist/devtools/browser-dev-host/assets/index-yw_35zwq.js +0 -586
@@ -1,13 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-D0fPJhtR.cjs');
3
+ var index = require('./index-It90_ScC.cjs');
4
4
  var node_crypto = require('node:crypto');
5
5
  var fs = require('node:fs');
6
6
  var path = require('node:path');
7
- var runtimePermissionEnv = require('./runtime-permission-env-Bbc5KS3u.cjs');
8
- var version = require('./version-Blqp4J3r.cjs');
7
+ var index_esm = require('./index.esm-CvMA_ppV.cjs');
8
+ var version = require('./version-CtGTgNGb.cjs');
9
+ var runtimePermissionEnv = require('./runtime-permission-env-BrSofQNz.cjs');
9
10
  require('node:zlib');
10
- var devContext = require('./dev-context-BBInsRLS.cjs');
11
+ var devContext = require('./dev-context-DYFBVQ_C.cjs');
11
12
  var os = require('node:os');
12
13
  var net = require('node:net');
13
14
  var promises = require('node:dns/promises');
@@ -29,7 +30,7 @@ var require$$0$2 = require('stream');
29
30
  var require$$0$3 = require('url');
30
31
  var require$$5 = require('zlib');
31
32
  var require$$1 = require('util');
32
- var projectVite = require('./project-vite-B_yd6m3R.cjs');
33
+ var projectVite = require('./project-vite-DybH-3Qp.cjs');
33
34
 
34
35
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
35
36
  const DEFAULT_DEV_CONTEXT_TIMEOUT_MS = 3000;
@@ -222,7 +223,7 @@ async function loadDevLaunchContext(options) {
222
223
  migratingProfile = false;
223
224
  if (migration.changed)
224
225
  options.logger.info('已迁移当前正式发布名称与图片,继续启动开发环境');
225
- if (!runtimePermissionEnv.parseMiniProgramRuntimePermissions(detail.runtime_permissions).valid)
226
+ if (!index_esm.parseMiniProgramRuntimePermissions(detail.runtime_permissions).valid)
226
227
  return unavailable('线上权限快照无效,请稍后重试;持续失败时请联系平台支持。');
227
228
  const effectivePermissions = runtimePermissionEnv.composeMiniappRuntimePermissions(localPermissions, detail.runtime_permissions, detail.party_type).runtimePermissions;
228
229
  return {
@@ -231,7 +232,7 @@ async function loadDevLaunchContext(options) {
231
232
  miniProgramId: verifiedMiniProgramId,
232
233
  runtimePermissions: effectivePermissions,
233
234
  networkPolicy: detail.network_policy,
234
- ...(runtimePermissionEnv.parseMiniProgramRuntimePermissions(detail.effective_runtime_permissions).valid
235
+ ...(index_esm.parseMiniProgramRuntimePermissions(detail.effective_runtime_permissions).valid
235
236
  ? { publishedRuntimePermissions: detail.effective_runtime_permissions }
236
237
  : {}),
237
238
  declaredPermissions: localPermissions.permissions ?? {},
@@ -283,6 +284,7 @@ function createMiniProgramSummary(miniProgramId, detail) {
283
284
  const id = typeof detail.mini_program_id === 'string' && detail.mini_program_id.trim() ? detail.mini_program_id.trim() : miniProgramId;
284
285
  return {
285
286
  miniProgramId: id,
287
+ ...(typeof detail.description === 'string' && detail.description.trim() ? { description: detail.description.trim() } : {}),
286
288
  ...(typeof detail.name === 'string' && detail.name.trim() ? { name: detail.name.trim() } : {}),
287
289
  ...(typeof detail.icon_url === 'string' && detail.icon_url.trim() ? { iconUrl: detail.icon_url.trim() } : {}),
288
290
  ...(typeof detail.status === 'string' && detail.status.trim() ? { status: detail.status.trim() } : {}),
@@ -395,7 +397,7 @@ async function createDevContextSession(options) {
395
397
  contextRevision: browserContextRevision,
396
398
  devSessionId,
397
399
  expiresAt: Date.now() + 24 * 60 * 60 * 1000,
398
- localDevGrant: runtimePermissionEnv.createMiniProgramLocalDevGrant({
400
+ localDevGrant: index_esm.createMiniProgramLocalDevGrant({
399
401
  declaredPermissions: candidateDevContext.declaredPermissions ?? {},
400
402
  runtimePermissions: candidateDevContext.runtimePermissions,
401
403
  revision: browserContextRevision,
@@ -429,7 +431,7 @@ async function createDevContextSession(options) {
429
431
  }
430
432
  }
431
433
  function updateLocalContext() {
432
- const grant = runtimePermissionEnv.createMiniProgramLocalDevGrant({
434
+ const grant = index_esm.createMiniProgramLocalDevGrant({
433
435
  declaredPermissions: currentDevContext.declaredPermissions ?? {},
434
436
  runtimePermissions: currentDevContext.runtimePermissions,
435
437
  revision: currentDevContext.contextRevision ?? contextRevision,
@@ -543,7 +545,7 @@ async function createDevContextSession(options) {
543
545
  if (candidateCompanionDigest !== companionManifestSha256)
544
546
  contextRevision++;
545
547
  candidateCompanionDigest = companionManifestSha256;
546
- return runtimePermissionEnv.serializeMiniProgramDevelopmentSnapshot({
548
+ return index_esm.serializeMiniProgramDevelopmentSnapshot({
547
549
  schema_version: 1,
548
550
  session_id: devSessionId,
549
551
  revision: contextRevision,
@@ -2593,7 +2595,7 @@ function validateDevSessionCreatePayload(payload, allowedMiniUrlOrigins, runtime
2593
2595
  !allowedMiniUrlOrigins.has(miniUrlOrigin.origin)) {
2594
2596
  throw new TypeError('mini_url_origin must be an allowed LAN origin');
2595
2597
  }
2596
- const parsedPermissions = runtimePermissionEnv.parseMiniProgramRuntimePermissions(runtimePermissions);
2598
+ const parsedPermissions = index_esm.parseMiniProgramRuntimePermissions(runtimePermissions);
2597
2599
  if (!parsedPermissions.valid) {
2598
2600
  throw new TypeError('runtime_permissions is invalid');
2599
2601
  }
@@ -3315,8 +3317,8 @@ const DEFAULT_CHANNEL_TRANSPORT = {
3315
3317
  };
3316
3318
  const IPV4_LOOPBACK_ADDRESSES = new net.BlockList();
3317
3319
  IPV4_LOOPBACK_ADDRESSES.addSubnet('127.0.0.0', 8, 'ipv4');
3318
- const { WebSocket: WebSocket$1, WebSocketServer: WebSocketServer$1 } = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/dev-Dpg4MIoV.cjs', document.baseURI).href)))('ws');
3319
- const { parse: parseHtml } = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/dev-Dpg4MIoV.cjs', document.baseURI).href)))('parse5');
3320
+ const { WebSocket: WebSocket$1, WebSocketServer: WebSocketServer$1 } = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/dev-Zb0pMdzr.cjs', document.baseURI).href)))('ws');
3321
+ const { parse: parseHtml } = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/dev-Zb0pMdzr.cjs', document.baseURI).href)))('parse5');
3320
3322
  const BROWSER_DEV_HOST_ROOT_CANDIDATES = [
3321
3323
  path.resolve(__dirname, 'devtools/browser-dev-host'),
3322
3324
  path.resolve(__dirname, '../devtools/browser-dev-host'),
@@ -12674,7 +12676,7 @@ function assertNodeRuntimeCapabilities(ctx, settings) {
12674
12676
  function createNodeRealtimeDriverRegistry() {
12675
12677
  const registry = createRuntimeRealtimeDriverRegistry();
12676
12678
  registry.registerLazy('node-websocket', async () => {
12677
- const mod = await Promise.resolve().then(function () { return require('./index.esm-jOc0zgE7.cjs'); });
12679
+ const mod = await Promise.resolve().then(function () { return require('./index.esm-YDTVatz_.cjs'); });
12678
12680
  return mod.createNodeWebSocketRuntimeDriver();
12679
12681
  });
12680
12682
  return registry;
@@ -16760,7 +16762,7 @@ function createLaunchSnapshot(source, requestOrigin, includeDiagnostics = false)
16760
16762
  }
16761
16763
  if (source.devContextPath)
16762
16764
  snapshot.dev_context_url = new URL(source.devContextPath, requestOrigin).toString();
16763
- if (runtimePermissionEnv.parseMiniProgramRuntimePermissions(source.runtimePermissions).valid && source.runtimePermissions) {
16765
+ if (index_esm.parseMiniProgramRuntimePermissions(source.runtimePermissions).valid && source.runtimePermissions) {
16764
16766
  snapshot.runtime_permissions = JSON.parse(JSON.stringify(source.runtimePermissions));
16765
16767
  }
16766
16768
  if (includeDiagnostics && context)
@@ -22564,6 +22566,7 @@ async function createScopedCdpProxy(transport, options) {
22564
22566
  let opening;
22565
22567
  let endpoint = '';
22566
22568
  let creationUnconfirmed;
22569
+ let reuseTarget = options.reuseTarget;
22567
22570
  const websocket = new WebSocketServer({ noServer: true, maxPayload: 40 * 1024 * 1024, perMessageDeflate: false });
22568
22571
  const server = node_http.createServer((request, response) => {
22569
22572
  if (!validPeer(request) || !validHost(request) || request.method !== 'GET') {
@@ -23105,7 +23108,9 @@ async function createScopedCdpProxy(transport, options) {
23105
23108
  const owner = options.createOwnedPage?.(url);
23106
23109
  let created;
23107
23110
  try {
23108
- created = await createTarget(owner?.url ?? url, signal);
23111
+ const previous = reuseTarget;
23112
+ reuseTarget = undefined;
23113
+ created = (previous && owner ? await reconnectTarget(previous, signal) : undefined) ?? await createTarget(owner?.url ?? url, signal);
23109
23114
  if (owner) {
23110
23115
  try {
23111
23116
  owner.bind(created.targetId);
@@ -23130,6 +23135,15 @@ async function createScopedCdpProxy(transport, options) {
23130
23135
  throw new Error('开发会话已关闭');
23131
23136
  }
23132
23137
  await ensureMonitor(targetId);
23138
+ if (created.reused === true) {
23139
+ const monitor = monitors.get(targetId);
23140
+ if (!monitor?.sessionId)
23141
+ throw new Error('无法重新连接开发标签页');
23142
+ // 新会话必须换文档及 owner,不能继承旧 Runtime、启动票或调试上传身份。
23143
+ const result = await transport.request('Page.navigate', { url: owner?.url ?? url }, monitor.sessionId);
23144
+ if (result.errorText)
23145
+ throw new Error('无法加载新的开发会话');
23146
+ }
23133
23147
  if (closed)
23134
23148
  throw new Error('开发会话已关闭');
23135
23149
  if (!targetId || !roots.has(targetId))
@@ -23154,6 +23168,37 @@ async function createScopedCdpProxy(transport, options) {
23154
23168
  });
23155
23169
  return opening;
23156
23170
  }
23171
+ /** 只重连此前登记的精确 target,且再次核验文档 owner;不枚举或按 URL 搜索页面。 */
23172
+ async function reconnectTarget(previous, signal) {
23173
+ assertPreviewUrl(previous.url);
23174
+ let sessionId;
23175
+ try {
23176
+ const result = await index.awaitWithSignal(transport.request('Target.getTargetInfo', { targetId: previous.targetId }), signal);
23177
+ if (!isTargetInfo(result.targetInfo) || result.targetInfo.type !== 'page' ||
23178
+ result.targetInfo.targetId !== previous.targetId || !index.isPreviewDocumentUrl(result.targetInfo.url, previous.url))
23179
+ return;
23180
+ signal?.throwIfAborted();
23181
+ const attached = await index.awaitWithSignal(transport.request('Target.attachToTarget', { targetId: previous.targetId, flatten: true }), signal);
23182
+ if (typeof attached.sessionId !== 'string')
23183
+ throw new Error('无法核验原开发标签页');
23184
+ sessionId = attached.sessionId;
23185
+ const expression = `window.__HB_SDK_PREVIEW_OWNER__?.token === ${JSON.stringify(previous.ownerToken)}`;
23186
+ const identity = await index.awaitWithSignal(transport.request('Runtime.evaluate', { expression, returnByValue: true }, sessionId), signal);
23187
+ signal?.throwIfAborted();
23188
+ if (!index.isRecord(identity.result) || identity.result.value !== true)
23189
+ return;
23190
+ return { targetId: previous.targetId, reused: true };
23191
+ }
23192
+ catch (error) {
23193
+ if (isMissingTarget(error))
23194
+ return;
23195
+ throw error;
23196
+ }
23197
+ finally {
23198
+ if (sessionId)
23199
+ await detachMonitorSession(sessionId);
23200
+ }
23201
+ }
23157
23202
  async function createTarget(url, signal) {
23158
23203
  let result;
23159
23204
  try {
@@ -23272,6 +23317,11 @@ async function createScopedCdpProxy(transport, options) {
23272
23317
  getTargetId: () => targetId,
23273
23318
  openPage,
23274
23319
  close: () => close(),
23320
+ release: () => close(false),
23321
+ getReusableTarget: () => {
23322
+ const owner = targetId && pageOwners.get(targetId);
23323
+ return targetId && owner ? { targetId, url: options.url, ownerToken: owner.ownerToken } : undefined;
23324
+ },
23275
23325
  isClosed: () => closed || transport.isClosed(),
23276
23326
  };
23277
23327
  }
@@ -23301,6 +23351,71 @@ function assertPreviewUrl(input) {
23301
23351
  throw new Error('开发标签页必须使用本机调试台地址');
23302
23352
  }
23303
23353
 
23354
+ /** 锁持有到本次 dev 释放浏览器,防止并行会话接管同一标签页。 */
23355
+ async function acquireBrowserReuse(project, cacheRoot = process.env.HB_SDK_PREVIEW_CACHE_DIR ?? index.envPaths('hb-sdk', { suffix: '' }).cache) {
23356
+ const projectRoot = await fs$1.realpath(project);
23357
+ const directory = path.resolve(cacheRoot, 'preview', 'browsers', 'v1', node_crypto.createHash('sha256').update(projectRoot).digest('hex'));
23358
+ await fs$1.mkdir(directory, { recursive: true, mode: 0o700 });
23359
+ const filename = path.join(directory, 'browser.json');
23360
+ let lock;
23361
+ try {
23362
+ lock = await index.acquireLocalFileLock(filename);
23363
+ }
23364
+ catch (error) {
23365
+ if (error instanceof index.DeployLockConflictError)
23366
+ return undefined;
23367
+ throw error;
23368
+ }
23369
+ return {
23370
+ directory,
23371
+ release: () => lock.release(),
23372
+ async read() {
23373
+ try {
23374
+ const info = await fs$1.lstat(filename);
23375
+ if (!info.isFile() || info.size > 16_384 || (process.getuid && info.uid !== process.getuid()))
23376
+ return;
23377
+ const value = JSON.parse(await fs$1.readFile(filename, 'utf8'));
23378
+ if (!index.isRecord(value) || value.version !== 1 || value.projectRoot !== projectRoot ||
23379
+ typeof value.profile !== 'string' || path.dirname(value.profile) !== directory || !path.basename(value.profile).startsWith('profile-') ||
23380
+ !Number.isSafeInteger(value.pid) || Number(value.pid) <= 0 || !['chrome', 'edge'].includes(String(value.channel)))
23381
+ return;
23382
+ if (value.processIdentity !== undefined && (typeof value.processIdentity !== 'string' || !/^[a-f0-9]{64}$/.test(value.processIdentity)))
23383
+ return;
23384
+ if (value.target !== undefined && (!index.isRecord(value.target) || typeof value.target.targetId !== 'string' ||
23385
+ !/^[A-Za-z0-9_-]{1,200}$/.test(value.target.targetId) || typeof value.target.url !== 'string' || value.target.url.length > 8192 ||
23386
+ typeof value.target.ownerToken !== 'string' || !/^[a-f0-9]{64}$/.test(value.target.ownerToken)))
23387
+ return;
23388
+ return value;
23389
+ }
23390
+ catch (error) {
23391
+ if (error.code === 'ENOENT' || error instanceof SyntaxError)
23392
+ return;
23393
+ throw error;
23394
+ }
23395
+ },
23396
+ async save(record) {
23397
+ const staging = filename + '.' + node_crypto.randomUUID() + '.tmp';
23398
+ try {
23399
+ await fs$1.writeFile(staging, JSON.stringify({ ...record, version: 1, projectRoot }), { flag: 'wx', mode: 0o600 });
23400
+ await fs$1.rename(staging, filename);
23401
+ }
23402
+ finally {
23403
+ await fs$1.rm(staging, { force: true });
23404
+ }
23405
+ },
23406
+ async clear() { await fs$1.rm(filename, { force: true }); },
23407
+ };
23408
+ }
23409
+ function isBrowserProcessAlive(pid) {
23410
+ try {
23411
+ process.kill(pid, 0);
23412
+ return true;
23413
+ }
23414
+ catch (error) {
23415
+ return error.code !== 'ESRCH';
23416
+ }
23417
+ }
23418
+
23304
23419
  function isTargetCreationUnconfirmed(error) {
23305
23420
  return error !== null && typeof error === 'object' && 'code' in error && error.code === 'TARGET_CREATION_UNCONFIRMED';
23306
23421
  }
@@ -23311,6 +23426,19 @@ class PreviewBrowserOpenError extends Error {
23311
23426
  this.name = 'PreviewError';
23312
23427
  }
23313
23428
  }
23429
+ /** 三种租约共享同一组精确目标操作,只覆盖各自的生命周期。 */
23430
+ function createBrowserLease(proxy, metadata, lifecycle = {}) {
23431
+ return {
23432
+ ...metadata,
23433
+ cdpEndpoint: proxy.endpoint,
23434
+ getTargetId: proxy.getTargetId,
23435
+ isClosed: proxy.isClosed,
23436
+ verifyBrowserPageOwner: proxy.verifyBrowserPageOwner,
23437
+ openPage: proxy.openPage,
23438
+ close: proxy.close,
23439
+ ...lifecycle,
23440
+ };
23441
+ }
23314
23442
  function previewBrowserCandidates(platform = process.platform, env = process.env) {
23315
23443
  if (platform === 'darwin')
23316
23444
  return [
@@ -23331,8 +23459,43 @@ function previewBrowserCandidates(platform = process.platform, env = process.env
23331
23459
  { channel: 'edge', executable: '/usr/bin/microsoft-edge' },
23332
23460
  ];
23333
23461
  }
23334
- /** 默认请求正在运行的日常浏览器授权;无法接入时回退到本次临时独立环境。 */
23462
+ /** 优先重连本项目自建浏览器,否则请求日常浏览器授权并按需回退独立环境。 */
23335
23463
  async function openPreviewBrowser(url, channel, options = {}) {
23464
+ let reuse = options.projectRoot && options.createOwnedPage && (options.reuseBrowser ?? !options.headless)
23465
+ ? await acquireBrowserReuse(options.projectRoot, options.cacheRoot)
23466
+ : undefined;
23467
+ let retained = false;
23468
+ try {
23469
+ if (reuse) {
23470
+ const previous = await reuse.read();
23471
+ if (previous && (!channel || previous.channel === channel)) {
23472
+ const existing = await reconnectIsolatedBrowser(url, previous, reuse, options);
23473
+ if (existing) {
23474
+ retained = true;
23475
+ return existing;
23476
+ }
23477
+ }
23478
+ else if (previous && await isRegisteredBrowserRunning(previous, options)) {
23479
+ // 显式切换浏览器不覆盖仍在运行的旧登记,另开临时环境并在退出时清理。
23480
+ await reuse.release();
23481
+ reuse = undefined;
23482
+ return openPreviewBrowserSession(url, channel, options);
23483
+ }
23484
+ else if (previous) {
23485
+ await fs$1.rm(previous.profile, { recursive: true, force: true });
23486
+ await reuse.clear();
23487
+ }
23488
+ }
23489
+ const browser = await openPreviewBrowserSession(url, channel, options, reuse);
23490
+ retained = browser?.release !== undefined;
23491
+ return browser;
23492
+ }
23493
+ finally {
23494
+ if (!retained)
23495
+ await reuse?.release();
23496
+ }
23497
+ }
23498
+ async function openPreviewBrowserSession(url, channel, options, reuse) {
23336
23499
  options.signal?.throwIfAborted();
23337
23500
  let fallbackReason = null;
23338
23501
  // headless 仅用于受控自动验收,绝不向开发者的个人浏览器弹授权。
@@ -23358,19 +23521,12 @@ async function openPreviewBrowser(url, channel, options = {}) {
23358
23521
  await proxy.close();
23359
23522
  options.signal.throwIfAborted();
23360
23523
  }
23361
- const lease = proxy;
23362
23524
  options.progress?.(`已连接获准的 ${attempt.transport.channel === 'chrome' ? 'Chrome' : 'Edge'};只使用本次创建的调试标签页`);
23363
- return {
23525
+ return createBrowserLease(proxy, {
23364
23526
  mode: 'attached',
23365
23527
  fallbackReason: null,
23366
23528
  channel: attempt.transport.channel,
23367
- cdpEndpoint: lease.endpoint,
23368
- getTargetId: () => lease.getTargetId(),
23369
- openPage: (nextUrl, signal) => lease.openPage(nextUrl, signal),
23370
- isClosed: () => lease.isClosed(),
23371
- close: () => lease.close(),
23372
- verifyBrowserPageOwner: (token, pageId, signal) => lease.verifyBrowserPageOwner(token, pageId, signal),
23373
- };
23529
+ });
23374
23530
  }
23375
23531
  catch (error) {
23376
23532
  // 代理负责等待晚到的 createTarget 响应并关闭自有标签页,不能提前切断其清理通道。
@@ -23393,7 +23549,105 @@ async function openPreviewBrowser(url, channel, options = {}) {
23393
23549
  }
23394
23550
  }
23395
23551
  options.signal?.throwIfAborted();
23396
- return launchIsolatedBrowser(url, channel, { ...options, fallbackReason });
23552
+ return launchIsolatedBrowser(url, channel, { ...options, fallbackReason }, reuse);
23553
+ }
23554
+ async function reconnectIsolatedBrowser(url, record, reuse, options) {
23555
+ options.signal?.throwIfAborted();
23556
+ let transport;
23557
+ try {
23558
+ transport = await (options.connectOwned ?? connectOwnedBrowserTransport)(record.profile, record.channel, { signal: options.signal, timeoutMs: 2500 });
23559
+ }
23560
+ catch {
23561
+ options.signal?.throwIfAborted();
23562
+ if (await isRegisteredBrowserRunning(record, options))
23563
+ throw Object.assign(new Error('原 SDK 浏览器仍在运行但暂时无法连接,请关闭该窗口后重试;本次未重复打开浏览器'), { name: 'PreviewError', code: 'BROWSER_RECONNECT_FAILED' });
23564
+ await fs$1.rm(record.profile, { recursive: true, force: true });
23565
+ await reuse.clear();
23566
+ return;
23567
+ }
23568
+ let proxy;
23569
+ try {
23570
+ proxy = await (options.createProxy ?? createScopedCdpProxy)(transport, {
23571
+ url, signal: options.signal, reuseTarget: record.target,
23572
+ createOwnedPage: options.createOwnedPage ? address => options.createOwnedPage(address, record.channel) : undefined,
23573
+ });
23574
+ options.signal?.throwIfAborted();
23575
+ await reuse.save({ ...record, target: proxy.getReusableTarget() });
23576
+ const lease = persistentBrowserLease(proxy, record, reuse, async () => {
23577
+ // 仅针对 SDK 自建 profile 的浏览器;不经过消费者受限 CDP endpoint。
23578
+ await transport.request('Browser.close').catch(() => undefined);
23579
+ const deadline = Date.now() + 2000;
23580
+ while (isBrowserProcessAlive(record.pid) && Date.now() < deadline)
23581
+ await new Promise(resolve => setTimeout(resolve, 50));
23582
+ if (await isRegisteredBrowserRunning(record, options))
23583
+ throw new Error('SDK 浏览器尚未退出,已保留其登记供下次重新连接');
23584
+ });
23585
+ options.progress?.('已复用当前项目的 SDK 独立浏览器,并建立新的开发会话');
23586
+ return lease;
23587
+ }
23588
+ catch (error) {
23589
+ await proxy?.close().catch(() => undefined);
23590
+ await transport.close().catch(() => undefined);
23591
+ throw error;
23592
+ }
23593
+ }
23594
+ async function isRegisteredBrowserRunning(record, options) {
23595
+ if (!isBrowserProcessAlive(record.pid))
23596
+ return false;
23597
+ const identity = record.processIdentity ? await index.readProcessIdentity(record.pid) : undefined;
23598
+ if (identity === null)
23599
+ return false;
23600
+ if (identity && identity === record.processIdentity)
23601
+ return true;
23602
+ const usingProfile = await (options.isBrowserUsingProfile ?? index.isProcessUsingProfile)(record.pid, record.profile);
23603
+ if (usingProfile !== undefined)
23604
+ return usingProfile;
23605
+ // 启动标识不同已经证明PID被复用;旧格式或查询失败时仍保守保留登记。
23606
+ return !identity;
23607
+ }
23608
+ function persistentBrowserLease(proxy, record, reuse, stop, fallbackReason = null) {
23609
+ let closing;
23610
+ let lastTarget = record.target;
23611
+ const save = async () => {
23612
+ // 控制连接断开会清空代理快照,但不代表原标签页已被关闭。
23613
+ lastTarget = proxy.getReusableTarget() ?? lastTarget;
23614
+ await reuse.save({ ...record, target: lastTarget });
23615
+ };
23616
+ return createBrowserLease(proxy, { channel: record.channel, mode: 'isolated', fallbackReason }, {
23617
+ async openPage(url, signal) {
23618
+ await proxy.openPage(url, signal);
23619
+ await save();
23620
+ },
23621
+ release: () => closing ??= (async () => {
23622
+ try {
23623
+ await save();
23624
+ }
23625
+ finally {
23626
+ try {
23627
+ await proxy.release();
23628
+ }
23629
+ finally {
23630
+ await reuse.release();
23631
+ }
23632
+ }
23633
+ })(),
23634
+ close: () => closing ??= (async () => {
23635
+ try {
23636
+ // Browser.close 需要在代理关闭上游连接之前发出。
23637
+ try {
23638
+ await stop();
23639
+ }
23640
+ finally {
23641
+ await proxy.close();
23642
+ }
23643
+ await reuse.clear();
23644
+ await fs$1.rm(record.profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => undefined);
23645
+ }
23646
+ finally {
23647
+ await reuse.release();
23648
+ }
23649
+ })(),
23650
+ });
23397
23651
  }
23398
23652
  /** 授权阶段取消可以立即结束;晚到的授权只释放连接,绝不继续创建标签页。 */
23399
23653
  async function waitForAttachment(work, signal) {
@@ -23422,8 +23676,8 @@ async function waitForAttachment(work, signal) {
23422
23676
  aborted();
23423
23677
  });
23424
23678
  }
23425
- /** 仅启动本机已有浏览器,profile 归本次 dev 所有,退出后清理。 */
23426
- async function launchIsolatedBrowser(url, channel, options) {
23679
+ /** 仅启动本机已有浏览器;持有项目登记时,profile 与浏览器可跨 dev 重启复用。 */
23680
+ async function launchIsolatedBrowser(url, channel, options, reuse) {
23427
23681
  for (const candidate of options.candidates ?? previewBrowserCandidates()) {
23428
23682
  options.signal?.throwIfAborted();
23429
23683
  if (channel && channel !== candidate.channel)
@@ -23434,7 +23688,7 @@ async function launchIsolatedBrowser(url, channel, options) {
23434
23688
  catch {
23435
23689
  continue;
23436
23690
  }
23437
- const profile = await fs$1.mkdtemp(path.join(os.tmpdir(), 'hb-sdk-preview-'));
23691
+ const profile = await fs$1.mkdtemp(reuse ? path.join(reuse.directory, 'profile-') : path.join(os.tmpdir(), 'hb-sdk-preview-'));
23438
23692
  if (options.signal?.aborted) {
23439
23693
  await fs$1.rm(profile, { recursive: true, force: true });
23440
23694
  options.signal.throwIfAborted();
@@ -23451,7 +23705,7 @@ async function launchIsolatedBrowser(url, channel, options) {
23451
23705
  '--no-first-run',
23452
23706
  '--no-default-browser-check',
23453
23707
  '--no-startup-window',
23454
- ], { stdio: options.observeProcess ? ['ignore', 'ignore', 'pipe'] : 'ignore', windowsHide: false });
23708
+ ], { stdio: options.observeProcess ? ['ignore', 'ignore', 'pipe'] : 'ignore', windowsHide: false, detached: Boolean(reuse) });
23455
23709
  let exited = false;
23456
23710
  child.once('error', () => {
23457
23711
  exited = true;
@@ -23469,6 +23723,7 @@ async function launchIsolatedBrowser(url, channel, options) {
23469
23723
  let transport;
23470
23724
  let proxy;
23471
23725
  let closing;
23726
+ let processIdentity;
23472
23727
  const close = () => (closing ??= (async () => {
23473
23728
  await proxy?.close().catch(() => undefined);
23474
23729
  if (transport && !transport.isClosed())
@@ -23476,6 +23731,7 @@ async function launchIsolatedBrowser(url, channel, options) {
23476
23731
  await stopBrowser(child, () => exited);
23477
23732
  // Chromium 子进程退出后再清理;Windows 短暂持有文件时不影响 dev 退出。
23478
23733
  await fs$1.rm(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => undefined);
23734
+ await reuse?.clear();
23479
23735
  })());
23480
23736
  // 自有进程在启动取消时可以直接退出,即使 createTarget 的响应尚未返回也不会遗留页面。
23481
23737
  const abortStartup = () => {
@@ -23483,6 +23739,11 @@ async function launchIsolatedBrowser(url, channel, options) {
23483
23739
  };
23484
23740
  options.signal?.addEventListener('abort', abortStartup, { once: true });
23485
23741
  try {
23742
+ // 在浏览器尚未就绪时崩溃,下次也能找到这一自建进程,避免再启动一个。
23743
+ if (reuse && child.pid) {
23744
+ processIdentity = (await index.readProcessIdentity(child.pid)) ?? undefined;
23745
+ await reuse.save({ profile, pid: child.pid, processIdentity, channel: candidate.channel });
23746
+ }
23486
23747
  const deadline = Date.now() + 10_000;
23487
23748
  while (!exited && Date.now() < deadline) {
23488
23749
  options.signal?.throwIfAborted();
@@ -23509,18 +23770,21 @@ async function launchIsolatedBrowser(url, channel, options) {
23509
23770
  }
23510
23771
  options.signal?.throwIfAborted();
23511
23772
  const lease = proxy;
23773
+ if (reuse && child.pid) {
23774
+ const record = { profile, pid: child.pid, processIdentity, channel: candidate.channel, target: lease.getReusableTarget() };
23775
+ await reuse.save(record);
23776
+ child.unref();
23777
+ return persistentBrowserLease(lease, record, reuse, () => stopBrowser(child, () => exited), options.fallbackReason);
23778
+ }
23512
23779
  // 已建立的lease可能在创建后立刻被用户关闭;保留身份交给控制器报告,不再次开其它窗口。
23513
- return {
23780
+ return createBrowserLease(lease, {
23514
23781
  mode: 'isolated',
23515
23782
  fallbackReason: options.fallbackReason,
23516
23783
  channel: candidate.channel,
23517
- cdpEndpoint: lease.endpoint,
23518
- getTargetId: () => lease.getTargetId(),
23784
+ }, {
23519
23785
  isClosed: () => exited || lease.isClosed(),
23520
23786
  close,
23521
- verifyBrowserPageOwner: (token, pageId, signal) => lease.verifyBrowserPageOwner(token, pageId, signal),
23522
- openPage: (nextUrl, signal) => lease.openPage(nextUrl, signal),
23523
- };
23787
+ });
23524
23788
  }
23525
23789
  await new Promise((resolve) => setTimeout(resolve, 100));
23526
23790
  }
@@ -23712,6 +23976,7 @@ class PreviewController {
23712
23976
  this.browser = undefined;
23713
23977
  signal.throwIfAborted();
23714
23978
  const browser = await (this.options.openBrowser ?? openPreviewBrowser)(this.url, this.options.channel, {
23979
+ projectRoot: this.options.projectRoot,
23715
23980
  signal,
23716
23981
  mode: this.options.browserMode ?? 'auto',
23717
23982
  progress: this.options.progress,
@@ -24060,8 +24325,11 @@ class PreviewController {
24060
24325
  this.shutdown.abort(new PreviewError('SESSION_CLOSED', '开发会话已关闭'));
24061
24326
  this.closing = (async () => {
24062
24327
  await this.opening?.catch(() => undefined);
24063
- await this.browser?.close();
24064
24328
  await this.connection?.close().catch(() => undefined);
24329
+ if (this.browser?.release)
24330
+ await this.browser.release();
24331
+ else
24332
+ await this.browser?.close();
24065
24333
  })();
24066
24334
  return this.closing;
24067
24335
  }
@@ -24223,7 +24491,9 @@ class DeviceLogStore {
24223
24491
  pending = new Map();
24224
24492
  uploadSessions = new Map();
24225
24493
  targetSnapshot(target, now = Date.now()) {
24226
- return { ...target, stale: target.state !== 'closed' && now - target.updatedAt > 15000 };
24494
+ const current = target.currentInstanceId ? this.instances.get(target.currentInstanceId) : undefined;
24495
+ return { ...target, capabilities: current?.capabilities ?? target.capabilities,
24496
+ stale: target.state !== 'closed' && now - target.updatedAt > 15000 };
24227
24497
  }
24228
24498
  instanceSnapshot(instance, now = Date.now()) {
24229
24499
  return {