@heybox/hb-sdk 0.9.8 → 0.9.9-alpha.1

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 (44) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +2 -0
  3. package/dist/cli-chunks/bindings-B9HSKhmy.cjs +84 -0
  4. package/dist/cli-chunks/{build-BuYvQeZO.cjs → build-vZ5iT2JO.cjs} +6 -5
  5. package/dist/cli-chunks/{create-4XrYdjC0.cjs → create-DJseFABS.cjs} +2 -2
  6. package/dist/cli-chunks/{dev-BIxJPUFK.cjs → dev-CsuAVpLX.cjs} +61 -14
  7. package/dist/cli-chunks/{doctor-XhNbYYVj.cjs → doctor-BYzYg-oP.cjs} +1 -1
  8. package/dist/cli-chunks/game-binding-guide-BfKQ4e83.cjs +273 -0
  9. package/dist/cli-chunks/game-bindings-DWOIBCax.cjs +51 -0
  10. package/dist/cli-chunks/{games-Cd9fgl6N.cjs → games-DmPaqaDd.cjs} +2 -2
  11. package/dist/cli-chunks/{index-Cr8tP0XZ.cjs → index-D5rcGk_z.cjs} +55 -24
  12. package/dist/cli-chunks/{index-aGcX-ULf.cjs → index-DPEhBPfc.cjs} +1 -1
  13. package/dist/cli-chunks/{index.esm-CvMA_ppV.cjs → index.esm-CenYK5Bl.cjs} +73 -3
  14. package/dist/cli-chunks/{index.esm-UetP1FSl.cjs → index.esm-DYWovNyE.cjs} +13 -10
  15. package/dist/cli-chunks/{login-Dd55F6qr.cjs → login-o1LQxi8P.cjs} +1 -1
  16. package/dist/cli-chunks/{project-vite-quIPuubf.cjs → project-vite-CGIy1XaL.cjs} +1 -1
  17. package/dist/cli-chunks/{remote-BfI4Ag6B.cjs → remote-BQ3O-aiB.cjs} +131 -133
  18. package/dist/cli-chunks/{runtime-permission-env-C1e5q2m5.cjs → runtime-permission-env-soFtqTxP.cjs} +27 -87
  19. package/dist/cli-chunks/{skill-DY7-DQPL.cjs → skill-BHighcnl.cjs} +2 -2
  20. package/dist/cli-chunks/{version-D4jIw125.cjs → version-CAh_EBAH.cjs} +1 -1
  21. package/dist/cli.cjs +1 -1
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-D9CVFRHE.js +224 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-FZ3iQQs-.js +13 -0
  24. package/dist/devtools/browser-dev-host/assets/index-CVzVitcL.js +567 -0
  25. package/dist/devtools/browser-dev-host/assets/index-D0XGMYIr.css +1 -0
  26. package/dist/devtools/browser-dev-host/index.html +3 -3
  27. package/dist/index.cjs.js +149 -4
  28. package/dist/index.esm.js +149 -5
  29. package/dist/miniapp-publish.cjs.js +65 -2
  30. package/dist/miniapp-publish.esm.js +64 -3
  31. package/dist/protocol.cjs.js +51 -5
  32. package/dist/protocol.esm.js +51 -5
  33. package/dist/templates/vanilla-vite-js/README.md.ejs +1 -1
  34. package/dist/vite.cjs.js +60 -3
  35. package/dist/vite.esm.js +60 -3
  36. package/package.json +6 -6
  37. package/skill/SKILL.md +3 -2
  38. package/skill/skill.json +5 -5
  39. package/types/index.d.ts +140 -4
  40. package/types/miniapp-publish/index.d.ts +14 -3
  41. package/dist/devtools/browser-dev-host/assets/browser-dev-host-x4xuSDs_.js +0 -221
  42. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-C1gCwbuV.js +0 -13
  43. package/dist/devtools/browser-dev-host/assets/index-Bk5RxHO3.css +0 -1
  44. package/dist/devtools/browser-dev-host/assets/index-C6l2jsZT.js +0 -567
@@ -1,14 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var index_esm = require('./index.esm-CvMA_ppV.cjs');
4
- var runtimePermissionEnv = require('./runtime-permission-env-C1e5q2m5.cjs');
3
+ var index_esm = require('./index.esm-CenYK5Bl.cjs');
4
+ var runtimePermissionEnv = require('./runtime-permission-env-soFtqTxP.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 gameBindingGuide = require('./game-binding-guide-BfKQ4e83.cjs');
10
11
  var promises = require('node:readline/promises');
11
- var index = require('./index-Cr8tP0XZ.cjs');
12
+ var index = require('./index-D5rcGk_z.cjs');
12
13
  var childProcess = require('node:child_process');
13
14
  require('node:zlib');
14
15
 
@@ -30,7 +31,7 @@ function getMiniappMetadataWarnings(metadata) {
30
31
  warnings.push({
31
32
  code: 'MINIAPP_TOOL_GAME_BINDING_MISSING',
32
33
  field: 'bindAppIds',
33
- message: '当前小程序为工具类,尚未关联游戏。如服务于特定 PC 游戏,可通过 hb-sdk remote games search "游戏名" 查询 appid 并填写 package.json#heybox.bindAppIds,修改后重新构建;通用工具可保持为空。',
34
+ message: '当前小程序为工具类,尚未关联游戏。关联后可在对应 PC 游戏工作区被发现(仍受适配平台等条件限制)。可在调试台“关联游戏”中选择,或运行 hb-sdk remote games configure;无需关联时可保持为空,修改后重新构建。',
34
35
  });
35
36
  }
36
37
  return warnings;
@@ -107,102 +108,6 @@ async function ensureBasicInfoDirectory(rootPath, relative) {
107
108
  }
108
109
  }
109
110
 
110
- class MiniProgramProjectBindingError extends Error {
111
- code;
112
- constructor(message, code) {
113
- super(message);
114
- this.code = code;
115
- this.name = 'MiniProgramProjectBindingError';
116
- }
117
- }
118
- function findMiniProgramProjectRoot(startDir) {
119
- let current = path.resolve(startDir);
120
- while (true) {
121
- if (fs$1.existsSync(path.join(current, 'package.json'))) {
122
- return current;
123
- }
124
- const parent = path.dirname(current);
125
- if (parent === current) {
126
- throw new MiniProgramProjectBindingError('当前目录或父目录未找到 package.json', 'PACKAGE_JSON_NOT_FOUND');
127
- }
128
- current = parent;
129
- }
130
- }
131
- async function readMiniProgramProjectPackage(startDir) {
132
- const projectRoot = findMiniProgramProjectRoot(startDir);
133
- const packageJsonPath = path.join(projectRoot, 'package.json');
134
- const raw = await fs.readFile(packageJsonPath, 'utf8');
135
- let packageJson;
136
- try {
137
- packageJson = JSON.parse(raw);
138
- }
139
- catch (error) {
140
- const message = error instanceof Error ? error.message : String(error);
141
- throw new MiniProgramProjectBindingError(`package.json 不是合法 JSON:${packageJsonPath}\n${message}`, 'PACKAGE_JSON_INVALID');
142
- }
143
- return {
144
- projectRoot,
145
- packageJsonPath,
146
- packageJson,
147
- raw,
148
- indent: detectJsonIndent(raw),
149
- trailingNewline: raw.endsWith('\r\n') ? '\r\n' : raw.endsWith('\n') ? '\n' : '',
150
- };
151
- }
152
- function readBoundMiniProgramIdFromPackageJson(packageJson) {
153
- const value = packageJson.heybox?.miniProgramId;
154
- return typeof value === 'string' && value.trim() ? value.trim() : undefined;
155
- }
156
- async function readBoundMiniProgramId(startDir) {
157
- return readBoundMiniProgramIdFromPackageJson((await readMiniProgramProjectPackage(startDir)).packageJson);
158
- }
159
- async function requireBoundMiniProgramId(startDir) {
160
- const context = await readMiniProgramProjectPackage(startDir);
161
- const miniProgramId = readBoundMiniProgramIdFromPackageJson(context.packageJson);
162
- if (!miniProgramId) {
163
- throw new MiniProgramProjectBindingError(`当前项目未绑定小程序。请先运行 hb-sdk remote create 或 hb-sdk remote bind <mini-program-id>。\n配置位置:${context.packageJsonPath}#heybox.miniProgramId`, 'MINI_PROGRAM_UNBOUND');
164
- }
165
- return { ...context, miniProgramId };
166
- }
167
- async function writeBoundMiniProgramId(startDir, miniProgramId, options = {}) {
168
- const context = await readMiniProgramProjectPackage(startDir);
169
- const normalizedMiniProgramId = String(miniProgramId).trim();
170
- if (!normalizedMiniProgramId) {
171
- throw new MiniProgramProjectBindingError('miniProgramId 不能为空', 'PACKAGE_JSON_INVALID');
172
- }
173
- const currentMiniProgramId = readBoundMiniProgramIdFromPackageJson(context.packageJson);
174
- if (currentMiniProgramId && currentMiniProgramId !== normalizedMiniProgramId && !options.force) {
175
- throw new MiniProgramProjectBindingError(`当前项目已绑定小程序 ${currentMiniProgramId}。如需覆盖本地绑定,请使用 --force。`, 'MINI_PROGRAM_BINDING_EXISTS');
176
- }
177
- if (currentMiniProgramId === normalizedMiniProgramId) {
178
- return {
179
- ...context,
180
- changed: false,
181
- miniProgramId: normalizedMiniProgramId,
182
- };
183
- }
184
- if (context.packageJson.heybox !== undefined && !isPlainObject(context.packageJson.heybox)) {
185
- throw new MiniProgramProjectBindingError('package.json heybox 字段必须是对象,不能写入 miniProgramId', 'PACKAGE_JSON_HEYBOX_INVALID');
186
- }
187
- context.packageJson.heybox = {
188
- ...(context.packageJson.heybox ?? {}),
189
- miniProgramId: normalizedMiniProgramId,
190
- };
191
- await fs.writeFile(context.packageJsonPath, `${JSON.stringify(context.packageJson, null, context.indent)}${context.trailingNewline || '\n'}`, 'utf8');
192
- return {
193
- ...context,
194
- changed: true,
195
- miniProgramId: normalizedMiniProgramId,
196
- };
197
- }
198
- function detectJsonIndent(raw) {
199
- const match = raw.match(/\n(\s+)"[^"]+":/);
200
- return match?.[1] ?? 2;
201
- }
202
- function isPlainObject(value) {
203
- return Object.prototype.toString.call(value) === '[object Object]';
204
- }
205
-
206
111
  function trustedProfileUrl(raw) {
207
112
  const url = new URL(raw);
208
113
  const trusted = ['max-c.com', 'xiaoheihe.cn', 'heybox.com'];
@@ -241,7 +146,7 @@ async function downloadImage(raw, fetchImpl) {
241
146
  }
242
147
  /** package-last 提交:失败只清理本次新增素材,原配置始终保留。 */
243
148
  async function migrateBasicInfo(cwd, detail, miniProgramId, fetchImpl = fetch, force = false) {
244
- const context = await readMiniProgramProjectPackage(cwd);
149
+ const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
245
150
  const heybox = context.packageJson.heybox ?? {};
246
151
  const existing = heybox.miniProgramId;
247
152
  if (existing && existing !== miniProgramId && !force)
@@ -317,7 +222,7 @@ async function migrateBasicInfo(cwd, detail, miniProgramId, fetchImpl = fetch, f
317
222
  }
318
223
  }
319
224
  async function compareBasicInfo(cwd, detail, fetchImpl = fetch) {
320
- const context = await readMiniProgramProjectPackage(cwd);
225
+ const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
321
226
  const published = detail.published_basic_info;
322
227
  let local;
323
228
  try {
@@ -604,7 +509,7 @@ function createDefaultCosClient(uploadToken, COS) {
604
509
  };
605
510
  }
606
511
  async function loadCosConstructor() {
607
- const cosModule = await Promise.resolve().then(function () { return require('./index-aGcX-ULf.cjs'); }).then(function (n) { return n.index; });
512
+ const cosModule = await Promise.resolve().then(function () { return require('./index-DPEhBPfc.cjs'); }).then(function (n) { return n.index; });
608
513
  return cosModule.default;
609
514
  }
610
515
  function formatSize(bytes) {
@@ -673,6 +578,9 @@ async function computeMiniappArtifactReceipt(files, runtime = {}) {
673
578
 
674
579
  function createRemoteApiClient(options) {
675
580
  return {
581
+ getPostBinding: (request) => remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_POST_BINDING_API_PATH, request, options),
582
+ previewPostBinding: (request) => remotePostForm(runtimePermissionEnv.USER_MINIPROGRAM_POST_PREVIEW_API_PATH, request, options),
583
+ setPostBinding: (request) => remotePostForm(`${runtimePermissionEnv.USER_MINIPROGRAM_POST_BINDING_API_PATH}/update`, request, options),
676
584
  listPermissionApplications: (request) => remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
677
585
  submitPermissionApplication: (request) => remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
678
586
  listDeveloperEntities: () => listDeveloperEntities(options),
@@ -743,7 +651,9 @@ async function precheckUserMiniprogramVersion(options, runtime) {
743
651
  }
744
652
  async function submitUserMiniprogramAudit(options, runtime) {
745
653
  return remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, {
746
- mini_program_id: options.mini_program_id, session_id: options.session_id, preflight_token: options.preflight_token,
654
+ mini_program_id: options.mini_program_id,
655
+ session_id: options.session_id,
656
+ preflight_token: options.preflight_token,
747
657
  }, runtime);
748
658
  }
749
659
  async function getVersionPreviewInfo(options, runtime) {
@@ -854,7 +764,7 @@ function createRemoteApiClientForEnvironment(environment) {
854
764
  }
855
765
  async function getBoundMiniProgram(options = {}, runtime = {}) {
856
766
  const cwd = options.cwd ?? process.cwd();
857
- const binding = await requireBoundMiniProgramId(cwd);
767
+ const binding = await gameBindingGuide.requireBoundMiniProgramId(cwd);
858
768
  const api = await resolveRemoteApiClient(options, runtime);
859
769
  const detail = await api.getUserMiniprogramDetail({ mini_program_id: binding.miniProgramId });
860
770
  return {
@@ -972,12 +882,12 @@ function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
972
882
  status: state.networkRequest.status,
973
883
  config: { useOfficialDomain },
974
884
  }
975
- : key === 'user_game_data'
885
+ : key === 'user_game_data' || key === 'post'
976
886
  ? {
977
887
  key,
978
888
  status: entry.status,
979
- // 精确资源清单是 snapshot 的合法必需项:浏览器模拟只调整开关,不能丢掉 Manifest 声明。
980
- config: { resources: entry.config.resources },
889
+ // 浏览器模拟不能丢掉资源清单或关联帖的读写声明。
890
+ config: { ...entry.config },
981
891
  }
982
892
  : {
983
893
  key,
@@ -1045,7 +955,7 @@ async function runDeployCommand(options, runtime = {}) {
1045
955
  const logger = runtime.logger ?? index.createCliLogger();
1046
956
  const cwd = runtime.cwd ?? process.cwd();
1047
957
  const projectRoot = index.findProjectRoot(cwd);
1048
- const packageJson = await readPackageJson(projectRoot);
958
+ let packageJson = await readPackageJson(projectRoot);
1049
959
  const miniProgramId = packageJson.heybox?.miniProgramId;
1050
960
  const autoPublish = options.autoPublish ?? true;
1051
961
  const env = options.env ?? process.env;
@@ -1060,13 +970,20 @@ async function runDeployCommand(options, runtime = {}) {
1060
970
  }
1061
971
  const declaredPlatforms = runtimePermissionEnv.readMiniappPlatformsFromPackageJson(projectRoot);
1062
972
  const declaredWindow = runtimePermissionEnv.readMiniappWindowFromPackageJson(projectRoot);
1063
- const declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
973
+ let declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
1064
974
  const declaredCategory = runtimePermissionEnv.readMiniappCategoryFromPackageJson(projectRoot);
1065
975
  const releaseNote = await resolveDeployReleaseNote(options, runtime);
1066
976
  const session = await logger.task('正在校验 Heybox 登录态', () => (runtime.requireAuthSession ?? index.requireHeyboxAuthSession)({ loginBaseUrl }), { successText: 'Heybox 登录态有效' });
1067
977
  logger.debug(`Heybox API: ${apiBaseUrl}`);
1068
978
  const uploadVersion = validateVersionForDeploy(packageJson.version, 'package.json.version');
1069
979
  const deploy = async () => {
980
+ if (!options.skipGameBindingGuide) {
981
+ await gameBindingGuide.guideGameBindings(gameBindingGuide.createGameBindingsBackend(projectRoot, { session, fetchImpl: runtime.fetchImpl }), {
982
+ isTTY: runtime.isTTY, stdin: runtime.stdin, stderr: runtime.stderr, question: runtime.gameBindingQuestion,
983
+ });
984
+ packageJson = await readPackageJson(projectRoot);
985
+ declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
986
+ }
1070
987
  let precheckVersion;
1071
988
  {
1072
989
  const configuredProfile = runtimePermissionEnv.parseMiniappBasicInfo(packageJson.heybox ?? {}, '0.8.1');
@@ -1527,6 +1444,11 @@ async function runRemoteCommand(options, runtime = {}) {
1527
1444
  }
1528
1445
  const context = await createRemoteCommandContext(options, runtime);
1529
1446
  switch (options.command) {
1447
+ case 'post:get':
1448
+ case 'post:preview':
1449
+ case 'post:bind':
1450
+ case 'post:unbind':
1451
+ return remotePostBinding(options, context, runtime);
1530
1452
  case 'permission:list':
1531
1453
  return remotePermissionList(options, context, runtime);
1532
1454
  case 'permission:apply':
@@ -1605,6 +1527,7 @@ async function runRemoteDeployCommand(options, runtime) {
1605
1527
  releaseNote: options.releaseNote,
1606
1528
  buildOutputMode: options.json ? 'stderr' : 'inherit',
1607
1529
  successOutputMode: 'remote',
1530
+ skipGameBindingGuide: Boolean(options.json),
1608
1531
  };
1609
1532
  const result = await (runtime.runDeployCommand ?? runDeployCommand)(deployOptions, deployRuntime);
1610
1533
  const output = result ?? { changed: true };
@@ -1623,8 +1546,8 @@ async function createRemoteCommandContext(options, runtime) {
1623
1546
  fetchImpl: runtime.fetchImpl,
1624
1547
  requireAuthSession: runtime.requireAuthSession,
1625
1548
  });
1626
- const packageJson = await readMiniProgramProjectPackage(runtime.cwd ?? process.cwd());
1627
- const binding = readBoundMiniProgramIdFromPackageJson(packageJson.packageJson);
1549
+ const packageJson = await gameBindingGuide.readMiniProgramProjectPackage(runtime.cwd ?? process.cwd());
1550
+ const binding = gameBindingGuide.readBoundMiniProgramIdFromPackageJson(packageJson.packageJson);
1628
1551
  const api = {
1629
1552
  ...adaptRemoteApiClient(createRemoteApiClientForEnvironment(environment)),
1630
1553
  ...runtime.api,
@@ -1642,6 +1565,13 @@ async function createRemoteCommandContext(options, runtime) {
1642
1565
  }
1643
1566
  function adaptRemoteApiClient(api) {
1644
1567
  return {
1568
+ getPostBinding: (miniProgramId) => api.getPostBinding({ mini_program_id: miniProgramId }),
1569
+ previewPostBinding: ({ miniProgramId, postId }) => api.previewPostBinding({ mini_program_id: miniProgramId, post_id: postId }),
1570
+ setPostBinding: ({ miniProgramId, postId, expectedRevision }) => api.setPostBinding({
1571
+ mini_program_id: miniProgramId,
1572
+ post_id: postId,
1573
+ expected_revision: expectedRevision,
1574
+ }),
1645
1575
  listPermissionApplications: (miniProgramId) => api.listPermissionApplications({ mini_program_id: miniProgramId }),
1646
1576
  submitPermissionApplication: ({ miniProgramId, key, reason, domains }) => api.submitPermissionApplication({ mini_program_id: miniProgramId, permission_key: key, reason, domains }),
1647
1577
  accessStatus: () => api.getDeveloperAccessStatus(),
@@ -1784,7 +1714,7 @@ async function remoteCreate(options, context, runtime) {
1784
1714
  runtimePermissionEnv.parseMiniappBasicInfo(context.packageJson.packageJson.heybox ?? {});
1785
1715
  const result = await context.api.createMiniProgram();
1786
1716
  const miniProgramId = requireMiniProgramId(result);
1787
- await writeBoundMiniProgramId(context.packageJson.projectRoot, miniProgramId, { force: options.forceBind });
1717
+ await gameBindingGuide.writeBoundMiniProgramId(context.packageJson.projectRoot, miniProgramId, { force: options.forceBind });
1788
1718
  const output = { changed: true, miniProgramId, remote: toCamelCaseDeep(result) };
1789
1719
  if (!options.json) {
1790
1720
  context.logger.success(`创建并绑定成功:${miniProgramId}`);
@@ -1808,6 +1738,39 @@ async function remoteBind(options, context, runtime) {
1808
1738
  }
1809
1739
  return finishRemoteCommand(options, runtime, output);
1810
1740
  }
1741
+ async function remotePostBinding(options, context, runtime) {
1742
+ const miniProgramId = requireBinding(context);
1743
+ if (options.command === 'post:get') {
1744
+ const result = await context.api.getPostBinding(miniProgramId);
1745
+ if (!options.json)
1746
+ context.logger.info(`关联帖子:${result.post_id || '未绑定'}`);
1747
+ return finishRemoteCommand(options, runtime, {
1748
+ changed: false,
1749
+ miniProgramId,
1750
+ binding: { postId: result.post_id },
1751
+ });
1752
+ }
1753
+ const postId = options.command === 'post:unbind' ? '' : requireNonEmpty(options.postId, '必须传入帖子 ID');
1754
+ if (postId && (!/^[1-9]\d{0,18}$/.test(postId) || BigInt(postId) > 9223372036854775807n)) {
1755
+ throw new Error('帖子 ID 必须为有效的正整数');
1756
+ }
1757
+ if (options.command === 'post:preview') {
1758
+ const result = await context.api.previewPostBinding({ miniProgramId, postId });
1759
+ if (!options.json)
1760
+ context.logger.info(`${result.title || '无标题帖子'}(${result.post_id}),作者:${result.author_name}`);
1761
+ return finishRemoteCommand(options, runtime, { changed: false, miniProgramId, post: toCamelCaseDeep(result) });
1762
+ }
1763
+ await assertBoundMiniProgramEntityMatchesCurrent(context, miniProgramId);
1764
+ const binding = await context.api.getPostBinding(miniProgramId);
1765
+ const expectedRevision = binding.revision;
1766
+ if (typeof expectedRevision !== 'string' || !/^(0|[1-9]\d{0,18})$/.test(expectedRevision) || BigInt(expectedRevision) >= 9223372036854775807n) {
1767
+ throw new Error('当前关联信息无效,请稍后重试');
1768
+ }
1769
+ const result = await context.api.setPostBinding({ miniProgramId, postId, expectedRevision });
1770
+ if (!options.json)
1771
+ context.logger.success(postId ? `已关联帖子:${postId}` : '已解除关联');
1772
+ return finishRemoteCommand(options, runtime, { changed: true, miniProgramId, binding: { postId: result.post_id } });
1773
+ }
1811
1774
  /** 工作台扫码只读取版本和协议,复用认证与项目绑定,避免图片比对和详情输出。 */
1812
1775
  async function readRemoteMiniProgramPreview(options, runtime = {}) {
1813
1776
  const context = await createRemoteCommandContext({ env: options.env }, runtime);
@@ -1838,7 +1801,20 @@ async function remoteInfo(options, context, runtime) {
1838
1801
  const removed = currentBindApps.filter((item) => !localIDs.has(item.appid));
1839
1802
  const bindings = { local, current: currentBindApps, added, removed };
1840
1803
  const basicInfo = await compareBasicInfo(context.packageJson.projectRoot, detail, runtime.fetchImpl);
1841
- const output = { changed: false, miniProgramId, detail: toCamelCaseDeep(detail), permissions: permissionViews, permissionSources: { localDeclaration: localPermissions.permissions ?? null, onlineManifest: detail.manifest ?? null, onlineRuntimeSnapshot: detail.effective_runtime_permissions ?? null, platformApprovals: detail.runtime_permissions ?? null }, bindings, basicInfo };
1804
+ const output = {
1805
+ changed: false,
1806
+ miniProgramId,
1807
+ detail: toCamelCaseDeep(detail),
1808
+ permissions: permissionViews,
1809
+ permissionSources: {
1810
+ localDeclaration: localPermissions.permissions ?? null,
1811
+ onlineManifest: detail.manifest ?? null,
1812
+ onlineRuntimeSnapshot: detail.effective_runtime_permissions ?? null,
1813
+ platformApprovals: detail.runtime_permissions ?? null,
1814
+ },
1815
+ bindings,
1816
+ basicInfo,
1817
+ };
1842
1818
  if (!options.json)
1843
1819
  context.logger.info(`版本资料:${basicInfo.status}`);
1844
1820
  if (!options.json) {
@@ -1885,11 +1861,11 @@ async function remotePermissionList(options, context, runtime) {
1885
1861
  const localPermissions = runtimePermissionEnv.readMiniappPermissionsFromPackageJson(context.packageJson.projectRoot, runtimePermissionEnv.resolveMiniappSdkVersion());
1886
1862
  const { views } = runtimePermissionEnv.composeMiniappRuntimePermissions(localPermissions, result.runtime_permissions, detail.party_type);
1887
1863
  if (!options.json) {
1888
- for (const view of views.filter(entry => entry.access === 'platform-approval')) {
1889
- const item = result.items.find(entry => entry.permission_key === view.key);
1864
+ for (const view of views.filter((entry) => entry.access === 'platform-approval')) {
1865
+ const item = result.items.find((entry) => entry.permission_key === view.key);
1890
1866
  const application = item?.latest_application;
1891
- const name = item?.permission_name ?? index_esm.MINI_PROGRAM_PERMISSION_CATALOG.find(entry => entry.key === view.key)?.name ?? view.key;
1892
- const approval = result.runtime_permissions?.entries?.find(entry => entry.key === view.key);
1867
+ const name = item?.permission_name ?? index_esm.MINI_PROGRAM_PERMISSION_CATALOG.find((entry) => entry.key === view.key)?.name ?? view.key;
1868
+ const approval = result.runtime_permissions?.entries?.find((entry) => entry.key === view.key);
1893
1869
  const source = view.approvalSource === 'first-party' ? ' 批准来源=第一方自动批准' : '';
1894
1870
  context.logger.info(`${view.key} (${name}) 原始审批=${approval?.status ?? 'disabled'}${source} 本地生效=${view.effective ? 'enabled' : 'disabled'} 最近申请=${application?.status ?? '未申请'}`);
1895
1871
  if (application?.application_id)
@@ -1898,7 +1874,13 @@ async function remotePermissionList(options, context, runtime) {
1898
1874
  context.logger.info(`审核意见:${application.review_remark}`);
1899
1875
  }
1900
1876
  }
1901
- return finishRemoteCommand(options, runtime, { changed: false, miniProgramId, items: toCamelCaseDeep(result.items), runtimePermissions: toCamelCaseDeep(result.runtime_permissions), permissions: views });
1877
+ return finishRemoteCommand(options, runtime, {
1878
+ changed: false,
1879
+ miniProgramId,
1880
+ items: toCamelCaseDeep(result.items),
1881
+ runtimePermissions: toCamelCaseDeep(result.runtime_permissions),
1882
+ permissions: views,
1883
+ });
1902
1884
  }
1903
1885
  async function remotePermissionApply(options, context, runtime) {
1904
1886
  const miniProgramId = requireBinding(context);
@@ -1914,10 +1896,15 @@ async function remotePermissionApply(options, context, runtime) {
1914
1896
  throw new Error('申请理由不能超过 500 字');
1915
1897
  let domains;
1916
1898
  if (key === 'network') {
1917
- const values = [...new Set(requireNonEmpty(options.domains, 'network 申请必须传 --domains,多个域名用逗号分隔').split(',').map(value => value.trim()).filter(Boolean))];
1899
+ const values = [
1900
+ ...new Set(requireNonEmpty(options.domains, 'network 申请必须传 --domains,多个域名用逗号分隔')
1901
+ .split(',')
1902
+ .map((value) => value.trim())
1903
+ .filter(Boolean)),
1904
+ ];
1918
1905
  if (!values.length || values.length > 20)
1919
1906
  throw new Error('请填写 1 至 20 个访问域名');
1920
- if (values.some(value => /[\s/:?#@*\\]/.test(value)))
1907
+ if (values.some((value) => /[\s/:?#@*\\]/.test(value)))
1921
1908
  throw new Error('请填写域名,不含协议、端口、路径或通配符');
1922
1909
  domains = values.join(',');
1923
1910
  }
@@ -2383,9 +2370,7 @@ async function confirmDangerousRemoteChange(options, runtime, logger, context) {
2383
2370
  throw new Error(`非交互环境执行 hb-sdk remote ${context.operation} 必须传 --yes`);
2384
2371
  }
2385
2372
  const confirmation = `${context.permissionWarning ? `${context.permissionWarning}\n` : ''}确认执行 ${context.operation}?`;
2386
- const accepted = runtime.promptConfirm
2387
- ? await runtime.promptConfirm(confirmation)
2388
- : await promptConfirm(`${confirmation}输入 yes 继续: `, runtime);
2373
+ const accepted = runtime.promptConfirm ? await runtime.promptConfirm(confirmation) : await promptConfirm(`${confirmation}输入 yes 继续: `, runtime);
2389
2374
  if (!accepted) {
2390
2375
  throw new Error('已取消操作');
2391
2376
  }
@@ -2417,19 +2402,35 @@ function printMiniProgramDetail(logger, detail, permissionViews, bindings) {
2417
2402
  const manifest = detail.manifest && typeof detail.manifest === 'object' ? detail.manifest : undefined;
2418
2403
  let online;
2419
2404
  try {
2420
- online = manifest ? runtimePermissionEnv.parseMiniappPermissions(manifest.permissions, { present: Object.hasOwn(manifest, 'permissions'), sdkVersion: typeof detail.sdk_version === 'string' ? detail.sdk_version : '0.8.0' }) : undefined;
2405
+ online = manifest
2406
+ ? runtimePermissionEnv.parseMiniappPermissions(manifest.permissions, {
2407
+ present: Object.hasOwn(manifest, 'permissions'),
2408
+ sdkVersion: typeof detail.sdk_version === 'string' ? detail.sdk_version : '0.8.0',
2409
+ })
2410
+ : undefined;
2411
+ }
2412
+ catch {
2413
+ /* 缺失或未知声明保持未知,不能推断线上可用。 */
2421
2414
  }
2422
- catch { /* 缺失或未知声明保持未知,不能推断线上可用。 */ }
2423
2415
  const publishedRuntime = index_esm.parseMiniProgramRuntimePermissions(detail.effective_runtime_permissions);
2424
2416
  let differs = false;
2425
2417
  for (const view of permissionViews) {
2426
2418
  const published = online ? online.permissions?.[view.key]?.enabled === true : undefined;
2427
2419
  const requested = online?.permissions?.[view.key];
2428
- const changed = published !== undefined && (published !== view.declared ||
2429
- (view.key === 'network' && published && view.requestedConfig?.useOfficialDomain !== (requested && 'useOfficialDomain' in requested ? requested.useOfficialDomain : undefined)));
2420
+ const changed = published !== undefined &&
2421
+ (published !== view.declared ||
2422
+ (view.key === 'network' &&
2423
+ published &&
2424
+ view.requestedConfig?.useOfficialDomain !== (requested && 'useOfficialDomain' in requested ? requested.useOfficialDomain : undefined)));
2430
2425
  differs ||= changed;
2431
- const approval = view.access === 'platform-approval' ? (view.approvalSource === 'first-party' ? '第一方自动批准' : view.approved ? '已批准' : '未批准') : '无需审批';
2432
- logger.info(` ${view.key}: 本地声明=${view.declared ? '是' : '否'} 线上版本声明=${published === undefined ? '未知' : published ? '是' : '否'} 平台批准=${approval} 线上快照=${publishedRuntime.valid ? publishedRuntime.permissions[view.key]?.status ?? '缺少条目' : '未知'}${changed ? ' [不一致]' : ''}`);
2426
+ const approval = view.access === 'platform-approval'
2427
+ ? view.approvalSource === 'first-party'
2428
+ ? '第一方自动批准'
2429
+ : view.approved
2430
+ ? '已批准'
2431
+ : '未批准'
2432
+ : '无需审批';
2433
+ logger.info(` ${view.key}: 本地声明=${view.declared ? '是' : '否'} 线上版本声明=${published === undefined ? '未知' : published ? '是' : '否'} 平台批准=${approval} 线上快照=${publishedRuntime.valid ? (publishedRuntime.permissions[view.key]?.status ?? '缺少条目') : '未知'}${changed ? ' [不一致]' : ''}`);
2433
2434
  }
2434
2435
  if (differs)
2435
2436
  logger.warn('本地声明与线上版本不一致;本地调试结果不代表线上生效,需发布包含声明的新版本。');
@@ -2528,14 +2529,11 @@ var remote = /*#__PURE__*/Object.freeze({
2528
2529
  runRemoteCommand: runRemoteCommand
2529
2530
  });
2530
2531
 
2531
- exports.MiniProgramProjectBindingError = MiniProgramProjectBindingError;
2532
2532
  exports.createBrowserDevPermissionState = createBrowserDevPermissionState;
2533
2533
  exports.createLocalDevLaunchToken = createLocalDevLaunchToken;
2534
2534
  exports.createMobileDevSessionRuntimePermissions = createMobileDevSessionRuntimePermissions;
2535
2535
  exports.getBoundMiniProgram = getBoundMiniProgram;
2536
2536
  exports.migrateBasicInfo = migrateBasicInfo;
2537
- exports.readBoundMiniProgramId = readBoundMiniProgramId;
2538
- exports.readBoundMiniProgramIdFromPackageJson = readBoundMiniProgramIdFromPackageJson;
2539
2537
  exports.readRemoteMiniProgramPreview = readRemoteMiniProgramPreview;
2540
2538
  exports.remote = remote;
2541
2539
  exports.resolveBrowserFakeContext = resolveBrowserFakeContext;
@@ -2,10 +2,11 @@
2
2
 
3
3
  var fs = require('node:fs');
4
4
  var path = require('node:path');
5
- var version = require('./version-D4jIw125.cjs');
5
+ var version = require('./version-CAh_EBAH.cjs');
6
+ var bindings = require('./bindings-B9HSKhmy.cjs');
6
7
  var fs$1 = require('node:fs/promises');
7
- var index_esm = require('./index.esm-CvMA_ppV.cjs');
8
- var index = require('./index-Cr8tP0XZ.cjs');
8
+ var index_esm = require('./index.esm-CenYK5Bl.cjs');
9
+ var index = require('./index-D5rcGk_z.cjs');
9
10
  var node_crypto = require('node:crypto');
10
11
  require('node:zlib');
11
12
  require('node:module');
@@ -80,87 +81,6 @@ function parseMiniappBasicInfo(value, sdkVersion = '0.8.2') {
80
81
  return { name, icon, coverImages };
81
82
  }
82
83
 
83
- /** 单个小程序版本最多声明的关联游戏数量。 */
84
- const MINIAPP_BIND_APP_IDS_MAX_COUNT = 20;
85
- /**
86
- * 校验并规范化小程序关联的游戏 App ID。
87
- *
88
- * @param value - 不可信声明。`undefined` 和 `[]` 均返回空绑定;其他值必须是最多 20 项的
89
- * 字符串数组,不接受 `null`、单个字符串、number 数组或类数组对象。
90
- * @param options - 可选诊断来源;`sourceLabel` 默认 `package.json#heybox.bindAppIds`,并原样
91
- * 作为所有错误消息的前缀。
92
- * @returns 新建、按 appid 数值升序排列且经 `Object.freeze` 冻结的 `readonly string[]`。
93
- * 输入数组及其顺序不会被修改;空输入也返回新的冻结空数组。
94
- * @throws `Error` `${sourceLabel} 必须是字符串数组`:`value` 不是数组。
95
- * @throws `Error` `${sourceLabel} 最多包含 20 个游戏 appid`:输入数组超过 20 项;数量检查
96
- * 先于逐项格式检查。
97
- * @throws `Error` `${sourceLabel} 包含非法游戏 appid:<value>`:任一项不是 string,或不匹配
98
- * `/^[1-9]\d*$/`。因此空串、首尾空白、`0`、前导零、正负号、小数、指数和非十进制字符
99
- * 都不会被自动修正。
100
- * @throws `Error` `${sourceLabel} 包含超出正 int32 范围的游戏 appid:<value>`:十进制值
101
- * 大于 `2147483647` 或不能成为安全整数。
102
- * @throws `Error` `${sourceLabel} 包含重复游戏 appid:<value>`:规范字符串在同一数组重复。
103
- *
104
- * @remarks
105
- * 合法范围是闭区间 `1..2147483647`,每项在输出中仍保持十进制 string。排序按数值而不是
106
- * 字典序执行,所以 `['3513350', '730', '10']` 输出为 `['10', '730', '3513350']`。
107
- * 函数先复制后排序并冻结结果,不排序或冻结调用方传入的数组。
108
- *
109
- * 这是同步、纯离线的格式规范化函数,不访问网络,也不确认 appid 是否真实存在、可绑定或
110
- * 属于当前开发者。`miniappManifest()` 用它校验 `package.json#heybox.bindAppIds` 并把非空结果
111
- * 写入 Manifest;远端 deploy 预检和提审才校验游戏可用性。缺失和空数组在普通构建中都表示
112
- * 无绑定,函数本身不处理 `remote deploy --from-version` 的历史快照继承语义。
113
- *
114
- * `bindAppIds` 是版本发布元数据,不是 Runtime 权限,也不会因调用
115
- * [navigation.openAppPage](/reference/sdk/navigation/openAppPage) 而变化。后者的 `appId` 是一次
116
- * 页面导航参数,允许 string 或 number、只要求字符串化后非空,不适用本函数的数组、int32、
117
- * 前导零、去重、20 项或排序规则。
118
- *
119
- * @example
120
- * ```ts
121
- * import { parseMiniappBindAppIds } from '@heybox/hb-sdk/miniapp-publish'
122
- *
123
- * const declared = ['3513350', '730', '10']
124
- * const appIds = parseMiniappBindAppIds(declared)
125
- *
126
- * console.log(appIds) // ['10', '730', '3513350']
127
- * console.log(declared) // ['3513350', '730', '10'],输入顺序不变
128
- * console.log(Object.isFrozen(appIds)) // true
129
- * ```
130
- *
131
- * @see [miniappManifest](/reference/symbols/vite/functions/miniappManifest)
132
- * @see [navigation.openAppPage](/reference/sdk/navigation/openAppPage)
133
- * @see [CLI 与远端发布](/guide/cli#生产构建)
134
- * @since 0.8.1
135
- */
136
- function parseMiniappBindAppIds(value, options = {}) {
137
- const sourceLabel = options.sourceLabel ?? 'package.json#heybox.bindAppIds';
138
- if (value === undefined)
139
- return Object.freeze([]);
140
- if (!Array.isArray(value))
141
- throw new Error(`${sourceLabel} 必须是字符串数组`);
142
- if (value.length > MINIAPP_BIND_APP_IDS_MAX_COUNT) {
143
- throw new Error(`${sourceLabel} 最多包含 ${MINIAPP_BIND_APP_IDS_MAX_COUNT} 个游戏 appid`);
144
- }
145
- const seen = new Set();
146
- const appIds = [];
147
- for (const item of value) {
148
- if (typeof item !== 'string' || !/^[1-9]\d*$/.test(item)) {
149
- throw new Error(`${sourceLabel} 包含非法游戏 appid:${String(item)}`);
150
- }
151
- const numeric = Number(item);
152
- if (!Number.isSafeInteger(numeric) || numeric > 2_147_483_647) {
153
- throw new Error(`${sourceLabel} 包含超出正 int32 范围的游戏 appid:${item}`);
154
- }
155
- if (seen.has(item))
156
- throw new Error(`${sourceLabel} 包含重复游戏 appid:${item}`);
157
- seen.add(item);
158
- appIds.push(item);
159
- }
160
- appIds.sort((left, right) => Number(left) - Number(right));
161
- return Object.freeze(appIds);
162
- }
163
-
164
84
  /**
165
85
  * 校验项目配置或产物中的小程序类别。
166
86
  *
@@ -245,6 +165,16 @@ function parseMiniappPermissions(value, options) {
245
165
  }
246
166
  useOfficialDomain = declaration.useOfficialDomain === true;
247
167
  }
168
+ if (key === 'post') {
169
+ for (const field of ['read', 'write']) {
170
+ if (declaration[field] !== undefined && typeof declaration[field] !== 'boolean') {
171
+ throw new Error(`${itemLabel}.${field} 必须是 boolean`);
172
+ }
173
+ }
174
+ if (declaration.enabled)
175
+ permissions.post = { enabled: true, read: declaration.read === true, write: declaration.write === true };
176
+ continue;
177
+ }
248
178
  if (key === 'user_game_data') {
249
179
  // 即使声明关闭也校验资源清单:enabled:false 不能隐藏非法字段。
250
180
  const resources = parseUserGameDataResources(declaration.resources, itemLabel);
@@ -298,7 +228,11 @@ partyType) {
298
228
  entries.push({
299
229
  key: definition.key,
300
230
  status: 'enabled',
301
- config: definition.key === 'user_game_data' ? { resources: normalizeUserGameDataResources(local.permissions?.user_game_data) } : {},
231
+ config: definition.key === 'user_game_data'
232
+ ? { resources: normalizeUserGameDataResources(local.permissions?.user_game_data) }
233
+ : definition.key === 'post'
234
+ ? { read: local.permissions?.post?.read === true, write: local.permissions?.post?.write === true }
235
+ : {},
302
236
  });
303
237
  }
304
238
  continue;
@@ -480,7 +414,7 @@ function validateMiniappManifestForDeploy(manifest) {
480
414
  if (category === undefined) {
481
415
  throw new Error('manifest.category 缺失,请在 package.json#heybox.category 声明 tool、game 或 other 后重新构建');
482
416
  }
483
- const bindAppIds = parseMiniappBindAppIds(manifest.bindAppIds, { sourceLabel: 'manifest.bindAppIds' });
417
+ const bindAppIds = bindings.parseMiniappBindAppIds(manifest.bindAppIds, { sourceLabel: 'manifest.bindAppIds' });
484
418
  const desc = parseMiniappDesc(manifest.desc, 'manifest.desc');
485
419
  return {
486
420
  version,
@@ -731,7 +665,7 @@ function readMiniappPermissionsFromPackageJson(root, sdkVersion) {
731
665
  function readMiniappBindAppIdsFromPackageJson(root) {
732
666
  const { packageJson } = readMiniappPackageJson(root);
733
667
  const heybox = readMiniappHeyboxConfig(packageJson);
734
- return parseMiniappBindAppIds(heybox?.bindAppIds);
668
+ return bindings.parseMiniappBindAppIds(heybox?.bindAppIds);
735
669
  }
736
670
  function readMiniappCategoryFromPackageJson(root) {
737
671
  const { packageJson } = readMiniappPackageJson(root);
@@ -210976,6 +210910,10 @@ const LIST_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/list';
210976
210910
  const CREATE_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/create';
210977
210911
  /** 查询单个小程序详情的开放平台 API 路径。 */
210978
210912
  const DETAIL_USER_MINIPROGRAM_API_PATH = '/mall/developer/user_miniprogram/detail';
210913
+ /** 查询和更新小程序关联帖子的开放平台 API 路径。 */
210914
+ const USER_MINIPROGRAM_POST_BINDING_API_PATH = '/mall/developer/user_miniprogram/post/binding';
210915
+ /** 校验并预览待关联的帖子。 */
210916
+ const USER_MINIPROGRAM_POST_PREVIEW_API_PATH = '/mall/developer/user_miniprogram/post/preview';
210979
210917
  /** 创建本地开发启动凭据的开放平台 API 路径。 */
210980
210918
  const CREATE_USER_MINIPROGRAM_LOCAL_DEV_LAUNCH_TOKEN_API_PATH = '/mall/developer/user_miniprogram/local_dev_launch_token';
210981
210919
  /** 查询小程序预览白名单的开放平台 API 路径。 */
@@ -211853,6 +211791,8 @@ exports.TAKE_DOWN_USER_MINIPROGRAM_API_PATH = TAKE_DOWN_USER_MINIPROGRAM_API_PAT
211853
211791
  exports.UPDATE_SQUARE_DISPLAY_API_PATH = UPDATE_SQUARE_DISPLAY_API_PATH;
211854
211792
  exports.UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH;
211855
211793
  exports.USER_MINIPROGRAM_ACCESS_STATUS_API_PATH = USER_MINIPROGRAM_ACCESS_STATUS_API_PATH;
211794
+ exports.USER_MINIPROGRAM_POST_BINDING_API_PATH = USER_MINIPROGRAM_POST_BINDING_API_PATH;
211795
+ exports.USER_MINIPROGRAM_POST_PREVIEW_API_PATH = USER_MINIPROGRAM_POST_PREVIEW_API_PATH;
211856
211796
  exports.USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH;
211857
211797
  exports.USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH = USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH;
211858
211798
  exports.WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH = WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH;
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var version = require('./version-D4jIw125.cjs');
3
+ var version = require('./version-CAh_EBAH.cjs');
4
4
  var fs = require('node:fs/promises');
5
5
  var path = require('node:path');
6
6
  var childProcess = require('node:child_process');
7
- var index = require('./index-Cr8tP0XZ.cjs');
7
+ var index = require('./index-D5rcGk_z.cjs');
8
8
  require('node:module');
9
9
  require('readline');
10
10
  require('os');
@@ -3,6 +3,6 @@
3
3
  /** 构建时替换为当前发布包的实际版本。 */
4
4
  const HB_SDK_VERSION = typeof undefined === 'string'
5
5
  ? undefined
6
- : '0.9.8';
6
+ : '0.9.9-alpha.1';
7
7
 
8
8
  exports.HB_SDK_VERSION = HB_SDK_VERSION;