@heybox/hb-sdk 0.9.6-alpha.11 → 0.9.6-alpha.14

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 (48) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +4 -1
  3. package/THIRD_PARTY_NOTICES.md +472 -48
  4. package/dist/cli-chunks/{artifact-BW6SD1G6.cjs → artifact-DTqf7LjW.cjs} +6 -5
  5. package/dist/cli-chunks/{build-B0Id0UTN.cjs → build-BY4DoIBI.cjs} +6 -5
  6. package/dist/cli-chunks/{create-DVu93Ekp.cjs → create-DG-eZzS2.cjs} +322 -4
  7. package/dist/cli-chunks/{dev-CeSjpEZQ.cjs → dev-BeSGi9u8.cjs} +20 -16
  8. package/dist/cli-chunks/{dev-context-CVc_BsWR.cjs → dev-context-7fvQuwt0.cjs} +22 -14
  9. package/dist/cli-chunks/{doctor-BF9mtkJr.cjs → doctor-DcxJh-U3.cjs} +1 -1
  10. package/dist/cli-chunks/{games-BKnDCklM.cjs → games-CbQNW3Z3.cjs} +1 -1
  11. package/dist/cli-chunks/{index-Cgui_8Rk.cjs → index-NJUh9sVX.cjs} +1 -1
  12. package/dist/cli-chunks/{index-Rp3UMZIO.cjs → index-lnwfzT8S.cjs} +73 -20
  13. package/dist/cli-chunks/index.esm-CvMA_ppV.cjs +7977 -0
  14. package/dist/cli-chunks/{index.esm-BK0eVYaM.cjs → index.esm-DOXvj-ZK.cjs} +7 -6
  15. package/dist/cli-chunks/{login-DpeDN-mt.cjs → login-PYy4XDVv.cjs} +1 -1
  16. package/dist/cli-chunks/{project-vite-Cg3jYqAJ.cjs → project-vite-Dzd2JLIc.cjs} +1 -1
  17. package/dist/cli-chunks/{remote-BQ-9rhTb.cjs → remote-r0tXpJh6.cjs} +13 -8
  18. package/dist/cli-chunks/{runtime-permission-env-BgipCJ0Z.cjs → runtime-permission-env-CN2K4GG7.cjs} +52 -6990
  19. package/dist/cli-chunks/{skill-D7pd4yPq.cjs → skill-BbrtzJTC.cjs} +2 -2
  20. package/dist/cli-chunks/{version-DbjRZkb6.cjs → version-SpegXNoR.cjs} +1 -1
  21. package/dist/cli.cjs +1 -1
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DdLOxwBk.js +228 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-DeuOZXeW.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-B-2wxdQX.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 +1030 -155
  29. package/dist/index.esm.js +1030 -155
  30. package/dist/miniapp-publish.cjs.js +1071 -130
  31. package/dist/miniapp-publish.esm.js +1071 -130
  32. package/dist/protocol.cjs.js +727 -158
  33. package/dist/protocol.esm.js +711 -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 +1076 -133
  38. package/dist/vite.esm.js +1076 -133
  39. package/package.json +6 -7
  40. package/skill/SKILL.md +4 -0
  41. package/skill/skill.json +5 -5
  42. package/types/index.d.ts +386 -9
  43. package/types/miniapp-publish/index.d.ts +18 -2
  44. package/types/protocol.d.ts +1 -1
  45. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DVlT56iQ.js +0 -100
  46. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-BzRxl_MM.js +0 -6
  47. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +0 -1
  48. package/dist/devtools/browser-dev-host/assets/index-DY5ZynQp.js +0 -586
@@ -5,7 +5,8 @@ var fs = require('node:fs/promises');
5
5
  var path = require('node:path');
6
6
  var require$$0 = require('fs');
7
7
  var require$$1 = require('path');
8
- var index = require('./index-Rp3UMZIO.cjs');
8
+ var index = require('./index-lnwfzT8S.cjs');
9
+ var index_esm = require('./index.esm-CvMA_ppV.cjs');
9
10
  require('node:module');
10
11
  require('readline');
11
12
  require('os');
@@ -1245,7 +1246,294 @@ function requireEjs () {
1245
1246
 
1246
1247
  var ejsExports = requireEjs();
1247
1248
 
1249
+ const CATALOG_BY_KEY = new Map(index_esm.GAME_DATA_RESOURCE_CATALOG.map((definition) => [definition.key, definition]));
1250
+ const FEATURE_SET = new Set(index_esm.USER_GAME_DATA_RESOURCE_FAMILIES);
1251
+ /**
1252
+ * 校验并规范化 `hb-sdk create` 的资料声明参数。
1253
+ *
1254
+ * @param options - 命令行原始取值;未传时返回空声明,不默认声明任何资源。
1255
+ * @returns 目录顺序、去重后的精确资源清单;空清单表示不写 `user_game_data`。
1256
+ * @throws 未知游戏、未知功能、未开放的资源 key、通配符或前缀 key、`--features` 缺失 `--game`、
1257
+ * `--game` 缺少资源选择、资源不属于显式指定的游戏时抛出;调用方必须在写文件前调用,报错时
1258
+ * 不得生成任何工程文件。
1259
+ *
1260
+ * @remarks
1261
+ * 本函数只读取 {@link GAME_DATA_RESOURCE_CATALOG} 这一冻结目录,不做源码扫描、不做模糊匹配,
1262
+ * 也不会因为上游新增解析分支而扩大清单:`*`、`?`、`game.ark` 这类前缀或额外子路径一律报错。
1263
+ * 显式分离「游戏 + 功能」和「精确资源 key」两条路径,两者可以同时使用,但显式 `--game` 会成为
1264
+ * `--resources` 的归属约束,避免一次创建静默带上未指定的游戏。
1265
+ *
1266
+ * @since 0.9.6
1267
+ */
1268
+ function parseCreateUserGameDataSelection(options) {
1269
+ const games = normalizeSelections(options.games, '--game');
1270
+ const features = normalizeSelections(options.features, '--features');
1271
+ const resourceValues = normalizeSelections(options.resources, '--resources');
1272
+ if (games.length === 0 && features.length === 0 && resourceValues.length === 0) {
1273
+ return { definitions: [], resources: [] };
1274
+ }
1275
+ const selectedGames = games.map(assertGameId);
1276
+ const selectedFeatures = features.map(assertFeature);
1277
+ if (selectedFeatures.length > 0 && selectedGames.length === 0) {
1278
+ throw new Error('--features 必须与 --game 一起使用;不会隐式声明全部游戏的功能');
1279
+ }
1280
+ if (selectedGames.length > 0 && selectedFeatures.length === 0 && resourceValues.length === 0) {
1281
+ throw new Error('--game 需要同时指定 --features 或 --resources;不会默认声明该游戏的全部资源');
1282
+ }
1283
+ const selectedKeys = new Set();
1284
+ for (const game of selectedGames) {
1285
+ for (const feature of selectedFeatures) {
1286
+ const matched = index_esm.GAME_DATA_RESOURCE_CATALOG.filter((definition) => definition.game === game && definition.family === feature);
1287
+ if (matched.length === 0) {
1288
+ throw new Error(`游戏 ${game} 未开放功能:${feature};请检查 --features 取值`);
1289
+ }
1290
+ for (const definition of matched)
1291
+ selectedKeys.add(definition.key);
1292
+ }
1293
+ }
1294
+ for (const value of resourceValues) {
1295
+ if (!index_esm.isUserGameDataResourceKey(value)) {
1296
+ throw new Error(describeUnsupportedResource(value));
1297
+ }
1298
+ if (selectedGames.length > 0) {
1299
+ const definition = CATALOG_BY_KEY.get(value);
1300
+ if (!definition || !selectedGames.includes(definition.game)) {
1301
+ throw new Error(`资源 ${value} 不属于 --game 指定的游戏:${selectedGames.join('、')}`);
1302
+ }
1303
+ }
1304
+ selectedKeys.add(value);
1305
+ }
1306
+ // 统一按冻结目录顺序输出,避免命令行顺序把 Manifest 写成不稳定形态。
1307
+ const definitions = index_esm.GAME_DATA_RESOURCE_CATALOG.filter((definition) => selectedKeys.has(definition.key));
1308
+ return { definitions, resources: definitions.map((definition) => definition.key) };
1309
+ }
1310
+ /** 拆分重复参数和逗号分隔值,保留首次出现的顺序并提前拦截通配符与空值。 */
1311
+ function normalizeSelections(values, optionName) {
1312
+ const normalized = [];
1313
+ for (const raw of values ?? []) {
1314
+ for (const part of raw.split(',')) {
1315
+ const value = part.trim();
1316
+ if (!value)
1317
+ throw new Error(`${optionName} 不能包含空值`);
1318
+ if (value.includes('*') || value.includes('?')) {
1319
+ throw new Error(`${optionName} 不接受通配符:${value};请使用目录中的精确值`);
1320
+ }
1321
+ if (!normalized.includes(value))
1322
+ normalized.push(value);
1323
+ }
1324
+ }
1325
+ return normalized;
1326
+ }
1327
+ function assertGameId(value) {
1328
+ if (!index_esm.isUserGameDataGameId(value)) {
1329
+ throw new Error(`未知游戏标识:${value};首发仅支持 ${index_esm.USER_GAME_DATA_GAME_IDS.join('、')}`);
1330
+ }
1331
+ return value;
1332
+ }
1333
+ function assertFeature(value) {
1334
+ if (!FEATURE_SET.has(value)) {
1335
+ throw new Error(`未知功能标识:${value};首发仅支持 ${index_esm.USER_GAME_DATA_RESOURCE_FAMILIES.join('、')}`);
1336
+ }
1337
+ return value;
1338
+ }
1339
+ /** 为未开放的资源 key 给出可操作的报错,明确它不是通配符、前缀或未来条目。 */
1340
+ function describeUnsupportedResource(value) {
1341
+ const exactKeys = index_esm.USER_GAME_DATA_RESOURCE_KEYS.join('、');
1342
+ const longerKey = index_esm.USER_GAME_DATA_RESOURCE_KEYS.find((key) => key.startsWith(`${value}.`));
1343
+ if (longerKey) {
1344
+ return `资源不接受前缀:${value};请填写精确 key,例如 ${longerKey}`;
1345
+ }
1346
+ const parentKey = index_esm.USER_GAME_DATA_RESOURCE_KEYS.find((key) => value.startsWith(`${key}.`));
1347
+ if (parentKey) {
1348
+ return `资源不接受额外的子路径:${value};请填写精确 key ${parentKey}`;
1349
+ }
1350
+ return `未开放资源:${value};首发仅支持 ${exactKeys}`;
1351
+ }
1352
+
1353
+ /**
1354
+ * 把校验后的声明范围转换为模板数据。
1355
+ *
1356
+ * @param selection - `parseCreateUserGameDataSelection` 的返回值。
1357
+ * @returns 可直接交给 EJS 的模板数据;资源清单为空时仍返回安全默认值。
1358
+ *
1359
+ * @since 0.9.6
1360
+ */
1361
+ function buildUserGameDataTemplateData(selection, purpose) {
1362
+ const resources = {};
1363
+ if (selection.resources.length > 0) {
1364
+ if (purpose === undefined)
1365
+ throw new Error('声明游戏资料时必须通过 --purpose 填写实际用途(1~30 个 Unicode 码点)');
1366
+ const normalized = index_esm.normalizeUserGameDataPurpose(purpose);
1367
+ for (const key of selection.resources)
1368
+ resources[key] = { purpose: normalized };
1369
+ }
1370
+ const permissions = selection.resources.length === 0 ? {} : { user_game_data: { enabled: true, resources } };
1371
+ return {
1372
+ userGameDataEnabled: selection.resources.length > 0,
1373
+ userGameDataPermissionsJson: indentBlock(JSON.stringify(permissions, null, 4), 4),
1374
+ userGameDataExampleSource: buildUserGameDataExampleSource(selection.definitions),
1375
+ userGameDataResources: selection.resources,
1376
+ };
1377
+ }
1378
+ /** 给 `JSON.stringify` 结果除首行外的每行补缩进,使内联到模板后保持 4 空格层级。 */
1379
+ function indentBlock(value, size) {
1380
+ const prefix = ' '.repeat(size);
1381
+ return value
1382
+ .split('\n')
1383
+ .map((line, index) => (index === 0 ? line : `${prefix}${line}`))
1384
+ .join('\n');
1385
+ }
1386
+ /**
1387
+ * 生成 `src/user-game-data.js`:带类型的示例片段与浏览器 Mock。
1388
+ *
1389
+ * @param definitions - 已是精确资源清单的目录定义,顺序即声明顺序。
1390
+ * @returns 完整 JS 源码;清单为空时返回空字符串(调用方不生成该文件)。
1391
+ *
1392
+ * @remarks
1393
+ * 示例与 Mock 都由同一份 `definitions` 生成,不存在第二份资源清单,因此不会与
1394
+ * `package.json#heybox.permissions.user_game_data.resources` 漂移。Mock 只返回明确的空结果,
1395
+ * 不伪造资料、许可或授权状态;本文件不声明 `userInfo`、`network` 等额外权限。
1396
+ *
1397
+ * @since 0.9.6
1398
+ */
1399
+ function buildUserGameDataExampleSource(definitions) {
1400
+ if (definitions.length === 0)
1401
+ return '';
1402
+ const lines = [
1403
+ '/**',
1404
+ ' * 平台/游戏资料示例与浏览器 Mock。',
1405
+ ' *',
1406
+ ' * 本文件由 `hb-sdk create --game … --features …` 按',
1407
+ ' * `package.json#heybox.permissions.user_game_data.resources` 生成,只覆盖已声明的资源;',
1408
+ ' * 调整声明后请重新生成或手工同步本文件。',
1409
+ ' *',
1410
+ ' * 读取客户端资料只需要 `user_game_data` 声明:不会因此附加 `userInfo`、`network` 或平台审批要求;',
1411
+ ' * 每项资源仍需用户在本设备逐项许可。缺少登录、许可或来源时 SDK 返回 blocked,',
1412
+ ' * 请展示返回的操作,不要伪造空数据。',
1413
+ ' */',
1414
+ '',
1415
+ '/** 已声明并生成示例的资源 key,与 package.json 声明逐项一致。 */',
1416
+ 'export const declaredGameDataResources = [',
1417
+ ...definitions.map((definition) => ` '${definition.key}',`),
1418
+ '];',
1419
+ '',
1420
+ ];
1421
+ for (const definition of definitions) {
1422
+ lines.push('/**', ` * ${definition.name}`, ' *', ` * 资源:\`${definition.key}\``, ' *', ' * @example', ...buildExampleCallLines(definition).map((line) => ` * ${line}`), ' */', '');
1423
+ }
1424
+ lines.push(...buildMockLines(definitions));
1425
+ return `${lines.join('\n')}\n`;
1426
+ }
1427
+ /**
1428
+ * 按资源能力族生成带返回类型的调用片段。
1429
+ *
1430
+ * @remarks
1431
+ * 首版 `profile` / `gacha` 只属于明日方舟,存档能力族只属于三款存档游戏,因此这里的类型名
1432
+ * 与冻结目录一致;新增游戏仍需在目录登记后重新生成向导产物,不会被源码扫描自动带出。
1433
+ */
1434
+ function buildExampleCallLines(definition) {
1435
+ const call = `hbSDK.user.games.get('${definition.game}')`;
1436
+ switch (definition.family) {
1437
+ case 'profile':
1438
+ return [
1439
+ `const profile = await ${call}.getProfile();`,
1440
+ '// 返回 ReadResult<ArkProfile>:ready 有数据,empty 无数据或未就绪,blocked 需先完成操作。',
1441
+ "if (profile.status === 'ready') renderProfile(profile.data);",
1442
+ "if (profile.status === 'blocked' && profile.action) renderAction(profile.action);",
1443
+ ];
1444
+ case 'gacha':
1445
+ return [
1446
+ `const analysis = await ${call}.getGachaAnalysis();`,
1447
+ '// 返回 ReadResult<ArkGachaAnalysis>:只做展示,不自动补拉来源数据。',
1448
+ `const records = await ${call}.listGachaRecords();`,
1449
+ '// 返回 ReadResult<Page<GachaRecord>>:nextCursor 绑定当前查询,换源后从首页重新读取。',
1450
+ "if (records.status === 'ready') renderGachaRecords(records.data.items);",
1451
+ ];
1452
+ case 'save_analysis':
1453
+ return [
1454
+ `const latest = await ${call}.saves.getLatestStructuredData();`,
1455
+ `// 返回 ReadResult<${resolveSaveResultType(definition.game)}>:只读已有解析结果,不启动同步或解析。`,
1456
+ `const sync = await ${call}.saves.sync();`,
1457
+ '// 返回 SyncResult:succeeded 只代表文件已同步,解析结果可能仍未更新。',
1458
+ "if (sync.status === 'blocked' && sync.action) renderAction(sync.action);",
1459
+ ];
1460
+ case 'save_files':
1461
+ return [
1462
+ `const files = await ${call}.saves.list();`,
1463
+ '// 返回 ReadResult<UserGameSaveInfo[]>:每个存档批次的 files[] 中提供受控 downloadFile(),不暴露任意路径。',
1464
+ "if (files.status === 'ready') renderSaveFiles(files.data);",
1465
+ ];
1466
+ }
1467
+ }
1468
+ /** 三款存档游戏的公开解析结果类型名;映射穷举存档 GameId,新增游戏会触发类型检查。 */
1469
+ const SAVE_RESULT_TYPES = {
1470
+ black_myth_wukong: 'BlackMythWukongSave',
1471
+ task_bar_hero: 'TaskBarHeroSave',
1472
+ phantom_blade_zero: 'PhantomBladeZeroSave',
1473
+ };
1474
+ function resolveSaveResultType(game) {
1475
+ if (game === 'ark') {
1476
+ // 目录中 ark 没有存档资源;显式抛错,避免未来目录变化时静默生成错误示例。
1477
+ throw new Error('明日方舟没有存档资源,无法生成存档示例类型');
1478
+ }
1479
+ return SAVE_RESULT_TYPES[game];
1480
+ }
1481
+ /** 生成与资源清单一一对应的最小 Mock:按游戏分组,只返回明确的空结果。 */
1482
+ function buildMockLines(definitions) {
1483
+ const games = [...new Set(definitions.map((definition) => definition.game))];
1484
+ const lines = [
1485
+ '/**',
1486
+ ' * 浏览器 Mock:与上面的资源清单一一对应,只返回空结果,不伪造资料或授权状态。',
1487
+ ' *',
1488
+ ' * 用法:本地浏览器预览时,把页面的真实读取替换为 createUserGameDataMock() 的返回值。',
1489
+ ' *',
1490
+ ' * @returns {object} 按游戏分组的只读 stub;仅用于本地 UI 占位。',
1491
+ ' */',
1492
+ 'export function createUserGameDataMock() {',
1493
+ ' return {',
1494
+ ];
1495
+ for (const game of games) {
1496
+ const gameDefinitions = definitions.filter((definition) => definition.game === game);
1497
+ lines.push(` ${game}: {`);
1498
+ if (game === 'ark') {
1499
+ // 明日方舟首版只有 profile / gacha 两项能力族,没有 saves 模块。
1500
+ for (const definition of gameDefinitions) {
1501
+ switch (definition.family) {
1502
+ case 'profile':
1503
+ lines.push(` getProfile: () => emptyReadResult('${definition.key}'),`);
1504
+ break;
1505
+ case 'gacha':
1506
+ lines.push(` getGachaAnalysis: () => emptyReadResult('${definition.key}'),`);
1507
+ lines.push(` listGachaRecords: () => emptyReadResult('${definition.key}'),`);
1508
+ break;
1509
+ }
1510
+ }
1511
+ }
1512
+ else {
1513
+ lines.push(' saves: {');
1514
+ for (const definition of gameDefinitions) {
1515
+ switch (definition.family) {
1516
+ case 'save_analysis':
1517
+ lines.push(` getLatestStructuredData: () => emptyReadResult('${definition.key}'),`);
1518
+ lines.push(' // 本地 stub:不访问云端,仅用于 UI 占位。');
1519
+ lines.push(" sync: () => ({ status: 'succeeded' }),");
1520
+ break;
1521
+ case 'save_files':
1522
+ lines.push(` list: () => emptyReadResult('${definition.key}'),`);
1523
+ break;
1524
+ }
1525
+ }
1526
+ lines.push(' },');
1527
+ }
1528
+ lines.push(' },');
1529
+ }
1530
+ lines.push(' };', '}', '', '/**', ' * 构造明确的空读取结果,避免 Mock 伪造资料或授权状态。', ' *', ' * @param {string} resource 资源 key', ' */', 'function emptyReadResult(resource) {', ' return {', " status: 'empty',", " reason: 'no_data',", ' message: `本地 Mock 未提供 ${resource} 的真实资料`,', ' meta: {},', ' };', '}');
1531
+ return lines;
1532
+ }
1533
+
1248
1534
  const TEMPLATE_NAME = 'vanilla-vite-js';
1535
+ /** 只有声明了资源才生成的文件(相对模板根路径,含 `.ejs` 后缀);无参创建的产物保持最小。 */
1536
+ const USER_GAME_DATA_TEMPLATE_FILES = ['src/user-game-data.js.ejs'];
1249
1537
  const TEMPLATE_ROOT_CANDIDATES = [
1250
1538
  path.resolve(__dirname, 'templates', TEMPLATE_NAME),
1251
1539
  path.resolve(__dirname, '..', 'templates', TEMPLATE_NAME),
@@ -1264,17 +1552,29 @@ async function runCreateCommand(projectName, options = {}) {
1264
1552
  const cwd = options.cwd ?? process.cwd();
1265
1553
  const targetDir = path.resolve(cwd, projectName);
1266
1554
  const packageName = readPackageName(projectName, targetDir);
1555
+ // 先完成声明校验:非法的游戏、功能或资源必须在创建目录、写文件之前退出,避免留下半成品工程。
1556
+ const userGameData = parseCreateUserGameDataSelection({
1557
+ features: options.features,
1558
+ games: options.games,
1559
+ resources: options.resources,
1560
+ });
1561
+ const userGameDataTemplate = buildUserGameDataTemplateData(userGameData, options.purpose);
1267
1562
  await assertTargetDirectoryWritable(targetDir);
1268
1563
  const templateRoot = await resolveTemplateRoot(options.templateRoots);
1269
1564
  const data = {
1270
1565
  packageName,
1271
1566
  projectName: packageName,
1272
1567
  sdkVersion: await readCurrentSdkVersion(options.packageJsonFiles),
1568
+ ...userGameDataTemplate,
1273
1569
  };
1274
- await renderTemplateDirectory(templateRoot, targetDir, data);
1570
+ await renderTemplateDirectory(templateRoot, targetDir, data, {
1571
+ skipFiles: userGameData.resources.length === 0 ? USER_GAME_DATA_TEMPLATE_FILES : undefined,
1572
+ templateRoot,
1573
+ });
1275
1574
  printCreateResult(projectName, targetDir, {
1276
1575
  cwd,
1277
1576
  logger: options.logger,
1577
+ userGameDataResources: userGameData.resources,
1278
1578
  });
1279
1579
  }
1280
1580
  function readPackageName(projectName, targetDir) {
@@ -1328,15 +1628,19 @@ async function resolvePackageJsonPath(packageJsonCandidates = PACKAGE_JSON_CANDI
1328
1628
  }
1329
1629
  throw new Error('未找到 @heybox/hb-sdk package.json');
1330
1630
  }
1331
- async function renderTemplateDirectory(sourceDir, targetDir, data) {
1631
+ async function renderTemplateDirectory(sourceDir, targetDir, data, options = {}) {
1632
+ const templateRoot = options.templateRoot ?? sourceDir;
1332
1633
  const entries = await fs.readdir(sourceDir, { withFileTypes: true });
1333
1634
  for (const entry of entries) {
1334
1635
  const sourcePath = path.join(sourceDir, entry.name);
1636
+ if (options.skipFiles?.includes(toTemplateRelativePath(templateRoot, sourcePath))) {
1637
+ continue;
1638
+ }
1335
1639
  const outputName = toOutputFileName(entry.name);
1336
1640
  const targetPath = path.join(targetDir, outputName);
1337
1641
  if (entry.isDirectory()) {
1338
1642
  await fs.mkdir(targetPath, { recursive: true });
1339
- await renderTemplateDirectory(sourcePath, targetPath, data);
1643
+ await renderTemplateDirectory(sourcePath, targetPath, data, { ...options, templateRoot });
1340
1644
  continue;
1341
1645
  }
1342
1646
  if (!entry.isFile()) {
@@ -1354,6 +1658,10 @@ async function renderTemplateDirectory(sourceDir, targetDir, data) {
1354
1658
  await fs.writeFile(targetPath, rendered, 'utf8');
1355
1659
  }
1356
1660
  }
1661
+ /** 以 `/` 分隔的模板内相对路径,用于稳定匹配需要跳过的可选模板文件。 */
1662
+ function toTemplateRelativePath(templateRoot, sourcePath) {
1663
+ return path.relative(templateRoot, sourcePath).split(path.sep).join('/');
1664
+ }
1357
1665
  function toOutputFileName(fileName) {
1358
1666
  return fileName.endsWith('.ejs') ? fileName.slice(0, -'.ejs'.length) : fileName;
1359
1667
  }
@@ -1371,6 +1679,16 @@ function printCreateResult(inputPath, targetDir, options) {
1371
1679
  const cwd = options.cwd;
1372
1680
  const displayPath = path.isAbsolute(inputPath) ? targetDir : path.relative(cwd, targetDir) || '.';
1373
1681
  logger.success(`已创建外部小程序模板:${targetDir}`);
1682
+ const resources = options.userGameDataResources ?? [];
1683
+ if (resources.length > 0) {
1684
+ logger.section('平台/游戏资料声明');
1685
+ logger.info(`package.json#heybox.permissions.user_game_data 已声明 ${resources.length} 项资源:`);
1686
+ for (const resource of resources) {
1687
+ logger.info(`- ${resource}`);
1688
+ }
1689
+ logger.info('user_game_data 是声明型权限,无需 remote permission apply;每项资源仍需用户在本设备逐项许可。');
1690
+ logger.info('已生成带类型的示例与浏览器 Mock:src/user-game-data.js');
1691
+ }
1374
1692
  logger.section('下一步');
1375
1693
  logger.info(`cd ${quoteShellPath(displayPath)}`);
1376
1694
  logger.info('npm install');
@@ -1,13 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-Rp3UMZIO.cjs');
3
+ var index = require('./index-lnwfzT8S.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-BgipCJ0Z.cjs');
8
- var version = require('./version-DbjRZkb6.cjs');
7
+ var index_esm = require('./index.esm-CvMA_ppV.cjs');
8
+ var version = require('./version-SpegXNoR.cjs');
9
+ var runtimePermissionEnv = require('./runtime-permission-env-CN2K4GG7.cjs');
9
10
  require('node:zlib');
10
- var devContext = require('./dev-context-CVc_BsWR.cjs');
11
+ var devContext = require('./dev-context-7fvQuwt0.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-Cg3jYqAJ.cjs');
33
+ var projectVite = require('./project-vite-Dzd2JLIc.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-CeSjpEZQ.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-CeSjpEZQ.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-BeSGi9u8.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-BeSGi9u8.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-BK0eVYaM.cjs'); });
12679
+ const mod = await Promise.resolve().then(function () { return require('./index.esm-DOXvj-ZK.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)
@@ -24489,7 +24491,9 @@ class DeviceLogStore {
24489
24491
  pending = new Map();
24490
24492
  uploadSessions = new Map();
24491
24493
  targetSnapshot(target, now = Date.now()) {
24492
- 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 };
24493
24497
  }
24494
24498
  instanceSnapshot(instance, now = Date.now()) {
24495
24499
  return {
@@ -1,12 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-Rp3UMZIO.cjs');
4
- var runtimePermissionEnv = require('./runtime-permission-env-BgipCJ0Z.cjs');
3
+ var index = require('./index-lnwfzT8S.cjs');
4
+ var runtimePermissionEnv = require('./runtime-permission-env-CN2K4GG7.cjs');
5
5
  var node_crypto = require('node:crypto');
6
6
  var fs = require('node:fs/promises');
7
7
  var path = require('node:path');
8
8
  var fs$1 = require('node:fs');
9
9
  var sharp = require('sharp');
10
+ var index_esm = require('./index.esm-CvMA_ppV.cjs');
10
11
 
11
12
  function createRemoteApiClient(options) {
12
13
  return {
@@ -544,7 +545,7 @@ async function compareBasicInfo(cwd, detail, fetchImpl = fetch) {
544
545
  function resolveBrowserFakeContext(context, now = Date.now()) {
545
546
  if (context.localDevGrant === undefined)
546
547
  return context;
547
- const parsed = runtimePermissionEnv.parseMiniProgramLocalDevGrant(context.localDevGrant);
548
+ const parsed = index_esm.parseMiniProgramLocalDevGrant(context.localDevGrant);
548
549
  if (!parsed.valid ||
549
550
  !context.devSessionId?.trim() ||
550
551
  !Number.isSafeInteger(context.contextRevision) ||
@@ -557,7 +558,7 @@ function resolveBrowserFakeContext(context, now = Date.now()) {
557
558
  return {
558
559
  ...context,
559
560
  ...(context.expiresAt <= now ? { source: 'anonymous', localDevLaunchToken: undefined, expiresAt: now + 30_000 } : {}),
560
- localDevGrant: runtimePermissionEnv.createMiniProgramLocalDevGrant({
561
+ localDevGrant: index_esm.createMiniProgramLocalDevGrant({
561
562
  declaredPermissions: context.declaredPermissions ?? {},
562
563
  runtimePermissions: context.runtimePermissions,
563
564
  revision: parsed.grant.revision,
@@ -577,8 +578,8 @@ const DEFAULT_PERMISSION_STATE = {
577
578
  },
578
579
  };
579
580
  function createBrowserDevPermissionState(context) {
580
- const parsed = runtimePermissionEnv.parseMiniProgramRuntimePermissions(context.localDevGrant
581
- ? runtimePermissionEnv.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
581
+ const parsed = index_esm.parseMiniProgramRuntimePermissions(context.localDevGrant
582
+ ? index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
582
583
  localDevGrant: context.localDevGrant }).runtimePermissions
583
584
  : context.runtimePermissions);
584
585
  const networkRequest = parsed.permissions.network;
@@ -601,7 +602,7 @@ function createMobileDevSessionRuntimePermissions(context) {
601
602
  const state = createBrowserDevPermissionState(context);
602
603
  return createDevRuntimePermissions(context.runtimePermissions, state, state.networkRequest.useOfficialDomain);
603
604
  }
604
- return runtimePermissionEnv.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions, runtimePermissions: context.runtimePermissions }).runtimePermissions;
605
+ return index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions, runtimePermissions: context.runtimePermissions }).runtimePermissions;
605
606
  }
606
607
  function cloneDefaultPermissionState() {
607
608
  return {
@@ -609,12 +610,12 @@ function cloneDefaultPermissionState() {
609
610
  };
610
611
  }
611
612
  function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
612
- const parsed = runtimePermissionEnv.parseMiniProgramRuntimePermissions(snapshot);
613
+ const parsed = index_esm.parseMiniProgramRuntimePermissions(snapshot);
613
614
  if (!parsed.valid) {
614
615
  return { schema_version: 1, entries: [] };
615
616
  }
616
617
  const entries = [];
617
- for (const key of runtimePermissionEnv.MINI_PROGRAM_PERMISSION_KEYS) {
618
+ for (const key of index_esm.MINI_PROGRAM_PERMISSION_KEYS) {
618
619
  const entry = parsed.permissions[key];
619
620
  if (!entry)
620
621
  continue;
@@ -624,11 +625,18 @@ function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
624
625
  status: state.networkRequest.status,
625
626
  config: { useOfficialDomain },
626
627
  }
627
- : {
628
- key,
629
- status: entry.status,
630
- config: {},
631
- });
628
+ : key === 'user_game_data'
629
+ ? {
630
+ key,
631
+ status: entry.status,
632
+ // 精确资源清单是 snapshot 的合法必需项:浏览器模拟只调整开关,不能丢掉 Manifest 声明。
633
+ config: { resources: entry.config.resources },
634
+ }
635
+ : {
636
+ key,
637
+ status: entry.status,
638
+ config: {},
639
+ });
632
640
  }
633
641
  const revision = isPlainRecord(snapshot) && typeof snapshot.revision === 'number' && Number.isInteger(snapshot.revision) && snapshot.revision >= 0
634
642
  ? snapshot.revision
@@ -3,7 +3,7 @@
3
3
  var fs = require('node:fs/promises');
4
4
  var os = require('node:os');
5
5
  var path = require('node:path');
6
- var index = require('./index-Rp3UMZIO.cjs');
6
+ var index = require('./index-lnwfzT8S.cjs');
7
7
  require('node:module');
8
8
  require('readline');
9
9
  require('os');
@@ -3,7 +3,7 @@
3
3
  var node_crypto = require('node:crypto');
4
4
  var fs = require('node:fs/promises');
5
5
  var path = require('node:path');
6
- var index = require('./index-Rp3UMZIO.cjs');
6
+ var index = require('./index-lnwfzT8S.cjs');
7
7
  require('node:module');
8
8
  require('readline');
9
9
  require('os');
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index$2 = require('./index-Rp3UMZIO.cjs');
3
+ var index$2 = require('./index-lnwfzT8S.cjs');
4
4
  var require$$0$3 = require('fs');
5
5
  var require$$0$2 = require('crypto');
6
6
  var require$$1$2 = require('path');