@heybox/hb-sdk 0.9.9-alpha.0 → 0.9.9-alpha.11

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 (43) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -0
  3. package/dist/cli-chunks/{build-Vi5Zyplz.cjs → build-D_2l0CIV.cjs} +5 -5
  4. package/dist/cli-chunks/{create-Cfz1IcYf.cjs → create-0QH1Tn92.cjs} +2 -2
  5. package/dist/cli-chunks/{dev-C2dtgF42.cjs → dev-CS5VPiB1.cjs} +912 -703
  6. package/dist/cli-chunks/{doctor-D-zMCLIA.cjs → doctor-B33mYzm-.cjs} +1 -1
  7. package/dist/cli-chunks/{game-binding-guide-z3X6h8ck.cjs → game-binding-guide-DMDuw1Pj.cjs} +3 -3
  8. package/dist/cli-chunks/{game-bindings-DiVP8PdD.cjs → game-bindings-CQWdvXfM.cjs} +4 -4
  9. package/dist/cli-chunks/{games-THhcga6y.cjs → games-deIaD0qu.cjs} +1 -1
  10. package/dist/cli-chunks/{index-BuYCoach.cjs → index-C91c2NGN.cjs} +1 -1
  11. package/dist/cli-chunks/{index-H9U6-mLY.cjs → index-DpfxAeSH.cjs} +78 -25
  12. package/dist/cli-chunks/{index.esm-XiyiK7eH.cjs → index.esm-B2WXn2A4.cjs} +10 -10
  13. package/dist/cli-chunks/{index.esm-D8lqHXUQ.cjs → index.esm-CenYK5Bl.cjs} +72 -3
  14. package/dist/cli-chunks/{login-Bw_1UJ8i.cjs → login-D7XGHQFo.cjs} +1 -1
  15. package/dist/cli-chunks/{project-vite-CFfq-fV7.cjs → project-vite-B7sylnO7.cjs} +1 -1
  16. package/dist/cli-chunks/{remote-CU88U8t8.cjs → remote-Crnu4l7X.cjs} +952 -742
  17. package/dist/cli-chunks/{runtime-permission-env-BtxzR-dv.cjs → runtime-permission-env-Cj9STUWz.cjs} +25 -4
  18. package/dist/cli-chunks/{skill-7RZJxGDO.cjs → skill-BDswKf84.cjs} +2 -2
  19. package/dist/cli-chunks/{version-COTSItDf.cjs → version-Dl0HQVTu.cjs} +1 -1
  20. package/dist/cli.cjs +1 -1
  21. package/dist/devtools/browser-dev-host/assets/browser-dev-host-Be8jnz2C.js +224 -0
  22. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-z3rWAJJc.js +6 -0
  23. package/dist/devtools/browser-dev-host/assets/index-CvUCSIVI.js +574 -0
  24. package/dist/devtools/browser-dev-host/assets/index-DQgWBZbX.css +1 -0
  25. package/dist/devtools/browser-dev-host/index.html +3 -3
  26. package/dist/index.cjs.js +149 -4
  27. package/dist/index.esm.js +149 -5
  28. package/dist/miniapp-publish.cjs.js +64 -1
  29. package/dist/miniapp-publish.esm.js +63 -2
  30. package/dist/protocol.cjs.js +51 -5
  31. package/dist/protocol.esm.js +51 -5
  32. package/dist/vite.cjs.js +74 -9
  33. package/dist/vite.esm.js +74 -9
  34. package/package.json +5 -5
  35. package/skill/SKILL.md +7 -0
  36. package/skill/skill.json +5 -5
  37. package/types/index.d.ts +140 -4
  38. package/types/miniapp-publish/index.d.ts +14 -3
  39. package/types/vite/index.d.ts +2 -0
  40. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CHdD15qt.js +0 -221
  41. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-az2quV7I.js +0 -13
  42. package/dist/devtools/browser-dev-host/assets/index-D0XGMYIr.css +0 -1
  43. package/dist/devtools/browser-dev-host/assets/index-o5r5oqtq.js +0 -567
@@ -1,15 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var index_esm = require('./index.esm-D8lqHXUQ.cjs');
4
- var runtimePermissionEnv = require('./runtime-permission-env-BtxzR-dv.cjs');
3
+ var index_esm = require('./index.esm-CenYK5Bl.cjs');
4
+ var runtimePermissionEnv = require('./runtime-permission-env-Cj9STUWz.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-z3X6h8ck.cjs');
10
+ var gameBindingGuide = require('./game-binding-guide-DMDuw1Pj.cjs');
11
11
  var promises = require('node:readline/promises');
12
- var index = require('./index-H9U6-mLY.cjs');
12
+ var index = require('./index-DpfxAeSH.cjs');
13
13
  var childProcess = require('node:child_process');
14
14
  require('node:zlib');
15
15
 
@@ -37,587 +37,310 @@ function getMiniappMetadataWarnings(metadata) {
37
37
  return warnings;
38
38
  }
39
39
 
40
- async function inspectBasicInfoImage(bytes, sourcePath, kind) {
41
- const inspected = await inspectDecodedBasicInfoImage(bytes, kind);
42
- const extensions = { jpg: ['jpg', 'jpeg'], png: ['png'], gif: ['gif'], webp: ['webp'] };
43
- const ext = sourcePath.split('.').pop().toLowerCase();
44
- if (!extensions[inspected.extension]?.includes(ext))
45
- throw new Error('资料图片格式与扩展名不一致');
46
- return inspected;
40
+ /** Browser Fake 与 channel 共用的本地 grant 有效性校验。 */
41
+ function resolveBrowserFakeContext(context, now = Date.now()) {
42
+ if (context.localDevGrant === undefined)
43
+ return context;
44
+ const parsed = index_esm.parseMiniProgramLocalDevGrant(context.localDevGrant);
45
+ if (!parsed.valid ||
46
+ !context.devSessionId?.trim() ||
47
+ !Number.isSafeInteger(context.contextRevision) ||
48
+ context.contextRevision !== parsed.grant.revision ||
49
+ !context.expiresAt ||
50
+ !Number.isFinite(context.expiresAt) ||
51
+ (context.source !== 'remote' && context.expiresAt <= now)) {
52
+ return { ...context, localDevGrant: undefined, warning: '本地临时授权无效或已过期,已降权' };
53
+ }
54
+ return {
55
+ ...context,
56
+ ...(context.expiresAt <= now ? { source: 'anonymous', localDevLaunchToken: undefined, expiresAt: now + 30_000 } : {}),
57
+ localDevGrant: index_esm.createMiniProgramLocalDevGrant({
58
+ declaredPermissions: context.declaredPermissions ?? {},
59
+ runtimePermissions: context.runtimePermissions,
60
+ revision: parsed.grant.revision,
61
+ eligiblePermissionKeys: context.platforms?.some((platform) => ['windows', 'macos', 'linux'].includes(platform))
62
+ ? ['network', 'companion', 'appProtocol']
63
+ : ['network', 'appProtocol'],
64
+ }),
65
+ };
47
66
  }
48
- async function inspectRemoteBasicInfoImage(bytes, kind) {
49
- return inspectDecodedBasicInfoImage(bytes, kind);
67
+ function shouldSkipMiniappPlatformCsp(_runtimePermissions) {
68
+ return false;
50
69
  }
51
- async function inspectDecodedBasicInfoImage(bytes, kind) {
52
- if (!bytes.length || bytes.length > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
53
- throw new Error('资料图片不得为空或超过 10 MiB');
54
- const decoder = sharp(bytes, { limitInputPixels: runtimePermissionEnv.BASIC_INFO_MAX_PIXELS, failOn: 'warning' });
55
- const metadata = await decoder.metadata();
56
- const extensions = { jpeg: 'jpg', png: 'png', gif: 'gif', webp: 'webp' };
57
- if (!metadata.format || !extensions[metadata.format])
58
- throw new Error('资料图片格式不支持');
59
- const width = metadata.width ?? 0;
60
- const height = metadata.pageHeight ?? metadata.height ?? 0;
61
- if (!width || !height || width * height > runtimePermissionEnv.BASIC_INFO_MAX_PIXELS)
62
- throw new Error('资料图片不得超过 4000 万像素');
63
- if (kind === 'icon' && (width !== 200 || height !== 200))
64
- throw new Error('icon 必须是 200×200');
65
- // 强制解码而非只信任图片头;不将解码结果写回图片。
66
- await decoder.stats();
67
- return { sha256: node_crypto.createHash('sha256').update(bytes).digest('hex'), extension: extensions[metadata.format] };
70
+ const DEFAULT_PERMISSION_STATE = {
71
+ networkRequest: {
72
+ status: 'disabled',
73
+ useOfficialDomain: false,
74
+ },
75
+ };
76
+ function createBrowserDevPermissionState(context) {
77
+ const parsed = index_esm.parseMiniProgramRuntimePermissions(context.localDevGrant
78
+ ? index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
79
+ localDevGrant: context.localDevGrant }).runtimePermissions
80
+ : context.runtimePermissions);
81
+ const networkRequest = parsed.permissions.network;
82
+ return parsed.valid && networkRequest
83
+ ? {
84
+ networkRequest: {
85
+ status: networkRequest.status,
86
+ useOfficialDomain: networkRequest.config.useOfficialDomain === true,
87
+ },
88
+ }
89
+ : cloneDefaultPermissionState();
68
90
  }
69
- async function readBasicInfoSource(projectRoot, relative, kind) {
70
- runtimePermissionEnv.validateBasicInfoPath(relative);
71
- const root = await fs.realpath(projectRoot);
72
- const target = await fs.realpath(path.join(root, relative));
73
- const resolvedRelative = path.relative(root, target).split(path.sep).join('/');
74
- runtimePermissionEnv.validateBasicInfoPath(resolvedRelative);
75
- if (resolvedRelative.startsWith('../') || path.isAbsolute(resolvedRelative))
76
- throw new Error('资料图片不能逃逸项目目录');
77
- const info = await fs.stat(target);
78
- if (!info.isFile() || info.size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
79
- throw new Error('资料图片必须为不超过 10 MiB 的普通文件');
80
- const file = await fs.open(target, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW);
81
- try {
82
- const actual = await file.stat();
83
- if (!actual.isFile() || actual.size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
84
- throw new Error('资料图片文件已变化');
85
- const bytes = await file.readFile();
86
- return { bytes, ...(await inspectBasicInfoImage(bytes, relative, kind)) };
91
+ /** Mobile Dev Session 使用本地声明与平台基线,不读取 Browser 模拟权限状态。 */
92
+ function createMobileDevSessionRuntimePermissions(context) {
93
+ if (context.source !== 'remote') {
94
+ return { schema_version: 1, entries: [] };
87
95
  }
88
- finally {
89
- await file.close();
96
+ // 历史内部调用没有本地声明,沿用旧快照适配;新 CLI 始终显式提供声明(可为空)。
97
+ if (context.declaredPermissions === undefined) {
98
+ const state = createBrowserDevPermissionState(context);
99
+ return createDevRuntimePermissions(context.runtimePermissions, state, state.networkRequest.useOfficialDomain);
90
100
  }
101
+ return index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions, runtimePermissions: context.runtimePermissions }).runtimePermissions;
91
102
  }
92
- /** 逐级校验真实目录,避免保留目录或迁移目录中的符号链接将写入带到项目外。 */
93
- async function ensureBasicInfoDirectory(rootPath, relative) {
94
- const root = await fs.realpath(rootPath);
95
- let current = root;
96
- for (const part of relative.split('/')) {
97
- if (!part || part === '.' || part === '..')
98
- throw new Error('资料目录不合法');
99
- current = path.join(current, part);
100
- await fs.mkdir(current).catch((error) => {
101
- if (error.code !== 'EEXIST')
102
- throw error;
103
- });
104
- const resolved = await fs.realpath(current);
105
- const within = path.relative(root, resolved);
106
- if (within.startsWith('..') || path.isAbsolute(within))
107
- throw new Error('资料目录不能逃逸项目');
103
+ function cloneDefaultPermissionState() {
104
+ return {
105
+ networkRequest: { ...DEFAULT_PERMISSION_STATE.networkRequest },
106
+ };
107
+ }
108
+ function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
109
+ const parsed = index_esm.parseMiniProgramRuntimePermissions(snapshot);
110
+ if (!parsed.valid) {
111
+ return { schema_version: 1, entries: [] };
108
112
  }
113
+ const entries = [];
114
+ for (const key of index_esm.MINI_PROGRAM_PERMISSION_KEYS) {
115
+ const entry = parsed.permissions[key];
116
+ if (!entry)
117
+ continue;
118
+ entries.push(key === 'network'
119
+ ? {
120
+ key,
121
+ status: state.networkRequest.status,
122
+ config: { useOfficialDomain },
123
+ }
124
+ : key === 'user_game_data' || key === 'post'
125
+ ? {
126
+ key,
127
+ status: entry.status,
128
+ // 浏览器模拟不能丢掉资源清单或关联帖的读写声明。
129
+ config: { ...entry.config },
130
+ }
131
+ : {
132
+ key,
133
+ status: entry.status,
134
+ config: {},
135
+ });
136
+ }
137
+ const revision = isPlainRecord(snapshot) && typeof snapshot.revision === 'number' && Number.isInteger(snapshot.revision) && snapshot.revision >= 0
138
+ ? snapshot.revision
139
+ : undefined;
140
+ return {
141
+ schema_version: 1,
142
+ ...(revision === undefined ? {} : { revision }),
143
+ entries,
144
+ };
109
145
  }
110
-
111
- function trustedProfileUrl(raw) {
112
- const url = new URL(raw);
113
- const trusted = ['max-c.com', 'xiaoheihe.cn', 'heybox.com'];
114
- if (url.protocol !== 'https:' ||
115
- url.username ||
116
- url.password ||
117
- (url.port && url.port !== '443') ||
118
- !trusted.some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`)))
119
- throw new Error('线上资料图片 URL 不受信任');
120
- return url;
146
+ function isPlainRecord(value) {
147
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
121
148
  }
122
- async function downloadImage(raw, fetchImpl) {
123
- const response = await fetchImpl(trustedProfileUrl(raw), { redirect: 'error', signal: AbortSignal.timeout(15_000) });
124
- if (!response.ok || !response.body)
125
- throw new Error('下载线上资料图片失败');
126
- if (Number(response.headers.get('content-length')) > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
127
- throw new Error('图片超过 10 MiB');
128
- const chunks = [];
129
- let size = 0;
130
- const reader = response.body.getReader();
149
+
150
+ /** 发布与开发预览共用项目级构建锁;文件系统失败时也不能无锁继续写 dist。 */
151
+ async function withProjectArtifactLock(root, operation) {
152
+ const lock = await index.acquireLocalFileLock(path.join(await fs.realpath(root), '.heybox', 'artifact-build'));
131
153
  try {
132
- for (;;) {
133
- const part = await reader.read();
134
- if (part.done)
135
- break;
136
- size += part.value.length;
137
- if (size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
138
- throw new Error('图片超过 10 MiB');
139
- chunks.push(part.value);
140
- }
154
+ return await operation();
141
155
  }
142
156
  finally {
143
- await reader.cancel();
157
+ await lock.release();
144
158
  }
145
- return Buffer.concat(chunks);
146
159
  }
147
- /** package-last 提交:失败只清理本次新增素材,原配置始终保留。 */
148
- async function migrateBasicInfo(cwd, detail, miniProgramId, fetchImpl = fetch, force = false) {
149
- const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
150
- const heybox = context.packageJson.heybox ?? {};
151
- const existing = heybox.miniProgramId;
152
- if (existing && existing !== miniProgramId && !force)
153
- throw new Error('当前项目已绑定其他小程序,请使用 --force');
154
- const fields = ['name', 'icon', 'coverImages'];
155
- const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(heybox, key));
156
- if (present.length && present.length !== 3)
157
- throw new Error(`资料配置不完整,请补齐 ${fields.filter((key) => !present.includes(key)).join('、')}`);
158
- const created = [];
159
- const temp = `${context.packageJsonPath}.${node_crypto.randomUUID()}.tmp`;
160
- try {
161
- let profile = present.length ? runtimePermissionEnv.parseMiniappBasicInfo(heybox) : undefined;
162
- if (profile) {
163
- await readBasicInfoSource(context.projectRoot, profile.icon, 'icon');
164
- for (const cover of profile.coverImages)
165
- await readBasicInfoSource(context.projectRoot, cover, 'cover');
166
- if (existing === miniProgramId)
167
- return { changed: false, miniProgramId };
160
+ const SUPPORTED_PACKAGE_MANAGERS = [
161
+ { name: 'pnpm', lockfile: 'pnpm-lock.yaml' },
162
+ { name: 'yarn', lockfile: 'yarn.lock' },
163
+ { name: 'npm', lockfile: 'package-lock.json' },
164
+ ];
165
+ function detectPackageManager(projectRoot) {
166
+ for (const candidate of SUPPORTED_PACKAGE_MANAGERS) {
167
+ if (fs$1.existsSync(path.join(projectRoot, candidate.lockfile))) {
168
+ return candidate.name;
168
169
  }
169
- else {
170
- if (detail.mini_program_id !== miniProgramId)
171
- throw new Error('远端小程序身份不一致');
172
- const snapshot = detail.published_basic_info;
173
- if (!snapshot?.version ||
174
- !snapshot.icon_url ||
175
- !Array.isArray(snapshot.cover_image_urls) ||
176
- snapshot.cover_image_urls.length < 1 ||
177
- snapshot.cover_image_urls.length > 5)
178
- throw new Error('没有当前正式发布快照,请手工配置 heybox.name/icon/coverImages');
179
- profile = { name: runtimePermissionEnv.normalizeBasicInfoName(snapshot.name), icon: '', coverImages: [] };
180
- const entries = [
181
- { url: snapshot.icon_url, kind: 'icon', label: 'icon' },
182
- ...snapshot.cover_image_urls.map((url, i) => ({ url, kind: 'cover', label: `cover-${String(i + 1).padStart(2, '0')}` })),
183
- ];
184
- for (const entry of entries) {
185
- const bytes = await downloadImage(entry.url, fetchImpl);
186
- const image = await inspectRemoteBasicInfoImage(bytes, entry.kind);
187
- const relative = `assets/heybox/${entry.label}.${image.sha256.slice(0, 12)}.${image.extension}`;
188
- const target = path.join(context.projectRoot, relative);
189
- await ensureBasicInfoDirectory(context.projectRoot, 'assets/heybox');
190
- try {
191
- await fs.writeFile(target, bytes, { flag: 'wx' });
192
- created.push(target);
193
- }
194
- catch (error) {
195
- if (error.code !== 'EEXIST' ||
196
- !(await readBasicInfoSource(context.projectRoot, relative, entry.kind).then((existing) => existing.bytes.equals(bytes), () => false)))
197
- throw new Error('迁移素材名称冲突,未覆盖已有文件');
198
- }
199
- if (entry.kind === 'icon')
200
- profile.icon = relative;
201
- else
202
- profile.coverImages.push(relative);
203
- }
204
- }
205
- // 避免覆盖用户在下载期间修改的配置。
206
- if ((await fs.readFile(context.packageJsonPath, 'utf8')) !== context.raw)
207
- throw new Error('package.json 已变化,请重试迁移');
208
- context.packageJson.heybox = { ...heybox, miniProgramId, ...profile };
209
- await fs.writeFile(temp, JSON.stringify(context.packageJson, null, context.indent) + context.trailingNewline, { flag: 'wx' });
210
- await fs.rename(temp, context.packageJsonPath);
211
- return { changed: true, miniProgramId };
212
170
  }
213
- catch (error) {
214
- // 若用户同时修改了 package,保留可能已被引用的素材供重试复用。
215
- if ((await fs.readFile(context.packageJsonPath, 'utf8').catch(() => '')) === context.raw) {
216
- await Promise.all(created.map((file) => fs.unlink(file).catch(() => { })));
171
+ return 'npm';
172
+ }
173
+ async function runBuildScript(pm, cwd, spawnImpl, options) {
174
+ const buildScript = await readProjectBuildScript(cwd);
175
+ options.signal?.throwIfAborted();
176
+ await new Promise((resolve, reject) => {
177
+ const pipeStdoutToStderr = options.outputMode === 'stderr';
178
+ const buildArgs = createBuildArgs(pm, options.mode, buildScript);
179
+ const isWindows = options.platform === 'win32';
180
+ const [executable, args] = isWindows ? createWindowsBuildCommand(pm, buildArgs) : [pm, buildArgs];
181
+ const child = spawnImpl(executable, args, {
182
+ cwd,
183
+ // 可取消构建独占进程组,取消时一起终止包管理器和构建子进程。
184
+ detached: Boolean(options.signal) && !isWindows,
185
+ env: { ...process.env, ...options.env },
186
+ ...(isWindows ? { shell: false, windowsVerbatimArguments: true } : {}),
187
+ stdio: pipeStdoutToStderr ? ['inherit', 'pipe', 'inherit'] : 'inherit',
188
+ });
189
+ if (pipeStdoutToStderr) {
190
+ child.stdout?.on('data', (chunk) => {
191
+ (options.stderr ?? process.stderr).write(chunk);
192
+ });
217
193
  }
218
- throw error;
219
- }
220
- finally {
221
- await fs.unlink(temp).catch(() => { });
194
+ let cancelled = false;
195
+ let killTree = Promise.resolve();
196
+ const cleanup = () => options.signal?.removeEventListener('abort', abort);
197
+ const abort = () => {
198
+ if (cancelled)
199
+ return;
200
+ cancelled = true;
201
+ if (!child.pid)
202
+ return;
203
+ if (isWindows) {
204
+ killTree = new Promise((done) => {
205
+ const killer = childProcess.spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
206
+ // 失败仍等待 child close,不能在构建仍写盘时释放锁。
207
+ killer.once('error', () => {
208
+ child.kill('SIGKILL');
209
+ done();
210
+ });
211
+ killer.once('close', () => done());
212
+ });
213
+ }
214
+ else {
215
+ try {
216
+ process.kill(-child.pid, 'SIGKILL');
217
+ }
218
+ catch (error) {
219
+ if (error.code !== 'ESRCH')
220
+ child.kill('SIGKILL');
221
+ }
222
+ }
223
+ };
224
+ options.signal?.addEventListener('abort', abort, { once: true });
225
+ if (options.signal?.aborted)
226
+ abort();
227
+ child.on('error', (error) => {
228
+ cleanup();
229
+ reject(error);
230
+ });
231
+ child.on('exit', (code) => {
232
+ if (cancelled)
233
+ return; // 取消必须等管道与子进程清理完成。
234
+ cleanup();
235
+ if (code === 0)
236
+ resolve();
237
+ else
238
+ reject(new Error(`${pm} run build exited with code ${code ?? 'null'}`));
239
+ });
240
+ child.on('close', () => {
241
+ if (!cancelled)
242
+ return;
243
+ cleanup();
244
+ void killTree.then(() => reject(options.signal?.reason ?? new Error('构建已取消')));
245
+ });
246
+ });
247
+ }
248
+ function createWindowsBuildCommand(pm, buildArgs) {
249
+ const command = `${pm}.cmd ${buildArgs.map(escapeWindowsCommandArgument).join(' ')}`;
250
+ return ['cmd.exe', ['/d', '/s', '/c', `"${command}"`]];
251
+ }
252
+ function validateBuildMode(mode, platform) {
253
+ if (platform === 'win32' && mode && !/^[A-Za-z0-9._-]+$/.test(mode)) {
254
+ throw new Error('Windows 下 HB_SDK_ENV 仅支持字母、数字、点、下划线和连字符');
222
255
  }
256
+ return mode;
223
257
  }
224
- async function compareBasicInfo(cwd, detail, fetchImpl = fetch) {
225
- const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
226
- const published = detail.published_basic_info;
227
- let local;
258
+ function escapeWindowsCommandArgument(argument) {
259
+ return `"${argument}"`;
260
+ }
261
+ async function readProjectBuildScript(projectRoot) {
228
262
  try {
229
- local = runtimePermissionEnv.parseMiniappBasicInfo(context.packageJson.heybox ?? {});
263
+ const packageJson = JSON.parse(await fs.readFile(path.join(projectRoot, 'package.json'), 'utf8'));
264
+ return typeof packageJson.scripts?.build === 'string' ? packageJson.scripts.build : '';
230
265
  }
231
266
  catch {
232
- return { status: 'unavailable' };
267
+ return '';
233
268
  }
234
- if (!local || !published?.version)
235
- return { status: 'unavailable', local, published };
236
- try {
237
- const pairs = [
238
- { local: local.icon, remote: published.icon_url, kind: 'icon' },
239
- ...local.coverImages.map((p, i) => ({ local: p, remote: published.cover_image_urls[i], kind: 'cover' })),
240
- ];
241
- let changed = local.name !== runtimePermissionEnv.normalizeBasicInfoName(published.name) || local.coverImages.length !== published.cover_image_urls.length;
242
- for (const pair of pairs) {
243
- if (!pair.remote) {
244
- changed = true;
245
- continue;
246
- }
247
- const source = await readBasicInfoSource(context.projectRoot, pair.local, pair.kind);
248
- const bytes = await downloadImage(pair.remote, fetchImpl);
249
- const remote = await inspectRemoteBasicInfoImage(bytes, pair.kind);
250
- changed ||= source.sha256 !== remote.sha256;
269
+ }
270
+ function createBuildArgs(pm, mode, buildScript) {
271
+ const modeOption = /\bhb-sdk\s+build\b/.test(buildScript) ? '--env' : '--mode';
272
+ return ['run', 'build', ...(mode ? [...(pm === 'npm' ? ['--'] : []), modeOption, mode] : [])];
273
+ }
274
+
275
+ /** 单次流式读取同时生成整包签名和逐文件 SHA-256 receipt。 */
276
+ async function computeMiniappArtifactReceipt(files, runtime = {}) {
277
+ const preparedFiles = runtimePermissionEnv.prepareMiniappArtifactFiles(files);
278
+ const hash = node_crypto.createHash('sha256');
279
+ const createReadStream = runtime.createReadStream ?? fs$1.createReadStream;
280
+ hash.update(runtimePermissionEnv.createMiniappArtifactSignatureHeader(preparedFiles.length));
281
+ for (const file of preparedFiles) {
282
+ hash.update(runtimePermissionEnv.createMiniappArtifactFileHeader(file));
283
+ const fileHash = node_crypto.createHash('sha256');
284
+ let bytesRead = 0;
285
+ for await (const chunk of createReadStream(file.absolutePath)) {
286
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
287
+ bytesRead += bytes.byteLength;
288
+ hash.update(bytes);
289
+ fileHash.update(bytes);
251
290
  }
252
- return { status: changed ? 'changed' : 'unchanged', local, published };
253
- }
254
- catch {
255
- return { status: 'unavailable', local, published };
291
+ if (bytesRead !== file.size) {
292
+ throw new Error(`构建产物在签名期间发生变化:${file.relativePath}`);
293
+ }
294
+ Object.assign(file, { sha256: fileHash.digest('hex') });
256
295
  }
296
+ return { artifactSignature: hash.digest('hex'), files: preparedFiles };
257
297
  }
258
298
 
259
- const CREATE_USER_MINIPROGRAM_UPLOAD_SESSION_API_PATH = '/mall/developer/user_miniprogram/version/upload_session/create';
260
- const RECORD_USER_MINIPROGRAM_UPLOAD_RESULT_API_PATH = '/mall/developer/user_miniprogram/version/upload_session/record';
261
- const COMPANION_FINALIZATION_TIMEOUT_MS = 30 * 60_000;
262
- async function authorizeCompanionUpload(options, runtime = {}) {
263
- const result = await postUserMiniprogramVersionForm('/mall/developer/user_miniprogram/version/upload_session/companion_authorization', options, { version: options.version, session_id: options.sessionId, relative_paths: options.relativePaths.join(','), artifact_protocol_version: '2' }, runtime);
264
- if (!result.bucket || !result.region || !Array.isArray(result.keys) || !result.tmp_secret_id || !result.tmp_secret_key || !result.session_token || !(result.expired_time > result.start_time)) {
265
- throw new Error('Companion 上传凭证响应不完整');
266
- }
267
- return result;
299
+ function createRemoteApiClient(options) {
300
+ return {
301
+ getPostBinding: (request) => remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_POST_BINDING_API_PATH, request, options),
302
+ previewPostBinding: (request) => remotePostForm(runtimePermissionEnv.USER_MINIPROGRAM_POST_PREVIEW_API_PATH, request, options),
303
+ setPostBinding: (request) => remotePostForm(`${runtimePermissionEnv.USER_MINIPROGRAM_POST_BINDING_API_PATH}/update`, request, options),
304
+ listPermissionApplications: (request) => remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
305
+ submitPermissionApplication: (request) => remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
306
+ listDeveloperEntities: () => listDeveloperEntities(options),
307
+ switchDeveloperEntity: (requestOptions) => switchDeveloperEntity(requestOptions, options),
308
+ getDeveloperAccessStatus: () => getDeveloperAccessStatus(options),
309
+ listUserMiniprograms: (requestOptions = {}) => listUserMiniprograms(requestOptions, options),
310
+ createUserMiniprogram: () => createUserMiniprogram(options),
311
+ getUserMiniprogramDetail: (requestOptions) => getUserMiniprogramDetail(requestOptions, options),
312
+ createLocalDevLaunchToken: (requestOptions) => createLocalDevLaunchToken$1(requestOptions, options),
313
+ getPreviewAllowlist: (requestOptions) => getPreviewAllowlist(requestOptions, options),
314
+ updatePreviewAllowlist: (requestOptions) => updatePreviewAllowlist(requestOptions, options),
315
+ createUserMiniprogramLeaderboard: (requestOptions) => createUserMiniprogramLeaderboard(requestOptions, options),
316
+ getUserMiniprogramLeaderboard: (requestOptions) => getUserMiniprogramLeaderboard(requestOptions, options),
317
+ listUserMiniprogramLeaderboards: (requestOptions) => listUserMiniprogramLeaderboards(requestOptions, options),
318
+ deleteUserMiniprogramLeaderboard: (requestOptions) => deleteUserMiniprogramLeaderboard(requestOptions, options),
319
+ precheckUserMiniprogramVersion: (requestOptions) => precheckUserMiniprogramVersion$1(requestOptions, options),
320
+ submitUserMiniprogramAudit: (requestOptions) => submitUserMiniprogramAudit$1(requestOptions, options),
321
+ getVersionPreviewInfo: (requestOptions) => getVersionPreviewInfo(requestOptions, options),
322
+ withdrawUserMiniprogramVersion: (requestOptions) => withdrawUserMiniprogramVersion(requestOptions, options),
323
+ releaseUserMiniprogramVersion: (requestOptions) => releaseUserMiniprogramVersion(requestOptions, options),
324
+ takeDownUserMiniprogram: (requestOptions) => takeDownUserMiniprogram(requestOptions, options),
325
+ reopenUserMiniprogram: (requestOptions) => reopenUserMiniprogram(requestOptions, options),
326
+ updateSquareDisplay: (requestOptions) => updateSquareDisplay(requestOptions, options),
327
+ listUserMiniprogramVersions: (requestOptions) => listUserMiniprogramVersions(requestOptions, options),
328
+ };
268
329
  }
269
- async function precheckUserMiniprogramVersion$1(options, runtime = {}) {
270
- return postUserMiniprogramVersionForm(runtimePermissionEnv.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH, options, {
271
- // 构建前轻预检不携带独立资料;权威准入读取构建 Manifest。
272
- ...(options.version ? { version: options.version } : {}),
273
- ...(options.manifest ? { manifest: JSON.stringify(options.manifest) } : {}),
274
- release_note: options.releaseNote,
275
- auto_publish: String(options.autoPublish),
276
- }, runtime);
330
+ async function listDeveloperEntities(runtime) {
331
+ return remoteGet(runtimePermissionEnv.DEVELOPER_ENTITY_LIST_API_PATH, {}, runtime);
277
332
  }
278
- async function submitUserMiniprogramAudit$1(options, runtime = {}) {
279
- return postUserMiniprogramVersionForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, options, { session_id: options.sessionId, preflight_token: options.preflightToken, artifact_protocol_version: '2' }, runtime);
333
+ async function switchDeveloperEntity(options, runtime) {
334
+ return (await remotePostForm(runtimePermissionEnv.DEVELOPER_ENTITY_SWITCH_API_PATH, options, runtime, { requireResult: false })) ?? {};
280
335
  }
281
- async function createUserMiniprogramUploadSession(options, runtime = {}) {
282
- return postUserMiniprogramVersionForm(CREATE_USER_MINIPROGRAM_UPLOAD_SESSION_API_PATH, options, {
283
- version: options.version,
284
- artifact_protocol_version: '2',
285
- artifact_signature: options.artifactSignature,
286
- files: JSON.stringify(options.files),
287
- manifest: JSON.stringify(options.manifest),
288
- release_note: options.releaseNote,
289
- auto_publish: String(options.autoPublish),
290
- }, runtime);
336
+ async function getDeveloperAccessStatus(runtime) {
337
+ return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_ACCESS_STATUS_API_PATH, {}, runtime);
291
338
  }
292
- async function recordUserMiniprogramUploadResult(options, runtime = {}) {
293
- const fields = {
294
- version: options.version,
295
- artifact_protocol_version: '2',
296
- session_id: options.sessionId,
297
- files: JSON.stringify(options.files),
298
- };
299
- const deadline = Date.now() + COMPANION_FINALIZATION_TIMEOUT_MS;
300
- for (;;) {
301
- const result = await postUserMiniprogramVersionForm(RECORD_USER_MINIPROGRAM_UPLOAD_RESULT_API_PATH, options, fields, runtime);
302
- if (result.artifact_protocol_version !== 2 || !Array.isArray(result.companion_files)) {
303
- throw new Error('服务端未返回产物协议 v2 Finalize 状态');
304
- }
305
- const failed = result.companion_files.find((file) => file.state === 'failed');
306
- if (failed)
307
- throw new Error(failed.error || `Companion 归档验证失败:${failed.relative_path}`);
308
- if (result.complete)
309
- return;
310
- if (Date.now() >= deadline)
311
- throw new Error('Companion 归档验证超时,请稍后重试');
312
- await new Promise((resolve) => setTimeout(resolve, Math.max(250, Math.min(result.retry_after_ms || 1000, 5000))));
313
- }
339
+ async function listUserMiniprograms(options, runtime) {
340
+ return remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_API_PATH, options, runtime);
314
341
  }
315
- async function postUserMiniprogramVersionForm(path, options, fields, runtime) {
316
- const fetchImpl = runtime.fetchImpl ?? fetch;
317
- const context = index.createHeyboxOpenPlatformRequestContext(options.session, path, {
318
- contentType: 'application/x-www-form-urlencoded',
319
- });
320
- const body = new URLSearchParams();
321
- body.set('mini_program_id', options.miniProgramId);
322
- for (const [key, value] of Object.entries(fields)) {
323
- body.set(key, value);
324
- }
325
- const response = await fetchImpl(index.createHeyboxApiUrl(runtime.baseUrl ?? context.baseUrl, path, context.platformParams), {
326
- method: 'POST',
327
- headers: context.headers,
328
- body: body.toString(),
329
- });
330
- const result = await index.readHeyboxApiEnvelope(response, {
331
- pathWithQuery: path,
332
- });
333
- return result ?? {};
334
- }
335
-
336
- const DEFAULT_CONCURRENCY = 4;
337
- async function runUpload(options, runtime = {}) {
338
- const logger = runtime.logger ?? index.createCliLogger();
339
- const concurrency = runtime.concurrency ?? DEFAULT_CONCURRENCY;
340
- const fetchImpl = runtime.fetchImpl ?? fetch;
341
- const getCDNUploadInfo = runtime.getCDNUploadInfo ?? index.getCDNUploadInfo;
342
- const getCDNUploadToken = runtime.getCDNUploadToken ?? index.getCDNUploadToken;
343
- const postCDNUploadCallback = runtime.postCDNUploadCallback ?? index.postCDNUploadCallback;
344
- const recordUserMiniprogramUploadResult$1 = runtime.recordUserMiniprogramUploadResult ?? recordUserMiniprogramUploadResult;
345
- const createReadStream = runtime.createReadStream ?? fs$1.createReadStream;
346
- const cdnBaseUrl = runtime.cdnBaseUrl ?? runtime.baseUrl;
347
- let createCosClient = runtime.createCosClient;
348
- if (!createCosClient) {
349
- const COS = await loadCosConstructor();
350
- createCosClient = ({ uploadToken }) => createDefaultCosClient(uploadToken, COS);
351
- }
352
- const orderedFiles = runtimePermissionEnv.prepareMiniappArtifactFiles(options.files);
353
- const batches = [false, true].flatMap(companion => chunkUploadFiles(orderedFiles.filter(file => file.relativePath.startsWith('companions/') === companion), runtimePermissionEnv.MINIAPP_UPLOAD_BATCH_SIZE));
354
- await logger.task(`正在上传 ${orderedFiles.length} 个文件`, async (taskContext) => {
355
- logger.debug(`上传并发数: ${concurrency}`);
356
- logger.debug(`上传批次数: ${batches.length}`);
357
- let completed = 0;
358
- for (let batchIndex = 0; batchIndex < batches.length; batchIndex += 1) {
359
- const batch = batches[batchIndex];
360
- const companion = batch[0].relativePath.startsWith('companions/');
361
- const grant = companion ? await (runtime.authorizeCompanionUpload ?? authorizeCompanionUpload)({
362
- session: options.session, miniProgramId: options.miniProgramId, version: options.version, sessionId: options.uploadSessionId, relativePaths: batch.map(file => file.relativePath),
363
- }, { baseUrl: runtime.baseUrl, fetchImpl }) : undefined;
364
- logger.debug(`正在处理上传批次 ${batchIndex + 1}/${batches.length},文件数: ${batch.length}`);
365
- logger.debug('正在获取 CDN 上传信息');
366
- const fileInfos = createUploadFileInfos(batch);
367
- const uploadInfo = grant ?? await getCDNUploadInfo({
368
- session: options.session,
369
- scope: runtimePermissionEnv.MINIAPP_UPLOAD_SCOPE,
370
- fileInfos,
371
- needCache: false,
372
- }, { baseUrl: cdnBaseUrl, fetchImpl });
373
- logger.debug(`CDN bucket: ${uploadInfo.bucket}`);
374
- logger.debug(`CDN region: ${uploadInfo.region}`);
375
- validateUploadInfoKeys(batch, uploadInfo.keys);
376
- const indexedFiles = batch.map((file, index) => ({ file, key: uploadInfo.keys[index] }));
377
- logger.debug('正在获取本批 CDN 上传凭证');
378
- let uploadToken;
379
- try {
380
- uploadToken = grant ? {
381
- credentials: { tmpSecretId: grant.tmp_secret_id, tmpSecretKey: grant.tmp_secret_key, sessionToken: grant.session_token },
382
- startTime: grant.start_time, expiredTime: grant.expired_time,
383
- } : await getCDNUploadToken({
384
- session: options.session,
385
- bucket: uploadInfo.bucket,
386
- keys: indexedFiles.map((item) => item.key),
387
- mimetypes: indexedFiles.map((item) => item.file.mimeType),
388
- isMultipartUpload: 0,
389
- }, { baseUrl: cdnBaseUrl, fetchImpl });
390
- }
391
- catch (error) {
392
- throw new index.CliError(`获取 CDN 上传凭证失败:${readErrorMessage(error)}`);
393
- }
394
- const cos = createCosClient({ session: options.session, uploadToken });
395
- const successfulKeys = [];
396
- const queue = indexedFiles.slice();
397
- let firstUploadError;
398
- const workers = Array.from({ length: Math.min(concurrency, indexedFiles.length) }, async () => {
399
- while (queue.length > 0 && !firstUploadError) {
400
- const uploadTask = queue.shift();
401
- if (!uploadTask) {
402
- return;
403
- }
404
- try {
405
- await cos.putObject({
406
- Bucket: uploadInfo.bucket,
407
- Region: uploadInfo.region,
408
- Key: uploadTask.key,
409
- Body: createReadStream(uploadTask.file.absolutePath),
410
- ContentLength: uploadTask.file.size,
411
- ContentType: uploadTask.file.mimeType,
412
- ...(companion ? { Headers: { 'x-cos-forbid-overwrite': 'true' } } : {}),
413
- }).catch(error => {
414
- if (companion && isExistingCompanionObject(error))
415
- return;
416
- throw error;
417
- });
418
- successfulKeys.push(uploadTask.key);
419
- completed += 1;
420
- taskContext.update(`正在上传 ${completed}/${orderedFiles.length} 个文件`);
421
- logger.debug(`[${String(completed).padStart(2)}/${orderedFiles.length}] ok ${uploadTask.file.relativePath} (${formatSize(uploadTask.file.size)})`);
422
- }
423
- catch (error) {
424
- completed += 1;
425
- const message = readErrorMessage(error);
426
- logger.debug(`[${String(completed).padStart(2)}/${orderedFiles.length}] error ${uploadTask.file.relativePath} -> ${message}`);
427
- firstUploadError ??= new index.CliError(`上传文件失败:${uploadTask.file.relativePath} -> ${message}`, readVerboseUploadError(uploadTask.file.relativePath, error));
428
- }
429
- }
430
- });
431
- await Promise.all(workers);
432
- if (successfulKeys.length > 0) {
433
- logger.debug('正在确认 CDN 上传结果');
434
- if (!companion)
435
- await postCDNUploadCallback({ session: options.session, keys: successfulKeys, isFinished: true }, { baseUrl: cdnBaseUrl, fetchImpl });
436
- await recordUserMiniprogramUploadResult$1({
437
- session: options.session,
438
- miniProgramId: options.miniProgramId,
439
- version: options.version,
440
- sessionId: options.uploadSessionId,
441
- files: indexedFiles
442
- .filter((item) => successfulKeys.includes(item.key))
443
- .map((item) => ({ path: item.file.relativePath, size: item.file.size, sha256: item.file.sha256 })),
444
- }, { baseUrl: runtime.baseUrl, fetchImpl });
445
- }
446
- if (firstUploadError) {
447
- throw firstUploadError;
448
- }
449
- }
450
- }, { successText: `已上传 ${orderedFiles.length} 个文件` });
451
- }
452
- function chunkUploadFiles(files, batchSize) {
453
- const batches = [];
454
- for (let index = 0; index < files.length; index += batchSize) {
455
- batches.push(files.slice(index, index + batchSize));
456
- }
457
- return batches;
458
- }
459
- function isExistingCompanionObject(error) {
460
- if (!error || typeof error !== 'object')
461
- return false;
462
- const value = error;
463
- return Number(value.statusCode) === 409 && value.code === 'ObjectAlreadyExists';
464
- }
465
- function createUploadFileInfos(files) {
466
- return files.map((file) => ({
467
- name: file.relativePath.split('/').pop() ?? file.relativePath,
468
- mimetype: file.mimeType,
469
- fsize: file.size,
470
- path: file.key,
471
- }));
472
- }
473
- function validateUploadInfoKeys(files, keys) {
474
- if (keys.length !== files.length) {
475
- throw new index.CliError(`CDN 上传接口返回 key 数量异常:期望 ${files.length},实际 ${keys.length}`);
476
- }
477
- for (let index$1 = 0; index$1 < files.length; index$1 += 1) {
478
- const expectedKey = files[index$1].key;
479
- const actualKey = keys[index$1];
480
- if (actualKey !== expectedKey) {
481
- throw new index.CliError(`CDN 上传接口返回 key 异常:${files[index$1].relativePath}`, [`CDN 上传接口返回 key 异常:${files[index$1].relativePath}`, `expected: ${expectedKey}`, `actual: ${actualKey}`].join('\n'));
482
- }
483
- }
484
- }
485
- function createDefaultCosClient(uploadToken, COS) {
486
- const cos = new COS({
487
- getAuthorization(_input, callback) {
488
- callback({
489
- TmpSecretId: uploadToken.credentials.tmpSecretId,
490
- TmpSecretKey: uploadToken.credentials.tmpSecretKey,
491
- XCosSecurityToken: uploadToken.credentials.sessionToken,
492
- StartTime: uploadToken.startTime,
493
- ExpiredTime: uploadToken.expiredTime,
494
- });
495
- },
496
- });
497
- return {
498
- putObject(params) {
499
- return new Promise((resolve, reject) => {
500
- cos.putObject(params, (err, result) => {
501
- if (err) {
502
- reject(err);
503
- return;
504
- }
505
- resolve(result);
506
- });
507
- });
508
- },
509
- };
510
- }
511
- async function loadCosConstructor() {
512
- const cosModule = await Promise.resolve().then(function () { return require('./index-BuYCoach.cjs'); }).then(function (n) { return n.index; });
513
- return cosModule.default;
514
- }
515
- function formatSize(bytes) {
516
- if (bytes < 1024) {
517
- return `${bytes} B`;
518
- }
519
- if (bytes < 1024 * 1024) {
520
- return `${(bytes / 1024).toFixed(1)} KB`;
521
- }
522
- return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
523
- }
524
- function readErrorMessage(error) {
525
- if (error instanceof Error && error.message) {
526
- return error.message;
527
- }
528
- if (isRecord(error)) {
529
- const primary = readStringField(error, ['message', 'Message', 'errorMessage', 'msg']);
530
- const code = readStringField(error, ['code', 'Code', 'errorCode', 'name']);
531
- const statusCode = readStringField(error, ['statusCode']);
532
- return [code, statusCode, primary].filter(Boolean).join(' ') || JSON.stringify(error);
533
- }
534
- return String(error);
535
- }
536
- function readVerboseUploadError(relativePath, error) {
537
- return [`上传文件失败:${relativePath}`, `原始错误:${readErrorMessage(error)}`].join('\n');
538
- }
539
- function readStringField(record, fields) {
540
- for (const field of fields) {
541
- const value = record[field];
542
- if (typeof value === 'string' && value.trim()) {
543
- return value.trim();
544
- }
545
- if (typeof value === 'number') {
546
- return String(value);
547
- }
548
- }
549
- return '';
550
- }
551
- function isRecord(value) {
552
- return Object.prototype.toString.call(value) === '[object Object]';
553
- }
554
-
555
- /** 单次流式读取同时生成整包签名和逐文件 SHA-256 receipt。 */
556
- async function computeMiniappArtifactReceipt(files, runtime = {}) {
557
- const preparedFiles = runtimePermissionEnv.prepareMiniappArtifactFiles(files);
558
- const hash = node_crypto.createHash('sha256');
559
- const createReadStream = runtime.createReadStream ?? fs$1.createReadStream;
560
- hash.update(runtimePermissionEnv.createMiniappArtifactSignatureHeader(preparedFiles.length));
561
- for (const file of preparedFiles) {
562
- hash.update(runtimePermissionEnv.createMiniappArtifactFileHeader(file));
563
- const fileHash = node_crypto.createHash('sha256');
564
- let bytesRead = 0;
565
- for await (const chunk of createReadStream(file.absolutePath)) {
566
- const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
567
- bytesRead += bytes.byteLength;
568
- hash.update(bytes);
569
- fileHash.update(bytes);
570
- }
571
- if (bytesRead !== file.size) {
572
- throw new Error(`构建产物在签名期间发生变化:${file.relativePath}`);
573
- }
574
- Object.assign(file, { sha256: fileHash.digest('hex') });
575
- }
576
- return { artifactSignature: hash.digest('hex'), files: preparedFiles };
577
- }
578
-
579
- function createRemoteApiClient(options) {
580
- return {
581
- listPermissionApplications: (request) => remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
582
- submitPermissionApplication: (request) => remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
583
- listDeveloperEntities: () => listDeveloperEntities(options),
584
- switchDeveloperEntity: (requestOptions) => switchDeveloperEntity(requestOptions, options),
585
- getDeveloperAccessStatus: () => getDeveloperAccessStatus(options),
586
- listUserMiniprograms: (requestOptions = {}) => listUserMiniprograms(requestOptions, options),
587
- createUserMiniprogram: () => createUserMiniprogram(options),
588
- getUserMiniprogramDetail: (requestOptions) => getUserMiniprogramDetail(requestOptions, options),
589
- createLocalDevLaunchToken: (requestOptions) => createLocalDevLaunchToken$1(requestOptions, options),
590
- getPreviewAllowlist: (requestOptions) => getPreviewAllowlist(requestOptions, options),
591
- updatePreviewAllowlist: (requestOptions) => updatePreviewAllowlist(requestOptions, options),
592
- createUserMiniprogramLeaderboard: (requestOptions) => createUserMiniprogramLeaderboard(requestOptions, options),
593
- getUserMiniprogramLeaderboard: (requestOptions) => getUserMiniprogramLeaderboard(requestOptions, options),
594
- listUserMiniprogramLeaderboards: (requestOptions) => listUserMiniprogramLeaderboards(requestOptions, options),
595
- deleteUserMiniprogramLeaderboard: (requestOptions) => deleteUserMiniprogramLeaderboard(requestOptions, options),
596
- precheckUserMiniprogramVersion: (requestOptions) => precheckUserMiniprogramVersion(requestOptions, options),
597
- submitUserMiniprogramAudit: (requestOptions) => submitUserMiniprogramAudit(requestOptions, options),
598
- getVersionPreviewInfo: (requestOptions) => getVersionPreviewInfo(requestOptions, options),
599
- withdrawUserMiniprogramVersion: (requestOptions) => withdrawUserMiniprogramVersion(requestOptions, options),
600
- releaseUserMiniprogramVersion: (requestOptions) => releaseUserMiniprogramVersion(requestOptions, options),
601
- takeDownUserMiniprogram: (requestOptions) => takeDownUserMiniprogram(requestOptions, options),
602
- reopenUserMiniprogram: (requestOptions) => reopenUserMiniprogram(requestOptions, options),
603
- updateSquareDisplay: (requestOptions) => updateSquareDisplay(requestOptions, options),
604
- listUserMiniprogramVersions: (requestOptions) => listUserMiniprogramVersions(requestOptions, options),
605
- };
606
- }
607
- async function listDeveloperEntities(runtime) {
608
- return remoteGet(runtimePermissionEnv.DEVELOPER_ENTITY_LIST_API_PATH, {}, runtime);
609
- }
610
- async function switchDeveloperEntity(options, runtime) {
611
- return (await remotePostForm(runtimePermissionEnv.DEVELOPER_ENTITY_SWITCH_API_PATH, options, runtime, { requireResult: false })) ?? {};
612
- }
613
- async function getDeveloperAccessStatus(runtime) {
614
- return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_ACCESS_STATUS_API_PATH, {}, runtime);
615
- }
616
- async function listUserMiniprograms(options, runtime) {
617
- return remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_API_PATH, options, runtime);
618
- }
619
- async function createUserMiniprogram(runtime) {
620
- return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_API_PATH, {}, runtime);
342
+ async function createUserMiniprogram(runtime) {
343
+ return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_API_PATH, {}, runtime);
621
344
  }
622
345
  async function getUserMiniprogramDetail(options, runtime) {
623
346
  return remoteGet(runtimePermissionEnv.DETAIL_USER_MINIPROGRAM_API_PATH, options, runtime);
@@ -643,12 +366,14 @@ async function listUserMiniprogramLeaderboards(options, runtime) {
643
366
  async function deleteUserMiniprogramLeaderboard(options, runtime) {
644
367
  return ((await remotePostForm(runtimePermissionEnv.DELETE_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime, { requireResult: false })) ?? {});
645
368
  }
646
- async function precheckUserMiniprogramVersion(options, runtime) {
369
+ async function precheckUserMiniprogramVersion$1(options, runtime) {
647
370
  return remotePostForm(runtimePermissionEnv.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
648
371
  }
649
- async function submitUserMiniprogramAudit(options, runtime) {
372
+ async function submitUserMiniprogramAudit$1(options, runtime) {
650
373
  return remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, {
651
- mini_program_id: options.mini_program_id, session_id: options.session_id, preflight_token: options.preflight_token,
374
+ mini_program_id: options.mini_program_id,
375
+ session_id: options.session_id,
376
+ preflight_token: options.preflight_token,
652
377
  }, runtime);
653
378
  }
654
379
  async function getVersionPreviewInfo(options, runtime) {
@@ -793,114 +518,530 @@ function isTruthyEnvFlag(value) {
793
518
  .toLowerCase());
794
519
  }
795
520
 
796
- /** Browser Fake 与 channel 共用的本地 grant 有效性校验。 */
797
- function resolveBrowserFakeContext(context, now = Date.now()) {
798
- if (context.localDevGrant === undefined)
799
- return context;
800
- const parsed = index_esm.parseMiniProgramLocalDevGrant(context.localDevGrant);
801
- if (!parsed.valid ||
802
- !context.devSessionId?.trim() ||
803
- !Number.isSafeInteger(context.contextRevision) ||
804
- context.contextRevision !== parsed.grant.revision ||
805
- !context.expiresAt ||
806
- !Number.isFinite(context.expiresAt) ||
807
- (context.source !== 'remote' && context.expiresAt <= now)) {
808
- return { ...context, localDevGrant: undefined, warning: '本地临时授权无效或已过期,已降权' };
521
+ /** PC 适配指南是下载、配置与验收步骤的统一入口。 */
522
+ const PC_ADAPTATION_GUIDE_URL = 'https://docs.xiaoheihe.cn/hb_sdk/guide/pc-adaptation';
523
+ const PC_CLIENT_DOWNLOAD_URL = 'https://www.xiaoheihe.cn';
524
+ const PC_ONBOARDING_PATH = '/__hb_sdk__/pc-onboarding';
525
+ /** 平台声明只代表适配承诺,不能据此认定已完成客户端验收。 */
526
+ function getPcAdaptationSuggestion(platforms) {
527
+ return platforms.includes('windows') || platforms.includes('macos')
528
+ ? '已声明 PC 平台:提审前建议在对应 PC 客户端验证窗口缩放、鼠标键盘及所用端能力。'
529
+ : '小程序也可以在小黑盒 PC 客户端运行。建议评估 Windows / macOS 适配,并在提审前完成客户端验证;仅做移动端可忽略。';
530
+ }
531
+
532
+ async function inspectBasicInfoImage(bytes, sourcePath, kind) {
533
+ const inspected = await inspectDecodedBasicInfoImage(bytes, kind);
534
+ const extensions = { jpg: ['jpg', 'jpeg'], png: ['png'], gif: ['gif'], webp: ['webp'] };
535
+ const ext = sourcePath.split('.').pop().toLowerCase();
536
+ if (!extensions[inspected.extension]?.includes(ext))
537
+ throw new Error('资料图片格式与扩展名不一致');
538
+ return inspected;
539
+ }
540
+ async function inspectRemoteBasicInfoImage(bytes, kind) {
541
+ return inspectDecodedBasicInfoImage(bytes, kind);
542
+ }
543
+ async function inspectDecodedBasicInfoImage(bytes, kind) {
544
+ if (!bytes.length || bytes.length > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
545
+ throw new Error('资料图片不得为空或超过 10 MiB');
546
+ const decoder = sharp(bytes, { limitInputPixels: runtimePermissionEnv.BASIC_INFO_MAX_PIXELS, failOn: 'warning' });
547
+ const metadata = await decoder.metadata();
548
+ const extensions = { jpeg: 'jpg', png: 'png', gif: 'gif', webp: 'webp' };
549
+ if (!metadata.format || !extensions[metadata.format])
550
+ throw new Error('资料图片格式不支持');
551
+ const width = metadata.width ?? 0;
552
+ const height = metadata.pageHeight ?? metadata.height ?? 0;
553
+ if (!width || !height || width * height > runtimePermissionEnv.BASIC_INFO_MAX_PIXELS)
554
+ throw new Error('资料图片不得超过 4000 万像素');
555
+ if (kind === 'icon' && (width !== 200 || height !== 200))
556
+ throw new Error('icon 必须是 200×200');
557
+ // 强制解码而非只信任图片头;不将解码结果写回图片。
558
+ await decoder.stats();
559
+ return { sha256: node_crypto.createHash('sha256').update(bytes).digest('hex'), extension: extensions[metadata.format] };
560
+ }
561
+ async function readBasicInfoSource(projectRoot, relative, kind) {
562
+ runtimePermissionEnv.validateBasicInfoPath(relative);
563
+ const root = await fs.realpath(projectRoot);
564
+ const target = await fs.realpath(path.join(root, relative));
565
+ const resolvedRelative = path.relative(root, target).split(path.sep).join('/');
566
+ runtimePermissionEnv.validateBasicInfoPath(resolvedRelative);
567
+ if (resolvedRelative.startsWith('../') || path.isAbsolute(resolvedRelative))
568
+ throw new Error('资料图片不能逃逸项目目录');
569
+ const info = await fs.stat(target);
570
+ if (!info.isFile() || info.size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
571
+ throw new Error('资料图片必须为不超过 10 MiB 的普通文件');
572
+ const file = await fs.open(target, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW);
573
+ try {
574
+ const actual = await file.stat();
575
+ if (!actual.isFile() || actual.size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
576
+ throw new Error('资料图片文件已变化');
577
+ const bytes = await file.readFile();
578
+ return { bytes, ...(await inspectBasicInfoImage(bytes, relative, kind)) };
809
579
  }
810
- return {
811
- ...context,
812
- ...(context.expiresAt <= now ? { source: 'anonymous', localDevLaunchToken: undefined, expiresAt: now + 30_000 } : {}),
813
- localDevGrant: index_esm.createMiniProgramLocalDevGrant({
814
- declaredPermissions: context.declaredPermissions ?? {},
815
- runtimePermissions: context.runtimePermissions,
816
- revision: parsed.grant.revision,
817
- eligiblePermissionKeys: context.platforms?.some((platform) => ['windows', 'macos', 'linux'].includes(platform))
818
- ? ['network', 'companion', 'appProtocol']
819
- : ['network', 'appProtocol'],
820
- }),
580
+ finally {
581
+ await file.close();
582
+ }
583
+ }
584
+ /** 逐级校验真实目录,避免保留目录或迁移目录中的符号链接将写入带到项目外。 */
585
+ async function ensureBasicInfoDirectory(rootPath, relative) {
586
+ const root = await fs.realpath(rootPath);
587
+ let current = root;
588
+ for (const part of relative.split('/')) {
589
+ if (!part || part === '.' || part === '..')
590
+ throw new Error('资料目录不合法');
591
+ current = path.join(current, part);
592
+ await fs.mkdir(current).catch((error) => {
593
+ if (error.code !== 'EEXIST')
594
+ throw error;
595
+ });
596
+ const resolved = await fs.realpath(current);
597
+ const within = path.relative(root, resolved);
598
+ if (within.startsWith('..') || path.isAbsolute(within))
599
+ throw new Error('资料目录不能逃逸项目');
600
+ }
601
+ }
602
+
603
+ function trustedProfileUrl(raw) {
604
+ const url = new URL(raw);
605
+ const trusted = ['max-c.com', 'xiaoheihe.cn', 'heybox.com'];
606
+ if (url.protocol !== 'https:' ||
607
+ url.username ||
608
+ url.password ||
609
+ (url.port && url.port !== '443') ||
610
+ !trusted.some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`)))
611
+ throw new Error('线上资料图片 URL 不受信任');
612
+ return url;
613
+ }
614
+ async function downloadImage(raw, fetchImpl) {
615
+ const response = await fetchImpl(trustedProfileUrl(raw), { redirect: 'error', signal: AbortSignal.timeout(15_000) });
616
+ if (!response.ok || !response.body)
617
+ throw new Error('下载线上资料图片失败');
618
+ if (Number(response.headers.get('content-length')) > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
619
+ throw new Error('图片超过 10 MiB');
620
+ const chunks = [];
621
+ let size = 0;
622
+ const reader = response.body.getReader();
623
+ try {
624
+ for (;;) {
625
+ const part = await reader.read();
626
+ if (part.done)
627
+ break;
628
+ size += part.value.length;
629
+ if (size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
630
+ throw new Error('图片超过 10 MiB');
631
+ chunks.push(part.value);
632
+ }
633
+ }
634
+ finally {
635
+ await reader.cancel();
636
+ }
637
+ return Buffer.concat(chunks);
638
+ }
639
+ /** package-last 提交:失败只清理本次新增素材,原配置始终保留。 */
640
+ async function migrateBasicInfo(cwd, detail, miniProgramId, fetchImpl = fetch, force = false) {
641
+ const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
642
+ const heybox = context.packageJson.heybox ?? {};
643
+ const existing = heybox.miniProgramId;
644
+ if (existing && existing !== miniProgramId && !force)
645
+ throw new Error('当前项目已绑定其他小程序,请使用 --force');
646
+ const fields = ['name', 'icon', 'coverImages'];
647
+ const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(heybox, key));
648
+ if (present.length && present.length !== 3)
649
+ throw new Error(`资料配置不完整,请补齐 ${fields.filter((key) => !present.includes(key)).join('、')}`);
650
+ const created = [];
651
+ const temp = `${context.packageJsonPath}.${node_crypto.randomUUID()}.tmp`;
652
+ try {
653
+ let profile = present.length ? runtimePermissionEnv.parseMiniappBasicInfo(heybox) : undefined;
654
+ if (profile) {
655
+ await readBasicInfoSource(context.projectRoot, profile.icon, 'icon');
656
+ for (const cover of profile.coverImages)
657
+ await readBasicInfoSource(context.projectRoot, cover, 'cover');
658
+ if (existing === miniProgramId)
659
+ return { changed: false, miniProgramId };
660
+ }
661
+ else {
662
+ if (detail.mini_program_id !== miniProgramId)
663
+ throw new Error('远端小程序身份不一致');
664
+ const snapshot = detail.published_basic_info;
665
+ if (!snapshot?.version ||
666
+ !snapshot.icon_url ||
667
+ !Array.isArray(snapshot.cover_image_urls) ||
668
+ snapshot.cover_image_urls.length < 1 ||
669
+ snapshot.cover_image_urls.length > 5)
670
+ throw new Error('没有当前正式发布快照,请手工配置 heybox.name/icon/coverImages');
671
+ profile = { name: runtimePermissionEnv.normalizeBasicInfoName(snapshot.name), icon: '', coverImages: [] };
672
+ const entries = [
673
+ { url: snapshot.icon_url, kind: 'icon', label: 'icon' },
674
+ ...snapshot.cover_image_urls.map((url, i) => ({ url, kind: 'cover', label: `cover-${String(i + 1).padStart(2, '0')}` })),
675
+ ];
676
+ for (const entry of entries) {
677
+ const bytes = await downloadImage(entry.url, fetchImpl);
678
+ const image = await inspectRemoteBasicInfoImage(bytes, entry.kind);
679
+ const relative = `assets/heybox/${entry.label}.${image.sha256.slice(0, 12)}.${image.extension}`;
680
+ const target = path.join(context.projectRoot, relative);
681
+ await ensureBasicInfoDirectory(context.projectRoot, 'assets/heybox');
682
+ try {
683
+ await fs.writeFile(target, bytes, { flag: 'wx' });
684
+ created.push(target);
685
+ }
686
+ catch (error) {
687
+ if (error.code !== 'EEXIST' ||
688
+ !(await readBasicInfoSource(context.projectRoot, relative, entry.kind).then((existing) => existing.bytes.equals(bytes), () => false)))
689
+ throw new Error('迁移素材名称冲突,未覆盖已有文件');
690
+ }
691
+ if (entry.kind === 'icon')
692
+ profile.icon = relative;
693
+ else
694
+ profile.coverImages.push(relative);
695
+ }
696
+ }
697
+ // 避免覆盖用户在下载期间修改的配置。
698
+ if ((await fs.readFile(context.packageJsonPath, 'utf8')) !== context.raw)
699
+ throw new Error('package.json 已变化,请重试迁移');
700
+ context.packageJson.heybox = { ...heybox, miniProgramId, ...profile };
701
+ await fs.writeFile(temp, JSON.stringify(context.packageJson, null, context.indent) + context.trailingNewline, { flag: 'wx' });
702
+ await fs.rename(temp, context.packageJsonPath);
703
+ return { changed: true, miniProgramId };
704
+ }
705
+ catch (error) {
706
+ // 若用户同时修改了 package,保留可能已被引用的素材供重试复用。
707
+ if ((await fs.readFile(context.packageJsonPath, 'utf8').catch(() => '')) === context.raw) {
708
+ await Promise.all(created.map((file) => fs.unlink(file).catch(() => { })));
709
+ }
710
+ throw error;
711
+ }
712
+ finally {
713
+ await fs.unlink(temp).catch(() => { });
714
+ }
715
+ }
716
+ async function compareBasicInfo(cwd, detail, fetchImpl = fetch) {
717
+ const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
718
+ const published = detail.published_basic_info;
719
+ let local;
720
+ try {
721
+ local = runtimePermissionEnv.parseMiniappBasicInfo(context.packageJson.heybox ?? {});
722
+ }
723
+ catch {
724
+ return { status: 'unavailable' };
725
+ }
726
+ if (!local || !published?.version)
727
+ return { status: 'unavailable', local, published };
728
+ try {
729
+ const pairs = [
730
+ { local: local.icon, remote: published.icon_url, kind: 'icon' },
731
+ ...local.coverImages.map((p, i) => ({ local: p, remote: published.cover_image_urls[i], kind: 'cover' })),
732
+ ];
733
+ let changed = local.name !== runtimePermissionEnv.normalizeBasicInfoName(published.name) || local.coverImages.length !== published.cover_image_urls.length;
734
+ for (const pair of pairs) {
735
+ if (!pair.remote) {
736
+ changed = true;
737
+ continue;
738
+ }
739
+ const source = await readBasicInfoSource(context.projectRoot, pair.local, pair.kind);
740
+ const bytes = await downloadImage(pair.remote, fetchImpl);
741
+ const remote = await inspectRemoteBasicInfoImage(bytes, pair.kind);
742
+ changed ||= source.sha256 !== remote.sha256;
743
+ }
744
+ return { status: changed ? 'changed' : 'unchanged', local, published };
745
+ }
746
+ catch {
747
+ return { status: 'unavailable', local, published };
748
+ }
749
+ }
750
+
751
+ const CREATE_USER_MINIPROGRAM_UPLOAD_SESSION_API_PATH = '/mall/developer/user_miniprogram/version/upload_session/create';
752
+ const RECORD_USER_MINIPROGRAM_UPLOAD_RESULT_API_PATH = '/mall/developer/user_miniprogram/version/upload_session/record';
753
+ const COMPANION_FINALIZATION_TIMEOUT_MS = 30 * 60_000;
754
+ async function authorizeCompanionUpload(options, runtime = {}) {
755
+ const result = await postUserMiniprogramVersionForm('/mall/developer/user_miniprogram/version/upload_session/companion_authorization', options, { version: options.version, session_id: options.sessionId, relative_paths: options.relativePaths.join(','), artifact_protocol_version: '2' }, runtime);
756
+ if (!result.bucket || !result.region || !Array.isArray(result.keys) || !result.tmp_secret_id || !result.tmp_secret_key || !result.session_token || !(result.expired_time > result.start_time)) {
757
+ throw new Error('Companion 上传凭证响应不完整');
758
+ }
759
+ return result;
760
+ }
761
+ async function precheckUserMiniprogramVersion(options, runtime = {}) {
762
+ return postUserMiniprogramVersionForm(runtimePermissionEnv.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH, options, {
763
+ // 构建前轻预检不携带独立资料;权威准入读取构建 Manifest。
764
+ ...(options.version ? { version: options.version } : {}),
765
+ ...(options.manifest ? { manifest: JSON.stringify(options.manifest) } : {}),
766
+ release_note: options.releaseNote,
767
+ auto_publish: String(options.autoPublish),
768
+ }, runtime);
769
+ }
770
+ async function submitUserMiniprogramAudit(options, runtime = {}) {
771
+ return postUserMiniprogramVersionForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, options, { session_id: options.sessionId, preflight_token: options.preflightToken, artifact_protocol_version: '2' }, runtime);
772
+ }
773
+ async function createUserMiniprogramUploadSession(options, runtime = {}) {
774
+ return postUserMiniprogramVersionForm(CREATE_USER_MINIPROGRAM_UPLOAD_SESSION_API_PATH, options, {
775
+ version: options.version,
776
+ artifact_protocol_version: '2',
777
+ artifact_signature: options.artifactSignature,
778
+ files: JSON.stringify(options.files),
779
+ manifest: JSON.stringify(options.manifest),
780
+ release_note: options.releaseNote,
781
+ auto_publish: String(options.autoPublish),
782
+ }, runtime);
783
+ }
784
+ async function recordUserMiniprogramUploadResult(options, runtime = {}) {
785
+ const fields = {
786
+ version: options.version,
787
+ artifact_protocol_version: '2',
788
+ session_id: options.sessionId,
789
+ files: JSON.stringify(options.files),
821
790
  };
791
+ const deadline = Date.now() + COMPANION_FINALIZATION_TIMEOUT_MS;
792
+ for (;;) {
793
+ const result = await postUserMiniprogramVersionForm(RECORD_USER_MINIPROGRAM_UPLOAD_RESULT_API_PATH, options, fields, runtime);
794
+ if (result.artifact_protocol_version !== 2 || !Array.isArray(result.companion_files)) {
795
+ throw new Error('服务端未返回产物协议 v2 Finalize 状态');
796
+ }
797
+ const failed = result.companion_files.find((file) => file.state === 'failed');
798
+ if (failed)
799
+ throw new Error(failed.error || `Companion 归档验证失败:${failed.relative_path}`);
800
+ if (result.complete)
801
+ return;
802
+ if (Date.now() >= deadline)
803
+ throw new Error('Companion 归档验证超时,请稍后重试');
804
+ await new Promise((resolve) => setTimeout(resolve, Math.max(250, Math.min(result.retry_after_ms || 1000, 5000))));
805
+ }
806
+ }
807
+ async function postUserMiniprogramVersionForm(path, options, fields, runtime) {
808
+ const fetchImpl = runtime.fetchImpl ?? fetch;
809
+ const context = index.createHeyboxOpenPlatformRequestContext(options.session, path, {
810
+ contentType: 'application/x-www-form-urlencoded',
811
+ });
812
+ const body = new URLSearchParams();
813
+ body.set('mini_program_id', options.miniProgramId);
814
+ for (const [key, value] of Object.entries(fields)) {
815
+ body.set(key, value);
816
+ }
817
+ const response = await fetchImpl(index.createHeyboxApiUrl(runtime.baseUrl ?? context.baseUrl, path, context.platformParams), {
818
+ method: 'POST',
819
+ headers: context.headers,
820
+ body: body.toString(),
821
+ });
822
+ const result = await index.readHeyboxApiEnvelope(response, {
823
+ pathWithQuery: path,
824
+ });
825
+ return result ?? {};
826
+ }
827
+
828
+ const DEFAULT_CONCURRENCY = 4;
829
+ async function runUpload(options, runtime = {}) {
830
+ const logger = runtime.logger ?? index.createCliLogger();
831
+ const concurrency = runtime.concurrency ?? DEFAULT_CONCURRENCY;
832
+ const fetchImpl = runtime.fetchImpl ?? fetch;
833
+ const getCDNUploadInfo = runtime.getCDNUploadInfo ?? index.getCDNUploadInfo;
834
+ const getCDNUploadToken = runtime.getCDNUploadToken ?? index.getCDNUploadToken;
835
+ const postCDNUploadCallback = runtime.postCDNUploadCallback ?? index.postCDNUploadCallback;
836
+ const recordUserMiniprogramUploadResult$1 = runtime.recordUserMiniprogramUploadResult ?? recordUserMiniprogramUploadResult;
837
+ const createReadStream = runtime.createReadStream ?? fs$1.createReadStream;
838
+ const cdnBaseUrl = runtime.cdnBaseUrl ?? runtime.baseUrl;
839
+ let createCosClient = runtime.createCosClient;
840
+ if (!createCosClient) {
841
+ const COS = await loadCosConstructor();
842
+ createCosClient = ({ uploadToken }) => createDefaultCosClient(uploadToken, COS);
843
+ }
844
+ const orderedFiles = runtimePermissionEnv.prepareMiniappArtifactFiles(options.files);
845
+ const batches = [false, true].flatMap(companion => chunkUploadFiles(orderedFiles.filter(file => file.relativePath.startsWith('companions/') === companion), runtimePermissionEnv.MINIAPP_UPLOAD_BATCH_SIZE));
846
+ await logger.task(`正在上传 ${orderedFiles.length} 个文件`, async (taskContext) => {
847
+ logger.debug(`上传并发数: ${concurrency}`);
848
+ logger.debug(`上传批次数: ${batches.length}`);
849
+ let completed = 0;
850
+ for (let batchIndex = 0; batchIndex < batches.length; batchIndex += 1) {
851
+ const batch = batches[batchIndex];
852
+ const companion = batch[0].relativePath.startsWith('companions/');
853
+ const grant = companion ? await (runtime.authorizeCompanionUpload ?? authorizeCompanionUpload)({
854
+ session: options.session, miniProgramId: options.miniProgramId, version: options.version, sessionId: options.uploadSessionId, relativePaths: batch.map(file => file.relativePath),
855
+ }, { baseUrl: runtime.baseUrl, fetchImpl }) : undefined;
856
+ logger.debug(`正在处理上传批次 ${batchIndex + 1}/${batches.length},文件数: ${batch.length}`);
857
+ logger.debug('正在获取 CDN 上传信息');
858
+ const fileInfos = createUploadFileInfos(batch);
859
+ const uploadInfo = grant ?? await getCDNUploadInfo({
860
+ session: options.session,
861
+ scope: runtimePermissionEnv.MINIAPP_UPLOAD_SCOPE,
862
+ fileInfos,
863
+ needCache: false,
864
+ }, { baseUrl: cdnBaseUrl, fetchImpl });
865
+ logger.debug(`CDN bucket: ${uploadInfo.bucket}`);
866
+ logger.debug(`CDN region: ${uploadInfo.region}`);
867
+ validateUploadInfoKeys(batch, uploadInfo.keys);
868
+ const indexedFiles = batch.map((file, index) => ({ file, key: uploadInfo.keys[index] }));
869
+ logger.debug('正在获取本批 CDN 上传凭证');
870
+ let uploadToken;
871
+ try {
872
+ uploadToken = grant ? {
873
+ credentials: { tmpSecretId: grant.tmp_secret_id, tmpSecretKey: grant.tmp_secret_key, sessionToken: grant.session_token },
874
+ startTime: grant.start_time, expiredTime: grant.expired_time,
875
+ } : await getCDNUploadToken({
876
+ session: options.session,
877
+ bucket: uploadInfo.bucket,
878
+ keys: indexedFiles.map((item) => item.key),
879
+ mimetypes: indexedFiles.map((item) => item.file.mimeType),
880
+ isMultipartUpload: 0,
881
+ }, { baseUrl: cdnBaseUrl, fetchImpl });
882
+ }
883
+ catch (error) {
884
+ throw new index.CliError(`获取 CDN 上传凭证失败:${readErrorMessage(error)}`);
885
+ }
886
+ const cos = createCosClient({ session: options.session, uploadToken });
887
+ const successfulKeys = [];
888
+ const queue = indexedFiles.slice();
889
+ let firstUploadError;
890
+ const workers = Array.from({ length: Math.min(concurrency, indexedFiles.length) }, async () => {
891
+ while (queue.length > 0 && !firstUploadError) {
892
+ const uploadTask = queue.shift();
893
+ if (!uploadTask) {
894
+ return;
895
+ }
896
+ try {
897
+ await cos.putObject({
898
+ Bucket: uploadInfo.bucket,
899
+ Region: uploadInfo.region,
900
+ Key: uploadTask.key,
901
+ Body: createReadStream(uploadTask.file.absolutePath),
902
+ ContentLength: uploadTask.file.size,
903
+ ContentType: uploadTask.file.mimeType,
904
+ ...(companion ? { Headers: { 'x-cos-forbid-overwrite': 'true' } } : {}),
905
+ }).catch(error => {
906
+ if (companion && isExistingCompanionObject(error))
907
+ return;
908
+ throw error;
909
+ });
910
+ successfulKeys.push(uploadTask.key);
911
+ completed += 1;
912
+ taskContext.update(`正在上传 ${completed}/${orderedFiles.length} 个文件`);
913
+ logger.debug(`[${String(completed).padStart(2)}/${orderedFiles.length}] ok ${uploadTask.file.relativePath} (${formatSize(uploadTask.file.size)})`);
914
+ }
915
+ catch (error) {
916
+ completed += 1;
917
+ const message = readErrorMessage(error);
918
+ logger.debug(`[${String(completed).padStart(2)}/${orderedFiles.length}] error ${uploadTask.file.relativePath} -> ${message}`);
919
+ firstUploadError ??= new index.CliError(`上传文件失败:${uploadTask.file.relativePath} -> ${message}`, readVerboseUploadError(uploadTask.file.relativePath, error));
920
+ }
921
+ }
922
+ });
923
+ await Promise.all(workers);
924
+ if (successfulKeys.length > 0) {
925
+ logger.debug('正在确认 CDN 上传结果');
926
+ if (!companion)
927
+ await postCDNUploadCallback({ session: options.session, keys: successfulKeys, isFinished: true }, { baseUrl: cdnBaseUrl, fetchImpl });
928
+ await recordUserMiniprogramUploadResult$1({
929
+ session: options.session,
930
+ miniProgramId: options.miniProgramId,
931
+ version: options.version,
932
+ sessionId: options.uploadSessionId,
933
+ files: indexedFiles
934
+ .filter((item) => successfulKeys.includes(item.key))
935
+ .map((item) => ({ path: item.file.relativePath, size: item.file.size, sha256: item.file.sha256 })),
936
+ }, { baseUrl: runtime.baseUrl, fetchImpl });
937
+ }
938
+ if (firstUploadError) {
939
+ throw firstUploadError;
940
+ }
941
+ }
942
+ }, { successText: `已上传 ${orderedFiles.length} 个文件` });
943
+ }
944
+ function chunkUploadFiles(files, batchSize) {
945
+ const batches = [];
946
+ for (let index = 0; index < files.length; index += batchSize) {
947
+ batches.push(files.slice(index, index + batchSize));
948
+ }
949
+ return batches;
822
950
  }
823
- function shouldSkipMiniappPlatformCsp(_runtimePermissions) {
824
- return false;
951
+ function isExistingCompanionObject(error) {
952
+ if (!error || typeof error !== 'object')
953
+ return false;
954
+ const value = error;
955
+ return Number(value.statusCode) === 409 && value.code === 'ObjectAlreadyExists';
825
956
  }
826
- const DEFAULT_PERMISSION_STATE = {
827
- networkRequest: {
828
- status: 'disabled',
829
- useOfficialDomain: false,
830
- },
831
- };
832
- function createBrowserDevPermissionState(context) {
833
- const parsed = index_esm.parseMiniProgramRuntimePermissions(context.localDevGrant
834
- ? index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
835
- localDevGrant: context.localDevGrant }).runtimePermissions
836
- : context.runtimePermissions);
837
- const networkRequest = parsed.permissions.network;
838
- return parsed.valid && networkRequest
839
- ? {
840
- networkRequest: {
841
- status: networkRequest.status,
842
- useOfficialDomain: networkRequest.config.useOfficialDomain === true,
843
- },
844
- }
845
- : cloneDefaultPermissionState();
957
+ function createUploadFileInfos(files) {
958
+ return files.map((file) => ({
959
+ name: file.relativePath.split('/').pop() ?? file.relativePath,
960
+ mimetype: file.mimeType,
961
+ fsize: file.size,
962
+ path: file.key,
963
+ }));
846
964
  }
847
- /** Mobile Dev Session 使用本地声明与平台基线,不读取 Browser 模拟权限状态。 */
848
- function createMobileDevSessionRuntimePermissions(context) {
849
- if (context.source !== 'remote') {
850
- return { schema_version: 1, entries: [] };
965
+ function validateUploadInfoKeys(files, keys) {
966
+ if (keys.length !== files.length) {
967
+ throw new index.CliError(`CDN 上传接口返回 key 数量异常:期望 ${files.length},实际 ${keys.length}`);
851
968
  }
852
- // 历史内部调用没有本地声明,沿用旧快照适配;新 CLI 始终显式提供声明(可为空)。
853
- if (context.declaredPermissions === undefined) {
854
- const state = createBrowserDevPermissionState(context);
855
- return createDevRuntimePermissions(context.runtimePermissions, state, state.networkRequest.useOfficialDomain);
969
+ for (let index$1 = 0; index$1 < files.length; index$1 += 1) {
970
+ const expectedKey = files[index$1].key;
971
+ const actualKey = keys[index$1];
972
+ if (actualKey !== expectedKey) {
973
+ throw new index.CliError(`CDN 上传接口返回 key 异常:${files[index$1].relativePath}`, [`CDN 上传接口返回 key 异常:${files[index$1].relativePath}`, `expected: ${expectedKey}`, `actual: ${actualKey}`].join('\n'));
974
+ }
856
975
  }
857
- return index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions, runtimePermissions: context.runtimePermissions }).runtimePermissions;
858
976
  }
859
- function cloneDefaultPermissionState() {
977
+ function createDefaultCosClient(uploadToken, COS) {
978
+ const cos = new COS({
979
+ getAuthorization(_input, callback) {
980
+ callback({
981
+ TmpSecretId: uploadToken.credentials.tmpSecretId,
982
+ TmpSecretKey: uploadToken.credentials.tmpSecretKey,
983
+ XCosSecurityToken: uploadToken.credentials.sessionToken,
984
+ StartTime: uploadToken.startTime,
985
+ ExpiredTime: uploadToken.expiredTime,
986
+ });
987
+ },
988
+ });
860
989
  return {
861
- networkRequest: { ...DEFAULT_PERMISSION_STATE.networkRequest },
990
+ putObject(params) {
991
+ return new Promise((resolve, reject) => {
992
+ cos.putObject(params, (err, result) => {
993
+ if (err) {
994
+ reject(err);
995
+ return;
996
+ }
997
+ resolve(result);
998
+ });
999
+ });
1000
+ },
862
1001
  };
863
1002
  }
864
- function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
865
- const parsed = index_esm.parseMiniProgramRuntimePermissions(snapshot);
866
- if (!parsed.valid) {
867
- return { schema_version: 1, entries: [] };
1003
+ async function loadCosConstructor() {
1004
+ const cosModule = await Promise.resolve().then(function () { return require('./index-C91c2NGN.cjs'); }).then(function (n) { return n.index; });
1005
+ return cosModule.default;
1006
+ }
1007
+ function formatSize(bytes) {
1008
+ if (bytes < 1024) {
1009
+ return `${bytes} B`;
868
1010
  }
869
- const entries = [];
870
- for (const key of index_esm.MINI_PROGRAM_PERMISSION_KEYS) {
871
- const entry = parsed.permissions[key];
872
- if (!entry)
873
- continue;
874
- entries.push(key === 'network'
875
- ? {
876
- key,
877
- status: state.networkRequest.status,
878
- config: { useOfficialDomain },
879
- }
880
- : key === 'user_game_data'
881
- ? {
882
- key,
883
- status: entry.status,
884
- // 精确资源清单是 snapshot 的合法必需项:浏览器模拟只调整开关,不能丢掉 Manifest 声明。
885
- config: { resources: entry.config.resources },
886
- }
887
- : {
888
- key,
889
- status: entry.status,
890
- config: {},
891
- });
1011
+ if (bytes < 1024 * 1024) {
1012
+ return `${(bytes / 1024).toFixed(1)} KB`;
892
1013
  }
893
- const revision = isPlainRecord(snapshot) && typeof snapshot.revision === 'number' && Number.isInteger(snapshot.revision) && snapshot.revision >= 0
894
- ? snapshot.revision
895
- : undefined;
896
- return {
897
- schema_version: 1,
898
- ...(revision === undefined ? {} : { revision }),
899
- entries,
900
- };
1014
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
901
1015
  }
902
- function isPlainRecord(value) {
903
- return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
1016
+ function readErrorMessage(error) {
1017
+ if (error instanceof Error && error.message) {
1018
+ return error.message;
1019
+ }
1020
+ if (isRecord(error)) {
1021
+ const primary = readStringField(error, ['message', 'Message', 'errorMessage', 'msg']);
1022
+ const code = readStringField(error, ['code', 'Code', 'errorCode', 'name']);
1023
+ const statusCode = readStringField(error, ['statusCode']);
1024
+ return [code, statusCode, primary].filter(Boolean).join(' ') || JSON.stringify(error);
1025
+ }
1026
+ return String(error);
1027
+ }
1028
+ function readVerboseUploadError(relativePath, error) {
1029
+ return [`上传文件失败:${relativePath}`, `原始错误:${readErrorMessage(error)}`].join('\n');
1030
+ }
1031
+ function readStringField(record, fields) {
1032
+ for (const field of fields) {
1033
+ const value = record[field];
1034
+ if (typeof value === 'string' && value.trim()) {
1035
+ return value.trim();
1036
+ }
1037
+ if (typeof value === 'number') {
1038
+ return String(value);
1039
+ }
1040
+ }
1041
+ return '';
1042
+ }
1043
+ function isRecord(value) {
1044
+ return Object.prototype.toString.call(value) === '[object Object]';
904
1045
  }
905
1046
 
906
1047
  /** 发布提示使用显式声明与远端主体批准策略,不消费本地调试授权。 */
@@ -921,11 +1062,6 @@ function getUnapprovedPermissionWarning(local, approvals, partyType) {
921
1062
  return missing.length ? `以下本地声明权限线上未批准,发布后不可用:${missing.join('、')}。本地调试可用不代表线上已批准。` : undefined;
922
1063
  }
923
1064
 
924
- const SUPPORTED_PACKAGE_MANAGERS = [
925
- { name: 'pnpm', lockfile: 'pnpm-lock.yaml' },
926
- { name: 'yarn', lockfile: 'yarn.lock' },
927
- { name: 'npm', lockfile: 'package-lock.json' },
928
- ];
929
1065
  const MIME_BY_EXT = {
930
1066
  '.css': 'text/css',
931
1067
  '.gif': 'image/gif',
@@ -959,11 +1095,12 @@ async function runDeployCommand(options, runtime = {}) {
959
1095
  if (typeof miniProgramId !== 'string' || !miniProgramId.trim()) {
960
1096
  throw new Error('未在 package.json 中找到 heybox.miniProgramId,请先配置 mini program id');
961
1097
  }
962
- if (runtime.expectedProject && (miniProgramId.trim() !== runtime.expectedProject.miniProgramId ||
963
- packageJson.version !== runtime.expectedProject.version)) {
1098
+ if (runtime.expectedProject &&
1099
+ (miniProgramId.trim() !== runtime.expectedProject.miniProgramId || packageJson.version !== runtime.expectedProject.version)) {
964
1100
  throw new index.CliError('项目 ID 或版本已变化,请刷新上传发布面板后重新核对');
965
1101
  }
966
1102
  const declaredPlatforms = runtimePermissionEnv.readMiniappPlatformsFromPackageJson(projectRoot);
1103
+ logger.info(`${getPcAdaptationSuggestion(declaredPlatforms)} PC 适配:${PC_ADAPTATION_GUIDE_URL} 客户端下载:${PC_CLIENT_DOWNLOAD_URL}`);
967
1104
  const declaredWindow = runtimePermissionEnv.readMiniappWindowFromPackageJson(projectRoot);
968
1105
  let declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
969
1106
  const declaredCategory = runtimePermissionEnv.readMiniappCategoryFromPackageJson(projectRoot);
@@ -974,7 +1111,10 @@ async function runDeployCommand(options, runtime = {}) {
974
1111
  const deploy = async () => {
975
1112
  if (!options.skipGameBindingGuide) {
976
1113
  await gameBindingGuide.guideGameBindings(gameBindingGuide.createGameBindingsBackend(projectRoot, { session, fetchImpl: runtime.fetchImpl }), {
977
- isTTY: runtime.isTTY, stdin: runtime.stdin, stderr: runtime.stderr, question: runtime.gameBindingQuestion,
1114
+ isTTY: runtime.isTTY,
1115
+ stdin: runtime.stdin,
1116
+ stderr: runtime.stderr,
1117
+ question: runtime.gameBindingQuestion,
978
1118
  });
979
1119
  packageJson = await readPackageJson(projectRoot);
980
1120
  declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
@@ -1023,7 +1163,8 @@ async function runDeployCommand(options, runtime = {}) {
1023
1163
  firstParty = detail.party_type === 'first_party';
1024
1164
  skipPlatformCsp = shouldSkipMiniappPlatformCsp(effectivePermissions);
1025
1165
  networkPolicy = effectivePermissions.entries.some((entry) => entry.key === 'network' && entry.status === 'enabled')
1026
- ? detail.network_policy : undefined;
1166
+ ? detail.network_policy
1167
+ : undefined;
1027
1168
  const permissionWarning = getUnapprovedPermissionWarning(localPermissions, detail.runtime_permissions, detail.party_type);
1028
1169
  if (permissionWarning)
1029
1170
  logger.warn(permissionWarning);
@@ -1196,7 +1337,7 @@ async function runDeployCommand(options, runtime = {}) {
1196
1337
  }
1197
1338
  try {
1198
1339
  const submitOptions = { session, miniProgramId, sessionId: uploadSessionId, preflightToken };
1199
- submitAuditResult = await logger.task('正在提交审核', () => (runtime.submitUserMiniprogramAudit ?? submitUserMiniprogramAudit$1)(submitOptions, {
1340
+ submitAuditResult = await logger.task('正在提交审核', () => (runtime.submitUserMiniprogramAudit ?? submitUserMiniprogramAudit)(submitOptions, {
1200
1341
  baseUrl: apiBaseUrl,
1201
1342
  fetchImpl: runtime.fetchImpl,
1202
1343
  }), { successText: '审核提交完成' });
@@ -1221,7 +1362,7 @@ async function runDeployCommand(options, runtime = {}) {
1221
1362
  version,
1222
1363
  };
1223
1364
  };
1224
- return (runtime.withDeployLock ?? index.withDeployLock)({ apiBaseUrl, miniProgramId, version: uploadVersion }, deploy);
1365
+ return (runtime.withDeployLock ?? index.withDeployLock)({ apiBaseUrl, miniProgramId, version: uploadVersion }, () => withProjectArtifactLock(projectRoot, deploy));
1225
1366
  }
1226
1367
  function printDeploySuccess(options) {
1227
1368
  options.logger.success(`提交审核成功:${options.miniProgramId} ${options.version}`);
@@ -1285,77 +1426,19 @@ async function maybePromptReleaseNote(runtime) {
1285
1426
  async function runVersionPrecheck(options, runtime, apiBaseUrl, projectRoot, logger) {
1286
1427
  try {
1287
1428
  const label = options.version ?? '';
1288
- return await logger.task(`正在预检版本 ${label}`, () => (runtime.precheckUserMiniprogramVersion ?? precheckUserMiniprogramVersion$1)(options, {
1429
+ return await logger.task(`正在预检版本 ${label}`, () => (runtime.precheckUserMiniprogramVersion ?? precheckUserMiniprogramVersion)(options, {
1289
1430
  baseUrl: apiBaseUrl,
1290
1431
  fetchImpl: runtime.fetchImpl,
1291
1432
  }), { successText: `版本 ${label} 预检通过` });
1292
1433
  }
1293
1434
  catch (error) {
1294
- throw translateHeyboxDeployError(error, { projectRoot, stage: 'precheck', version: options.version ?? '', workbench: Boolean(runtime.expectedProject) });
1295
- }
1296
- }
1297
- function detectPackageManager(projectRoot) {
1298
- for (const candidate of SUPPORTED_PACKAGE_MANAGERS) {
1299
- if (fs$1.existsSync(path.join(projectRoot, candidate.lockfile))) {
1300
- return candidate.name;
1301
- }
1302
- }
1303
- return 'npm';
1304
- }
1305
- async function runBuildScript(pm, cwd, spawnImpl, options) {
1306
- const buildScript = await readProjectBuildScript(cwd);
1307
- await new Promise((resolve, reject) => {
1308
- const pipeStdoutToStderr = options.outputMode === 'stderr';
1309
- const buildArgs = createBuildArgs(pm, options.mode, buildScript);
1310
- const isWindows = options.platform === 'win32';
1311
- const [executable, args] = isWindows ? createWindowsBuildCommand(pm, buildArgs) : [pm, buildArgs];
1312
- const child = spawnImpl(executable, args, {
1313
- cwd,
1314
- env: { ...process.env, ...options.env },
1315
- ...(isWindows ? { shell: false, windowsVerbatimArguments: true } : {}),
1316
- stdio: pipeStdoutToStderr ? ['inherit', 'pipe', 'inherit'] : 'inherit',
1317
- });
1318
- if (pipeStdoutToStderr) {
1319
- child.stdout?.on('data', (chunk) => {
1320
- (options.stderr ?? process.stderr).write(chunk);
1321
- });
1322
- }
1323
- child.on('error', reject);
1324
- child.on('exit', (code) => {
1325
- if (code === 0) {
1326
- resolve();
1327
- }
1328
- else {
1329
- reject(new Error(`${pm} run build exited with code ${code ?? 'null'}`));
1330
- }
1435
+ throw translateHeyboxDeployError(error, {
1436
+ projectRoot,
1437
+ stage: 'precheck',
1438
+ version: options.version ?? '',
1439
+ workbench: Boolean(runtime.expectedProject),
1331
1440
  });
1332
- });
1333
- }
1334
- function createWindowsBuildCommand(pm, buildArgs) {
1335
- const command = `${pm}.cmd ${buildArgs.map(escapeWindowsCommandArgument).join(' ')}`;
1336
- return ['cmd.exe', ['/d', '/s', '/c', `"${command}"`]];
1337
- }
1338
- function validateBuildMode(mode, platform) {
1339
- if (platform === 'win32' && mode && !/^[A-Za-z0-9._-]+$/.test(mode)) {
1340
- throw new Error('Windows 下 HB_SDK_ENV 仅支持字母、数字、点、下划线和连字符');
1341
- }
1342
- return mode;
1343
- }
1344
- function escapeWindowsCommandArgument(argument) {
1345
- return `"${argument}"`;
1346
- }
1347
- async function readProjectBuildScript(projectRoot) {
1348
- try {
1349
- const packageJson = JSON.parse(await fs.readFile(path.join(projectRoot, 'package.json'), 'utf8'));
1350
- return typeof packageJson.scripts?.build === 'string' ? packageJson.scripts.build : '';
1351
1441
  }
1352
- catch {
1353
- return '';
1354
- }
1355
- }
1356
- function createBuildArgs(pm, mode, buildScript) {
1357
- const modeOption = /\bhb-sdk\s+build\b/.test(buildScript) ? '--env' : '--mode';
1358
- return ['run', 'build', ...(mode ? [...(pm === 'npm' ? ['--'] : []), modeOption, mode] : [])];
1359
1442
  }
1360
1443
  function inferMimeType(fileName) {
1361
1444
  return MIME_BY_EXT[path.extname(fileName).toLowerCase()] || 'application/octet-stream';
@@ -1433,12 +1516,48 @@ function suggestNextPatchVersion(version) {
1433
1516
  return `${matched[1]}.${matched[2]}.${Number(matched[3]) + 1}`;
1434
1517
  }
1435
1518
 
1519
+ const MAX_POST_ID = 9223372036854775807n;
1520
+ function isPostId(value) {
1521
+ return /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= MAX_POST_ID;
1522
+ }
1523
+ /** 只提取官方链接里的帖子标识,编码 ID 由后端解码校验。 */
1524
+ function parsePostReference(value) {
1525
+ const input = value.trim();
1526
+ if (isPostId(input))
1527
+ return input;
1528
+ let url;
1529
+ try {
1530
+ url = new URL(input);
1531
+ }
1532
+ catch {
1533
+ throw new Error('请提供有效的帖子 ID 或小黑盒帖子链接。链接请用英文双引号包裹,例如 npm exec hb-sdk -- remote post preview "https://api.xiaoheihe.cn/v3/bbs/app/api/web/share?link_id=43ef72d469fb&h_src=app",并去掉 Markdown 的 [文字](链接) 格式');
1534
+ }
1535
+ if (!['https:', 'http:'].includes(url.protocol) ||
1536
+ url.username ||
1537
+ url.password ||
1538
+ url.port ||
1539
+ !['api.xiaoheihe.cn', 'www.xiaoheihe.cn', 'web.xiaoheihe.cn', 'heybox.debugmode.cn', 'web.debugmode.cn'].includes(url.hostname)) {
1540
+ throw new Error('请提供小黑盒官方帖子链接');
1541
+ }
1542
+ const reference = url.pathname === '/v3/bbs/app/api/web/share' ? url.searchParams.get('link_id') : /^\/app\/bbs\/link\/([a-zA-Z0-9]+)\/?$/.exec(url.pathname)?.[1];
1543
+ if (!reference)
1544
+ throw new Error('帖子链接中没有有效的帖子 ID');
1545
+ if (isPostId(reference) || /^[0-9a-f]{5,20}$/.test(reference))
1546
+ return reference;
1547
+ throw new Error('帖子链接中的 ID 格式无效,请重新复制帖子链接');
1548
+ }
1549
+
1436
1550
  async function runRemoteCommand(options, runtime = {}) {
1437
1551
  if (options.command === 'deploy') {
1438
1552
  return runRemoteDeployCommand(options, runtime);
1439
1553
  }
1440
1554
  const context = await createRemoteCommandContext(options, runtime);
1441
1555
  switch (options.command) {
1556
+ case 'post:get':
1557
+ case 'post:preview':
1558
+ case 'post:bind':
1559
+ case 'post:unbind':
1560
+ return remotePostBinding(options, context, runtime);
1442
1561
  case 'permission:list':
1443
1562
  return remotePermissionList(options, context, runtime);
1444
1563
  case 'permission:apply':
@@ -1555,6 +1674,13 @@ async function createRemoteCommandContext(options, runtime) {
1555
1674
  }
1556
1675
  function adaptRemoteApiClient(api) {
1557
1676
  return {
1677
+ getPostBinding: (miniProgramId) => api.getPostBinding({ mini_program_id: miniProgramId }),
1678
+ previewPostBinding: ({ miniProgramId, postId }) => api.previewPostBinding({ mini_program_id: miniProgramId, post_id: postId }),
1679
+ setPostBinding: ({ miniProgramId, postId, expectedRevision }) => api.setPostBinding({
1680
+ mini_program_id: miniProgramId,
1681
+ post_id: postId,
1682
+ expected_revision: expectedRevision,
1683
+ }),
1558
1684
  listPermissionApplications: (miniProgramId) => api.listPermissionApplications({ mini_program_id: miniProgramId }),
1559
1685
  submitPermissionApplication: ({ miniProgramId, key, reason, domains }) => api.submitPermissionApplication({ mini_program_id: miniProgramId, permission_key: key, reason, domains }),
1560
1686
  accessStatus: () => api.getDeveloperAccessStatus(),
@@ -1721,6 +1847,44 @@ async function remoteBind(options, context, runtime) {
1721
1847
  }
1722
1848
  return finishRemoteCommand(options, runtime, output);
1723
1849
  }
1850
+ async function remotePostBinding(options, context, runtime) {
1851
+ const miniProgramId = requireBinding(context);
1852
+ if (options.command === 'post:get') {
1853
+ const result = await context.api.getPostBinding(miniProgramId);
1854
+ if (!options.json) {
1855
+ if (result.post_id) {
1856
+ const post = await context.api.previewPostBinding({ miniProgramId, postId: result.post_id });
1857
+ context.logger.info(`标题:${post.title || '无标题帖子'}\n作者:${post.author_name}`);
1858
+ }
1859
+ else {
1860
+ context.logger.info('当前小程序未关联帖子');
1861
+ }
1862
+ }
1863
+ return finishRemoteCommand(options, runtime, {
1864
+ changed: false,
1865
+ miniProgramId,
1866
+ binding: { postId: result.post_id },
1867
+ });
1868
+ }
1869
+ const postId = options.command === 'post:unbind' ? '' : parsePostReference(requireNonEmpty(options.postId, '必须传入帖子 ID 或链接'));
1870
+ if (options.command === 'post:preview') {
1871
+ const result = await context.api.previewPostBinding({ miniProgramId, postId });
1872
+ if (!options.json) {
1873
+ context.logger.info(`标题:${result.title || '无标题帖子'}\n作者:${result.author_name}`);
1874
+ }
1875
+ return finishRemoteCommand(options, runtime, { changed: false, miniProgramId, post: toCamelCaseDeep(result) });
1876
+ }
1877
+ await assertBoundMiniProgramEntityMatchesCurrent(context, miniProgramId);
1878
+ const binding = await context.api.getPostBinding(miniProgramId);
1879
+ const expectedRevision = binding.revision;
1880
+ if (typeof expectedRevision !== 'string' || !/^(0|[1-9]\d{0,18})$/.test(expectedRevision) || BigInt(expectedRevision) >= 9223372036854775807n) {
1881
+ throw new Error('当前关联信息无效,请稍后重试');
1882
+ }
1883
+ const result = await context.api.setPostBinding({ miniProgramId, postId, expectedRevision });
1884
+ if (!options.json)
1885
+ context.logger.success(postId ? `已关联帖子:${postId}` : '已解除关联');
1886
+ return finishRemoteCommand(options, runtime, { changed: true, miniProgramId, binding: { postId: result.post_id } });
1887
+ }
1724
1888
  /** 工作台扫码只读取版本和协议,复用认证与项目绑定,避免图片比对和详情输出。 */
1725
1889
  async function readRemoteMiniProgramPreview(options, runtime = {}) {
1726
1890
  const context = await createRemoteCommandContext({ env: options.env }, runtime);
@@ -1751,7 +1915,20 @@ async function remoteInfo(options, context, runtime) {
1751
1915
  const removed = currentBindApps.filter((item) => !localIDs.has(item.appid));
1752
1916
  const bindings = { local, current: currentBindApps, added, removed };
1753
1917
  const basicInfo = await compareBasicInfo(context.packageJson.projectRoot, detail, runtime.fetchImpl);
1754
- 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 };
1918
+ const output = {
1919
+ changed: false,
1920
+ miniProgramId,
1921
+ detail: toCamelCaseDeep(detail),
1922
+ permissions: permissionViews,
1923
+ permissionSources: {
1924
+ localDeclaration: localPermissions.permissions ?? null,
1925
+ onlineManifest: detail.manifest ?? null,
1926
+ onlineRuntimeSnapshot: detail.effective_runtime_permissions ?? null,
1927
+ platformApprovals: detail.runtime_permissions ?? null,
1928
+ },
1929
+ bindings,
1930
+ basicInfo,
1931
+ };
1755
1932
  if (!options.json)
1756
1933
  context.logger.info(`版本资料:${basicInfo.status}`);
1757
1934
  if (!options.json) {
@@ -1798,11 +1975,11 @@ async function remotePermissionList(options, context, runtime) {
1798
1975
  const localPermissions = runtimePermissionEnv.readMiniappPermissionsFromPackageJson(context.packageJson.projectRoot, runtimePermissionEnv.resolveMiniappSdkVersion());
1799
1976
  const { views } = runtimePermissionEnv.composeMiniappRuntimePermissions(localPermissions, result.runtime_permissions, detail.party_type);
1800
1977
  if (!options.json) {
1801
- for (const view of views.filter(entry => entry.access === 'platform-approval')) {
1802
- const item = result.items.find(entry => entry.permission_key === view.key);
1978
+ for (const view of views.filter((entry) => entry.access === 'platform-approval')) {
1979
+ const item = result.items.find((entry) => entry.permission_key === view.key);
1803
1980
  const application = item?.latest_application;
1804
- const name = item?.permission_name ?? index_esm.MINI_PROGRAM_PERMISSION_CATALOG.find(entry => entry.key === view.key)?.name ?? view.key;
1805
- const approval = result.runtime_permissions?.entries?.find(entry => entry.key === view.key);
1981
+ const name = item?.permission_name ?? index_esm.MINI_PROGRAM_PERMISSION_CATALOG.find((entry) => entry.key === view.key)?.name ?? view.key;
1982
+ const approval = result.runtime_permissions?.entries?.find((entry) => entry.key === view.key);
1806
1983
  const source = view.approvalSource === 'first-party' ? ' 批准来源=第一方自动批准' : '';
1807
1984
  context.logger.info(`${view.key} (${name}) 原始审批=${approval?.status ?? 'disabled'}${source} 本地生效=${view.effective ? 'enabled' : 'disabled'} 最近申请=${application?.status ?? '未申请'}`);
1808
1985
  if (application?.application_id)
@@ -1811,7 +1988,13 @@ async function remotePermissionList(options, context, runtime) {
1811
1988
  context.logger.info(`审核意见:${application.review_remark}`);
1812
1989
  }
1813
1990
  }
1814
- return finishRemoteCommand(options, runtime, { changed: false, miniProgramId, items: toCamelCaseDeep(result.items), runtimePermissions: toCamelCaseDeep(result.runtime_permissions), permissions: views });
1991
+ return finishRemoteCommand(options, runtime, {
1992
+ changed: false,
1993
+ miniProgramId,
1994
+ items: toCamelCaseDeep(result.items),
1995
+ runtimePermissions: toCamelCaseDeep(result.runtime_permissions),
1996
+ permissions: views,
1997
+ });
1815
1998
  }
1816
1999
  async function remotePermissionApply(options, context, runtime) {
1817
2000
  const miniProgramId = requireBinding(context);
@@ -1827,10 +2010,15 @@ async function remotePermissionApply(options, context, runtime) {
1827
2010
  throw new Error('申请理由不能超过 500 字');
1828
2011
  let domains;
1829
2012
  if (key === 'network') {
1830
- const values = [...new Set(requireNonEmpty(options.domains, 'network 申请必须传 --domains,多个域名用逗号分隔').split(',').map(value => value.trim()).filter(Boolean))];
2013
+ const values = [
2014
+ ...new Set(requireNonEmpty(options.domains, 'network 申请必须传 --domains,多个域名用逗号分隔')
2015
+ .split(',')
2016
+ .map((value) => value.trim())
2017
+ .filter(Boolean)),
2018
+ ];
1831
2019
  if (!values.length || values.length > 20)
1832
2020
  throw new Error('请填写 1 至 20 个访问域名');
1833
- if (values.some(value => /[\s/:?#@*\\]/.test(value)))
2021
+ if (values.some((value) => /[\s/:?#@*\\]/.test(value)))
1834
2022
  throw new Error('请填写域名,不含协议、端口、路径或通配符');
1835
2023
  domains = values.join(',');
1836
2024
  }
@@ -2296,9 +2484,7 @@ async function confirmDangerousRemoteChange(options, runtime, logger, context) {
2296
2484
  throw new Error(`非交互环境执行 hb-sdk remote ${context.operation} 必须传 --yes`);
2297
2485
  }
2298
2486
  const confirmation = `${context.permissionWarning ? `${context.permissionWarning}\n` : ''}确认执行 ${context.operation}?`;
2299
- const accepted = runtime.promptConfirm
2300
- ? await runtime.promptConfirm(confirmation)
2301
- : await promptConfirm(`${confirmation}输入 yes 继续: `, runtime);
2487
+ const accepted = runtime.promptConfirm ? await runtime.promptConfirm(confirmation) : await promptConfirm(`${confirmation}输入 yes 继续: `, runtime);
2302
2488
  if (!accepted) {
2303
2489
  throw new Error('已取消操作');
2304
2490
  }
@@ -2330,19 +2516,35 @@ function printMiniProgramDetail(logger, detail, permissionViews, bindings) {
2330
2516
  const manifest = detail.manifest && typeof detail.manifest === 'object' ? detail.manifest : undefined;
2331
2517
  let online;
2332
2518
  try {
2333
- online = manifest ? runtimePermissionEnv.parseMiniappPermissions(manifest.permissions, { present: Object.hasOwn(manifest, 'permissions'), sdkVersion: typeof detail.sdk_version === 'string' ? detail.sdk_version : '0.8.0' }) : undefined;
2519
+ online = manifest
2520
+ ? runtimePermissionEnv.parseMiniappPermissions(manifest.permissions, {
2521
+ present: Object.hasOwn(manifest, 'permissions'),
2522
+ sdkVersion: typeof detail.sdk_version === 'string' ? detail.sdk_version : '0.8.0',
2523
+ })
2524
+ : undefined;
2525
+ }
2526
+ catch {
2527
+ /* 缺失或未知声明保持未知,不能推断线上可用。 */
2334
2528
  }
2335
- catch { /* 缺失或未知声明保持未知,不能推断线上可用。 */ }
2336
2529
  const publishedRuntime = index_esm.parseMiniProgramRuntimePermissions(detail.effective_runtime_permissions);
2337
2530
  let differs = false;
2338
2531
  for (const view of permissionViews) {
2339
2532
  const published = online ? online.permissions?.[view.key]?.enabled === true : undefined;
2340
2533
  const requested = online?.permissions?.[view.key];
2341
- const changed = published !== undefined && (published !== view.declared ||
2342
- (view.key === 'network' && published && view.requestedConfig?.useOfficialDomain !== (requested && 'useOfficialDomain' in requested ? requested.useOfficialDomain : undefined)));
2534
+ const changed = published !== undefined &&
2535
+ (published !== view.declared ||
2536
+ (view.key === 'network' &&
2537
+ published &&
2538
+ view.requestedConfig?.useOfficialDomain !== (requested && 'useOfficialDomain' in requested ? requested.useOfficialDomain : undefined)));
2343
2539
  differs ||= changed;
2344
- const approval = view.access === 'platform-approval' ? (view.approvalSource === 'first-party' ? '第一方自动批准' : view.approved ? '已批准' : '未批准') : '无需审批';
2345
- logger.info(` ${view.key}: 本地声明=${view.declared ? '是' : '否'} 线上版本声明=${published === undefined ? '未知' : published ? '是' : '否'} 平台批准=${approval} 线上快照=${publishedRuntime.valid ? publishedRuntime.permissions[view.key]?.status ?? '缺少条目' : '未知'}${changed ? ' [不一致]' : ''}`);
2540
+ const approval = view.access === 'platform-approval'
2541
+ ? view.approvalSource === 'first-party'
2542
+ ? '第一方自动批准'
2543
+ : view.approved
2544
+ ? '已批准'
2545
+ : '未批准'
2546
+ : '无需审批';
2547
+ logger.info(` ${view.key}: 本地声明=${view.declared ? '是' : '否'} 线上版本声明=${published === undefined ? '未知' : published ? '是' : '否'} 平台批准=${approval} 线上快照=${publishedRuntime.valid ? (publishedRuntime.permissions[view.key]?.status ?? '缺少条目') : '未知'}${changed ? ' [不一致]' : ''}`);
2346
2548
  }
2347
2549
  if (differs)
2348
2550
  logger.warn('本地声明与线上版本不一致;本地调试结果不代表线上生效,需发布包含声明的新版本。');
@@ -2441,14 +2643,22 @@ var remote = /*#__PURE__*/Object.freeze({
2441
2643
  runRemoteCommand: runRemoteCommand
2442
2644
  });
2443
2645
 
2646
+ exports.PC_ONBOARDING_PATH = PC_ONBOARDING_PATH;
2647
+ exports.computeMiniappArtifactReceipt = computeMiniappArtifactReceipt;
2444
2648
  exports.createBrowserDevPermissionState = createBrowserDevPermissionState;
2445
2649
  exports.createLocalDevLaunchToken = createLocalDevLaunchToken;
2446
2650
  exports.createMobileDevSessionRuntimePermissions = createMobileDevSessionRuntimePermissions;
2651
+ exports.detectPackageManager = detectPackageManager;
2447
2652
  exports.getBoundMiniProgram = getBoundMiniProgram;
2653
+ exports.getPcAdaptationSuggestion = getPcAdaptationSuggestion;
2448
2654
  exports.migrateBasicInfo = migrateBasicInfo;
2449
2655
  exports.readRemoteMiniProgramPreview = readRemoteMiniProgramPreview;
2450
2656
  exports.remote = remote;
2451
2657
  exports.resolveBrowserFakeContext = resolveBrowserFakeContext;
2658
+ exports.resolveRemoteEnvironment = resolveRemoteEnvironment;
2659
+ exports.runBuildScript = runBuildScript;
2452
2660
  exports.runRemoteCommand = runRemoteCommand;
2453
2661
  exports.shouldSkipMiniappPlatformCsp = shouldSkipMiniappPlatformCsp;
2662
+ exports.validateBuildMode = validateBuildMode;
2454
2663
  exports.validateDeployReleaseNote = validateDeployReleaseNote;
2664
+ exports.withProjectArtifactLock = withProjectArtifactLock;