@heybox/hb-sdk 0.9.9-alpha.4 → 0.10.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/dist/cli-chunks/{build-BJ3OdlOf.cjs → build-2HtqErzg.cjs} +4 -4
- package/dist/cli-chunks/{create-Nnriz1g8.cjs → create-DkQcWVCt.cjs} +1 -1
- package/dist/cli-chunks/{dev-fCGFdByu.cjs → dev-DVLzZmC9.cjs} +16785 -15512
- package/dist/cli-chunks/{doctor-Dka35I4J.cjs → doctor-DoNFtMdI.cjs} +1 -1
- package/dist/cli-chunks/{game-binding-guide-74xdBeSz.cjs → game-binding-guide-Brl6PLLk.cjs} +2 -2
- package/dist/cli-chunks/{game-bindings-Bn9K3b-V.cjs → game-bindings-DNLO-UF4.cjs} +3 -3
- package/dist/cli-chunks/{games-CJd7dnrn.cjs → games-lxVFeZNF.cjs} +1 -1
- package/dist/cli-chunks/{index-C0e35S9F.cjs → index-BIQCaIlS.cjs} +479 -21
- package/dist/cli-chunks/{index-BXVwHHJK.cjs → index-D4TFWbsi.cjs} +1 -1
- package/dist/cli-chunks/{index.esm-BXwlM8dI.cjs → index.esm-D-GaYxTQ.cjs} +11 -11
- package/dist/cli-chunks/{login-BnQ61BTt.cjs → login-C-AlCUrx.cjs} +1 -1
- package/dist/cli-chunks/{project-vite-o_omhA5m.cjs → project-vite-C5e3UaK6.cjs} +1 -1
- package/dist/cli-chunks/{remote-IrbvALD1.cjs → remote-BM0eYi33.cjs} +942 -837
- package/dist/cli-chunks/{runtime-permission-env-B8cFtlhN.cjs → runtime-permission-env-DWE4ffLc.cjs} +3 -2
- package/dist/cli-chunks/{skill-BgrvLAJa.cjs → skill-CidjQRHX.cjs} +2 -2
- package/dist/cli-chunks/{version-BDrKYZTU.cjs → version-D_sJ12ed.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-0lgdUAiO.js +224 -0
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-C4EU7is4.js +6 -0
- package/dist/devtools/browser-dev-host/assets/index-870cPYsT.css +1 -0
- package/dist/devtools/browser-dev-host/assets/index-Bq4nDVWQ.js +574 -0
- package/dist/devtools/browser-dev-host/assets/pc-onboarding-example-BS3sevnG.webp +0 -0
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/vite.cjs.js +16 -8
- package/dist/vite.esm.js +16 -8
- package/package.json +6 -5
- package/skill/SKILL.md +7 -0
- package/skill/skill.json +5 -5
- package/types/vite/index.d.ts +2 -0
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-CRAx6EPL.js +0 -224
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-hnNxdeA6.js +0 -13
- package/dist/devtools/browser-dev-host/assets/index-C5kOabQa.js +0 -567
- package/dist/devtools/browser-dev-host/assets/index-D0XGMYIr.css +0 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var index_esm = require('./index.esm-CenYK5Bl.cjs');
|
|
4
|
-
var runtimePermissionEnv = require('./runtime-permission-env-
|
|
4
|
+
var runtimePermissionEnv = require('./runtime-permission-env-DWE4ffLc.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-
|
|
10
|
+
var gameBindingGuide = require('./game-binding-guide-Brl6PLLk.cjs');
|
|
11
11
|
var promises = require('node:readline/promises');
|
|
12
|
-
var index = require('./index-
|
|
12
|
+
var index = require('./index-BIQCaIlS.cjs');
|
|
13
13
|
var childProcess = require('node:child_process');
|
|
14
14
|
require('node:zlib');
|
|
15
15
|
|
|
@@ -37,636 +37,356 @@ function getMiniappMetadataWarnings(metadata) {
|
|
|
37
37
|
return warnings;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
49
|
-
return
|
|
67
|
+
function shouldSkipMiniappPlatformCsp(_runtimePermissions) {
|
|
68
|
+
return false;
|
|
50
69
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
|
|
89
|
-
|
|
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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
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
|
|
157
|
+
await lock.release();
|
|
144
158
|
}
|
|
145
|
-
return Buffer.concat(chunks);
|
|
146
159
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
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
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
258
|
+
function escapeWindowsCommandArgument(argument) {
|
|
259
|
+
return `"${argument}"`;
|
|
260
|
+
}
|
|
261
|
+
async function readProjectBuildScript(projectRoot) {
|
|
228
262
|
try {
|
|
229
|
-
|
|
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
|
|
267
|
+
return '';
|
|
233
268
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
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
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
|
270
|
-
return
|
|
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
|
|
279
|
-
return
|
|
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
|
|
282
|
-
return
|
|
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
|
|
293
|
-
|
|
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
|
|
316
|
-
|
|
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 ?? {};
|
|
342
|
+
async function createUserMiniprogram(runtime) {
|
|
343
|
+
return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_API_PATH, {}, runtime);
|
|
334
344
|
}
|
|
335
|
-
|
|
336
|
-
|
|
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} 个文件` });
|
|
345
|
+
async function getUserMiniprogramDetail(options, runtime) {
|
|
346
|
+
return remoteGet(runtimePermissionEnv.DETAIL_USER_MINIPROGRAM_API_PATH, options, runtime);
|
|
451
347
|
}
|
|
452
|
-
function
|
|
453
|
-
|
|
454
|
-
for (let index = 0; index < files.length; index += batchSize) {
|
|
455
|
-
batches.push(files.slice(index, index + batchSize));
|
|
456
|
-
}
|
|
457
|
-
return batches;
|
|
348
|
+
async function createLocalDevLaunchToken$1(options, runtime) {
|
|
349
|
+
return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_LOCAL_DEV_LAUNCH_TOKEN_API_PATH, options, runtime);
|
|
458
350
|
}
|
|
459
|
-
function
|
|
460
|
-
|
|
461
|
-
return false;
|
|
462
|
-
const value = error;
|
|
463
|
-
return Number(value.statusCode) === 409 && value.code === 'ObjectAlreadyExists';
|
|
351
|
+
async function getPreviewAllowlist(options, runtime) {
|
|
352
|
+
return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH, options, runtime);
|
|
464
353
|
}
|
|
465
|
-
function
|
|
466
|
-
return
|
|
467
|
-
name: file.relativePath.split('/').pop() ?? file.relativePath,
|
|
468
|
-
mimetype: file.mimeType,
|
|
469
|
-
fsize: file.size,
|
|
470
|
-
path: file.key,
|
|
471
|
-
}));
|
|
354
|
+
async function updatePreviewAllowlist(options, runtime) {
|
|
355
|
+
return remotePostForm(runtimePermissionEnv.UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH, options, runtime);
|
|
472
356
|
}
|
|
473
|
-
function
|
|
474
|
-
|
|
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
|
-
}
|
|
357
|
+
async function createUserMiniprogramLeaderboard(options, runtime) {
|
|
358
|
+
return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime);
|
|
484
359
|
}
|
|
485
|
-
function
|
|
486
|
-
|
|
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
|
-
};
|
|
360
|
+
async function getUserMiniprogramLeaderboard(options, runtime) {
|
|
361
|
+
return remoteGet(runtimePermissionEnv.DETAIL_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime);
|
|
510
362
|
}
|
|
511
|
-
async function
|
|
512
|
-
|
|
513
|
-
return cosModule.default;
|
|
363
|
+
async function listUserMiniprogramLeaderboards(options, runtime) {
|
|
364
|
+
return remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime);
|
|
514
365
|
}
|
|
515
|
-
function
|
|
516
|
-
|
|
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`;
|
|
366
|
+
async function deleteUserMiniprogramLeaderboard(options, runtime) {
|
|
367
|
+
return ((await remotePostForm(runtimePermissionEnv.DELETE_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime, { requireResult: false })) ?? {});
|
|
523
368
|
}
|
|
524
|
-
function
|
|
525
|
-
|
|
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);
|
|
369
|
+
async function precheckUserMiniprogramVersion$1(options, runtime) {
|
|
370
|
+
return remotePostForm(runtimePermissionEnv.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
|
|
535
371
|
}
|
|
536
|
-
function
|
|
537
|
-
return
|
|
372
|
+
async function submitUserMiniprogramAudit$1(options, runtime) {
|
|
373
|
+
return remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, {
|
|
374
|
+
mini_program_id: options.mini_program_id,
|
|
375
|
+
session_id: options.session_id,
|
|
376
|
+
preflight_token: options.preflight_token,
|
|
377
|
+
}, runtime);
|
|
538
378
|
}
|
|
539
|
-
function
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
}
|
|
545
|
-
if (typeof value === 'number') {
|
|
546
|
-
return String(value);
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
return '';
|
|
379
|
+
async function getVersionPreviewInfo(options, runtime) {
|
|
380
|
+
return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH, {
|
|
381
|
+
mini_program_id: options.mini_program_id,
|
|
382
|
+
preview_version: options.version,
|
|
383
|
+
}, runtime);
|
|
550
384
|
}
|
|
551
|
-
function
|
|
552
|
-
return
|
|
385
|
+
async function withdrawUserMiniprogramVersion(options, runtime) {
|
|
386
|
+
return remotePostForm(runtimePermissionEnv.WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
|
|
553
387
|
}
|
|
554
|
-
|
|
555
|
-
|
|
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
|
-
getPostBinding: (request) => remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_POST_BINDING_API_PATH, request, options),
|
|
582
|
-
previewPostBinding: (request) => remotePostForm(runtimePermissionEnv.USER_MINIPROGRAM_POST_PREVIEW_API_PATH, request, options),
|
|
583
|
-
setPostBinding: (request) => remotePostForm(`${runtimePermissionEnv.USER_MINIPROGRAM_POST_BINDING_API_PATH}/update`, request, options),
|
|
584
|
-
listPermissionApplications: (request) => remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
|
|
585
|
-
submitPermissionApplication: (request) => remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_PERMISSION_APPLICATION_API_PATH, request, options),
|
|
586
|
-
listDeveloperEntities: () => listDeveloperEntities(options),
|
|
587
|
-
switchDeveloperEntity: (requestOptions) => switchDeveloperEntity(requestOptions, options),
|
|
588
|
-
getDeveloperAccessStatus: () => getDeveloperAccessStatus(options),
|
|
589
|
-
listUserMiniprograms: (requestOptions = {}) => listUserMiniprograms(requestOptions, options),
|
|
590
|
-
createUserMiniprogram: () => createUserMiniprogram(options),
|
|
591
|
-
getUserMiniprogramDetail: (requestOptions) => getUserMiniprogramDetail(requestOptions, options),
|
|
592
|
-
createLocalDevLaunchToken: (requestOptions) => createLocalDevLaunchToken$1(requestOptions, options),
|
|
593
|
-
getPreviewAllowlist: (requestOptions) => getPreviewAllowlist(requestOptions, options),
|
|
594
|
-
updatePreviewAllowlist: (requestOptions) => updatePreviewAllowlist(requestOptions, options),
|
|
595
|
-
createUserMiniprogramLeaderboard: (requestOptions) => createUserMiniprogramLeaderboard(requestOptions, options),
|
|
596
|
-
getUserMiniprogramLeaderboard: (requestOptions) => getUserMiniprogramLeaderboard(requestOptions, options),
|
|
597
|
-
listUserMiniprogramLeaderboards: (requestOptions) => listUserMiniprogramLeaderboards(requestOptions, options),
|
|
598
|
-
deleteUserMiniprogramLeaderboard: (requestOptions) => deleteUserMiniprogramLeaderboard(requestOptions, options),
|
|
599
|
-
precheckUserMiniprogramVersion: (requestOptions) => precheckUserMiniprogramVersion(requestOptions, options),
|
|
600
|
-
submitUserMiniprogramAudit: (requestOptions) => submitUserMiniprogramAudit(requestOptions, options),
|
|
601
|
-
getVersionPreviewInfo: (requestOptions) => getVersionPreviewInfo(requestOptions, options),
|
|
602
|
-
withdrawUserMiniprogramVersion: (requestOptions) => withdrawUserMiniprogramVersion(requestOptions, options),
|
|
603
|
-
releaseUserMiniprogramVersion: (requestOptions) => releaseUserMiniprogramVersion(requestOptions, options),
|
|
604
|
-
takeDownUserMiniprogram: (requestOptions) => takeDownUserMiniprogram(requestOptions, options),
|
|
605
|
-
reopenUserMiniprogram: (requestOptions) => reopenUserMiniprogram(requestOptions, options),
|
|
606
|
-
updateSquareDisplay: (requestOptions) => updateSquareDisplay(requestOptions, options),
|
|
607
|
-
listUserMiniprogramVersions: (requestOptions) => listUserMiniprogramVersions(requestOptions, options),
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
async function listDeveloperEntities(runtime) {
|
|
611
|
-
return remoteGet(runtimePermissionEnv.DEVELOPER_ENTITY_LIST_API_PATH, {}, runtime);
|
|
612
|
-
}
|
|
613
|
-
async function switchDeveloperEntity(options, runtime) {
|
|
614
|
-
return (await remotePostForm(runtimePermissionEnv.DEVELOPER_ENTITY_SWITCH_API_PATH, options, runtime, { requireResult: false })) ?? {};
|
|
615
|
-
}
|
|
616
|
-
async function getDeveloperAccessStatus(runtime) {
|
|
617
|
-
return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_ACCESS_STATUS_API_PATH, {}, runtime);
|
|
618
|
-
}
|
|
619
|
-
async function listUserMiniprograms(options, runtime) {
|
|
620
|
-
return remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_API_PATH, options, runtime);
|
|
621
|
-
}
|
|
622
|
-
async function createUserMiniprogram(runtime) {
|
|
623
|
-
return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_API_PATH, {}, runtime);
|
|
624
|
-
}
|
|
625
|
-
async function getUserMiniprogramDetail(options, runtime) {
|
|
626
|
-
return remoteGet(runtimePermissionEnv.DETAIL_USER_MINIPROGRAM_API_PATH, options, runtime);
|
|
627
|
-
}
|
|
628
|
-
async function createLocalDevLaunchToken$1(options, runtime) {
|
|
629
|
-
return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_LOCAL_DEV_LAUNCH_TOKEN_API_PATH, options, runtime);
|
|
630
|
-
}
|
|
631
|
-
async function getPreviewAllowlist(options, runtime) {
|
|
632
|
-
return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH, options, runtime);
|
|
633
|
-
}
|
|
634
|
-
async function updatePreviewAllowlist(options, runtime) {
|
|
635
|
-
return remotePostForm(runtimePermissionEnv.UPDATE_USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH, options, runtime);
|
|
636
|
-
}
|
|
637
|
-
async function createUserMiniprogramLeaderboard(options, runtime) {
|
|
638
|
-
return remotePostForm(runtimePermissionEnv.CREATE_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime);
|
|
639
|
-
}
|
|
640
|
-
async function getUserMiniprogramLeaderboard(options, runtime) {
|
|
641
|
-
return remoteGet(runtimePermissionEnv.DETAIL_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime);
|
|
642
|
-
}
|
|
643
|
-
async function listUserMiniprogramLeaderboards(options, runtime) {
|
|
644
|
-
return remoteGet(runtimePermissionEnv.LIST_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime);
|
|
645
|
-
}
|
|
646
|
-
async function deleteUserMiniprogramLeaderboard(options, runtime) {
|
|
647
|
-
return ((await remotePostForm(runtimePermissionEnv.DELETE_USER_MINIPROGRAM_LEADERBOARD_API_PATH, options, runtime, { requireResult: false })) ?? {});
|
|
648
|
-
}
|
|
649
|
-
async function precheckUserMiniprogramVersion(options, runtime) {
|
|
650
|
-
return remotePostForm(runtimePermissionEnv.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
|
|
651
|
-
}
|
|
652
|
-
async function submitUserMiniprogramAudit(options, runtime) {
|
|
653
|
-
return remotePostForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, {
|
|
654
|
-
mini_program_id: options.mini_program_id,
|
|
655
|
-
session_id: options.session_id,
|
|
656
|
-
preflight_token: options.preflight_token,
|
|
657
|
-
}, runtime);
|
|
658
|
-
}
|
|
659
|
-
async function getVersionPreviewInfo(options, runtime) {
|
|
660
|
-
return remoteGet(runtimePermissionEnv.USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH, {
|
|
661
|
-
mini_program_id: options.mini_program_id,
|
|
662
|
-
preview_version: options.version,
|
|
663
|
-
}, runtime);
|
|
664
|
-
}
|
|
665
|
-
async function withdrawUserMiniprogramVersion(options, runtime) {
|
|
666
|
-
return remotePostForm(runtimePermissionEnv.WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
|
|
667
|
-
}
|
|
668
|
-
async function releaseUserMiniprogramVersion(options, runtime) {
|
|
669
|
-
return remotePostForm(runtimePermissionEnv.RELEASE_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
|
|
388
|
+
async function releaseUserMiniprogramVersion(options, runtime) {
|
|
389
|
+
return remotePostForm(runtimePermissionEnv.RELEASE_USER_MINIPROGRAM_VERSION_API_PATH, options, runtime);
|
|
670
390
|
}
|
|
671
391
|
async function takeDownUserMiniprogram(options, runtime) {
|
|
672
392
|
return remotePostForm(runtimePermissionEnv.TAKE_DOWN_USER_MINIPROGRAM_API_PATH, options, runtime);
|
|
@@ -703,209 +423,642 @@ async function remotePostForm(path, fields, runtime, options = {}) {
|
|
|
703
423
|
if (options.requireResult === false) {
|
|
704
424
|
return readOptionalResult(response, path);
|
|
705
425
|
}
|
|
706
|
-
return readRequiredResult(response, path);
|
|
426
|
+
return readRequiredResult(response, path);
|
|
427
|
+
}
|
|
428
|
+
async function readRequiredResult(response, pathWithQuery) {
|
|
429
|
+
const result = await index.readHeyboxApiEnvelope(response, { pathWithQuery, requireResult: true });
|
|
430
|
+
return result;
|
|
431
|
+
}
|
|
432
|
+
async function readOptionalResult(response, pathWithQuery) {
|
|
433
|
+
return index.readHeyboxApiEnvelope(response, { pathWithQuery, requireResult: false });
|
|
434
|
+
}
|
|
435
|
+
function createPathWithQuery(path, query) {
|
|
436
|
+
const params = new URLSearchParams();
|
|
437
|
+
for (const [key, value] of Object.entries(query)) {
|
|
438
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
439
|
+
params.set(key, String(value));
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const queryString = params.toString();
|
|
443
|
+
return queryString ? `${path}?${queryString}` : path;
|
|
444
|
+
}
|
|
445
|
+
function createFormBody(fields) {
|
|
446
|
+
const body = new URLSearchParams();
|
|
447
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
448
|
+
if (value === undefined || value === null) {
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (Array.isArray(value)) {
|
|
452
|
+
body.set(key, value.join(','));
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (typeof value === 'object') {
|
|
456
|
+
body.set(key, JSON.stringify(value));
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
body.set(key, String(value));
|
|
460
|
+
}
|
|
461
|
+
return body.toString();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function resolveRemoteEnvironment(options = {}, runtime = {}) {
|
|
465
|
+
const env = options.env ?? process.env;
|
|
466
|
+
const apiBaseUrl = index.resolveHeyboxApiBaseUrl({ ...options, env });
|
|
467
|
+
const loginBaseUrl = index.resolveHeyboxLoginBaseUrl({ ...options, env });
|
|
468
|
+
const session = options.session ?? (await (runtime.requireAuthSession ?? index.requireHeyboxAuthSession)({ loginBaseUrl }));
|
|
469
|
+
return {
|
|
470
|
+
apiBaseUrl,
|
|
471
|
+
loginBaseUrl,
|
|
472
|
+
allowUnsafeApiBaseUrl: options.allowUnsafeApiBaseUrl === true || isTruthyEnvFlag(env.HB_SDK_ALLOW_UNSAFE_API_BASE_URL),
|
|
473
|
+
env,
|
|
474
|
+
fetchImpl: runtime.fetchImpl ?? options.fetchImpl ?? fetch,
|
|
475
|
+
session,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
function createRemoteApiClientForEnvironment(environment) {
|
|
479
|
+
return createRemoteApiClient({
|
|
480
|
+
baseUrl: environment.apiBaseUrl,
|
|
481
|
+
fetchImpl: environment.fetchImpl,
|
|
482
|
+
session: environment.session,
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
async function getBoundMiniProgram(options = {}, runtime = {}) {
|
|
486
|
+
const cwd = options.cwd ?? process.cwd();
|
|
487
|
+
const binding = await gameBindingGuide.requireBoundMiniProgramId(cwd);
|
|
488
|
+
const api = await resolveRemoteApiClient(options, runtime);
|
|
489
|
+
const detail = await api.getUserMiniprogramDetail({ mini_program_id: binding.miniProgramId });
|
|
490
|
+
return {
|
|
491
|
+
...binding,
|
|
492
|
+
detail,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
async function createLocalDevLaunchToken(options, runtime = {}) {
|
|
496
|
+
const miniProgramId = options.miniProgramId.trim();
|
|
497
|
+
if (!miniProgramId) {
|
|
498
|
+
throw new Error('mini-program-id 不能为空');
|
|
499
|
+
}
|
|
500
|
+
const api = await resolveRemoteApiClient(options, runtime);
|
|
501
|
+
return api.createLocalDevLaunchToken({
|
|
502
|
+
mini_program_id: miniProgramId,
|
|
503
|
+
...(options.developmentSnapshot ? { development_snapshot: options.developmentSnapshot } : {}),
|
|
504
|
+
...(options.companionManifestSha256
|
|
505
|
+
? { companion_manifest_sha256: options.companionManifestSha256 }
|
|
506
|
+
: {}),
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
async function resolveRemoteApiClient(options, runtime) {
|
|
510
|
+
if (runtime.apiClient) {
|
|
511
|
+
return runtime.apiClient;
|
|
512
|
+
}
|
|
513
|
+
return createRemoteApiClientForEnvironment(await resolveRemoteEnvironment(options, runtime));
|
|
514
|
+
}
|
|
515
|
+
function isTruthyEnvFlag(value) {
|
|
516
|
+
return ['1', 'true', 'yes', 'on'].includes(String(value ?? '')
|
|
517
|
+
.trim()
|
|
518
|
+
.toLowerCase());
|
|
519
|
+
}
|
|
520
|
+
|
|
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
|
+
const PC_ONBOARDING_EVENT_PATH = `${PC_ONBOARDING_PATH}/event`;
|
|
526
|
+
const PC_ONBOARDING_ACTIONS = ['exposure', 'guide', 'download', 'close', 'later'];
|
|
527
|
+
function parsePcOnboardingEvent(input) {
|
|
528
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
529
|
+
return;
|
|
530
|
+
const value = input;
|
|
531
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
532
|
+
if (Object.keys(value).some((key) => !['eventId', 'dialogId', 'source', 'action'].includes(key)) ||
|
|
533
|
+
typeof value.eventId !== 'string' ||
|
|
534
|
+
!uuid.test(value.eventId) ||
|
|
535
|
+
typeof value.dialogId !== 'string' ||
|
|
536
|
+
!uuid.test(value.dialogId) ||
|
|
537
|
+
!['automatic', 'manual'].includes(String(value.source)) ||
|
|
538
|
+
!PC_ONBOARDING_ACTIONS.includes(value.action))
|
|
539
|
+
return;
|
|
540
|
+
return value;
|
|
541
|
+
}
|
|
542
|
+
/** 平台声明只代表适配承诺,不能据此认定已完成客户端验收。 */
|
|
543
|
+
function getPcAdaptationSuggestion(platforms) {
|
|
544
|
+
return platforms.includes('windows') || platforms.includes('macos')
|
|
545
|
+
? '已声明 PC 平台:提审前建议在对应 PC 客户端验证窗口缩放、鼠标键盘及所用端能力。'
|
|
546
|
+
: '小程序也可以在小黑盒 PC 客户端运行。建议评估 Windows / macOS 适配,并在提审前完成客户端验证;仅做移动端可忽略。';
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
async function inspectBasicInfoImage(bytes, sourcePath, kind) {
|
|
550
|
+
const inspected = await inspectDecodedBasicInfoImage(bytes, kind);
|
|
551
|
+
const extensions = { jpg: ['jpg', 'jpeg'], png: ['png'], gif: ['gif'], webp: ['webp'] };
|
|
552
|
+
const ext = sourcePath.split('.').pop().toLowerCase();
|
|
553
|
+
if (!extensions[inspected.extension]?.includes(ext))
|
|
554
|
+
throw new Error('资料图片格式与扩展名不一致');
|
|
555
|
+
return inspected;
|
|
556
|
+
}
|
|
557
|
+
async function inspectRemoteBasicInfoImage(bytes, kind) {
|
|
558
|
+
return inspectDecodedBasicInfoImage(bytes, kind);
|
|
559
|
+
}
|
|
560
|
+
async function inspectDecodedBasicInfoImage(bytes, kind) {
|
|
561
|
+
if (!bytes.length || bytes.length > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
|
|
562
|
+
throw new Error('资料图片不得为空或超过 10 MiB');
|
|
563
|
+
const decoder = sharp(bytes, { limitInputPixels: runtimePermissionEnv.BASIC_INFO_MAX_PIXELS, failOn: 'warning' });
|
|
564
|
+
const metadata = await decoder.metadata();
|
|
565
|
+
const extensions = { jpeg: 'jpg', png: 'png', gif: 'gif', webp: 'webp' };
|
|
566
|
+
if (!metadata.format || !extensions[metadata.format])
|
|
567
|
+
throw new Error('资料图片格式不支持');
|
|
568
|
+
const width = metadata.width ?? 0;
|
|
569
|
+
const height = metadata.pageHeight ?? metadata.height ?? 0;
|
|
570
|
+
if (!width || !height || width * height > runtimePermissionEnv.BASIC_INFO_MAX_PIXELS)
|
|
571
|
+
throw new Error('资料图片不得超过 4000 万像素');
|
|
572
|
+
if (kind === 'icon' && (width !== 200 || height !== 200))
|
|
573
|
+
throw new Error('icon 必须是 200×200');
|
|
574
|
+
// 强制解码而非只信任图片头;不将解码结果写回图片。
|
|
575
|
+
await decoder.stats();
|
|
576
|
+
return { sha256: node_crypto.createHash('sha256').update(bytes).digest('hex'), extension: extensions[metadata.format] };
|
|
577
|
+
}
|
|
578
|
+
async function readBasicInfoSource(projectRoot, relative, kind) {
|
|
579
|
+
runtimePermissionEnv.validateBasicInfoPath(relative);
|
|
580
|
+
const root = await fs.realpath(projectRoot);
|
|
581
|
+
const target = await fs.realpath(path.join(root, relative));
|
|
582
|
+
const resolvedRelative = path.relative(root, target).split(path.sep).join('/');
|
|
583
|
+
runtimePermissionEnv.validateBasicInfoPath(resolvedRelative);
|
|
584
|
+
if (resolvedRelative.startsWith('../') || path.isAbsolute(resolvedRelative))
|
|
585
|
+
throw new Error('资料图片不能逃逸项目目录');
|
|
586
|
+
const info = await fs.stat(target);
|
|
587
|
+
if (!info.isFile() || info.size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
|
|
588
|
+
throw new Error('资料图片必须为不超过 10 MiB 的普通文件');
|
|
589
|
+
const file = await fs.open(target, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW);
|
|
590
|
+
try {
|
|
591
|
+
const actual = await file.stat();
|
|
592
|
+
if (!actual.isFile() || actual.size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
|
|
593
|
+
throw new Error('资料图片文件已变化');
|
|
594
|
+
const bytes = await file.readFile();
|
|
595
|
+
return { bytes, ...(await inspectBasicInfoImage(bytes, relative, kind)) };
|
|
596
|
+
}
|
|
597
|
+
finally {
|
|
598
|
+
await file.close();
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/** 逐级校验真实目录,避免保留目录或迁移目录中的符号链接将写入带到项目外。 */
|
|
602
|
+
async function ensureBasicInfoDirectory(rootPath, relative) {
|
|
603
|
+
const root = await fs.realpath(rootPath);
|
|
604
|
+
let current = root;
|
|
605
|
+
for (const part of relative.split('/')) {
|
|
606
|
+
if (!part || part === '.' || part === '..')
|
|
607
|
+
throw new Error('资料目录不合法');
|
|
608
|
+
current = path.join(current, part);
|
|
609
|
+
await fs.mkdir(current).catch((error) => {
|
|
610
|
+
if (error.code !== 'EEXIST')
|
|
611
|
+
throw error;
|
|
612
|
+
});
|
|
613
|
+
const resolved = await fs.realpath(current);
|
|
614
|
+
const within = path.relative(root, resolved);
|
|
615
|
+
if (within.startsWith('..') || path.isAbsolute(within))
|
|
616
|
+
throw new Error('资料目录不能逃逸项目');
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function trustedProfileUrl(raw) {
|
|
621
|
+
const url = new URL(raw);
|
|
622
|
+
const trusted = ['max-c.com', 'xiaoheihe.cn', 'heybox.com'];
|
|
623
|
+
if (url.protocol !== 'https:' ||
|
|
624
|
+
url.username ||
|
|
625
|
+
url.password ||
|
|
626
|
+
(url.port && url.port !== '443') ||
|
|
627
|
+
!trusted.some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`)))
|
|
628
|
+
throw new Error('线上资料图片 URL 不受信任');
|
|
629
|
+
return url;
|
|
630
|
+
}
|
|
631
|
+
async function downloadImage(raw, fetchImpl) {
|
|
632
|
+
const response = await fetchImpl(trustedProfileUrl(raw), { redirect: 'error', signal: AbortSignal.timeout(15_000) });
|
|
633
|
+
if (!response.ok || !response.body)
|
|
634
|
+
throw new Error('下载线上资料图片失败');
|
|
635
|
+
if (Number(response.headers.get('content-length')) > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
|
|
636
|
+
throw new Error('图片超过 10 MiB');
|
|
637
|
+
const chunks = [];
|
|
638
|
+
let size = 0;
|
|
639
|
+
const reader = response.body.getReader();
|
|
640
|
+
try {
|
|
641
|
+
for (;;) {
|
|
642
|
+
const part = await reader.read();
|
|
643
|
+
if (part.done)
|
|
644
|
+
break;
|
|
645
|
+
size += part.value.length;
|
|
646
|
+
if (size > runtimePermissionEnv.BASIC_INFO_MAX_BYTES)
|
|
647
|
+
throw new Error('图片超过 10 MiB');
|
|
648
|
+
chunks.push(part.value);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
finally {
|
|
652
|
+
await reader.cancel();
|
|
653
|
+
}
|
|
654
|
+
return Buffer.concat(chunks);
|
|
655
|
+
}
|
|
656
|
+
/** package-last 提交:失败只清理本次新增素材,原配置始终保留。 */
|
|
657
|
+
async function migrateBasicInfo(cwd, detail, miniProgramId, fetchImpl = fetch, force = false) {
|
|
658
|
+
const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
|
|
659
|
+
const heybox = context.packageJson.heybox ?? {};
|
|
660
|
+
const existing = heybox.miniProgramId;
|
|
661
|
+
if (existing && existing !== miniProgramId && !force)
|
|
662
|
+
throw new Error('当前项目已绑定其他小程序,请使用 --force');
|
|
663
|
+
const fields = ['name', 'icon', 'coverImages'];
|
|
664
|
+
const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(heybox, key));
|
|
665
|
+
if (present.length && present.length !== 3)
|
|
666
|
+
throw new Error(`资料配置不完整,请补齐 ${fields.filter((key) => !present.includes(key)).join('、')}`);
|
|
667
|
+
const created = [];
|
|
668
|
+
const temp = `${context.packageJsonPath}.${node_crypto.randomUUID()}.tmp`;
|
|
669
|
+
try {
|
|
670
|
+
let profile = present.length ? runtimePermissionEnv.parseMiniappBasicInfo(heybox) : undefined;
|
|
671
|
+
if (profile) {
|
|
672
|
+
await readBasicInfoSource(context.projectRoot, profile.icon, 'icon');
|
|
673
|
+
for (const cover of profile.coverImages)
|
|
674
|
+
await readBasicInfoSource(context.projectRoot, cover, 'cover');
|
|
675
|
+
if (existing === miniProgramId)
|
|
676
|
+
return { changed: false, miniProgramId };
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
if (detail.mini_program_id !== miniProgramId)
|
|
680
|
+
throw new Error('远端小程序身份不一致');
|
|
681
|
+
const snapshot = detail.published_basic_info;
|
|
682
|
+
if (!snapshot?.version ||
|
|
683
|
+
!snapshot.icon_url ||
|
|
684
|
+
!Array.isArray(snapshot.cover_image_urls) ||
|
|
685
|
+
snapshot.cover_image_urls.length < 1 ||
|
|
686
|
+
snapshot.cover_image_urls.length > 5)
|
|
687
|
+
throw new Error('没有当前正式发布快照,请手工配置 heybox.name/icon/coverImages');
|
|
688
|
+
profile = { name: runtimePermissionEnv.normalizeBasicInfoName(snapshot.name), icon: '', coverImages: [] };
|
|
689
|
+
const entries = [
|
|
690
|
+
{ url: snapshot.icon_url, kind: 'icon', label: 'icon' },
|
|
691
|
+
...snapshot.cover_image_urls.map((url, i) => ({ url, kind: 'cover', label: `cover-${String(i + 1).padStart(2, '0')}` })),
|
|
692
|
+
];
|
|
693
|
+
for (const entry of entries) {
|
|
694
|
+
const bytes = await downloadImage(entry.url, fetchImpl);
|
|
695
|
+
const image = await inspectRemoteBasicInfoImage(bytes, entry.kind);
|
|
696
|
+
const relative = `assets/heybox/${entry.label}.${image.sha256.slice(0, 12)}.${image.extension}`;
|
|
697
|
+
const target = path.join(context.projectRoot, relative);
|
|
698
|
+
await ensureBasicInfoDirectory(context.projectRoot, 'assets/heybox');
|
|
699
|
+
try {
|
|
700
|
+
await fs.writeFile(target, bytes, { flag: 'wx' });
|
|
701
|
+
created.push(target);
|
|
702
|
+
}
|
|
703
|
+
catch (error) {
|
|
704
|
+
if (error.code !== 'EEXIST' ||
|
|
705
|
+
!(await readBasicInfoSource(context.projectRoot, relative, entry.kind).then((existing) => existing.bytes.equals(bytes), () => false)))
|
|
706
|
+
throw new Error('迁移素材名称冲突,未覆盖已有文件');
|
|
707
|
+
}
|
|
708
|
+
if (entry.kind === 'icon')
|
|
709
|
+
profile.icon = relative;
|
|
710
|
+
else
|
|
711
|
+
profile.coverImages.push(relative);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
// 避免覆盖用户在下载期间修改的配置。
|
|
715
|
+
if ((await fs.readFile(context.packageJsonPath, 'utf8')) !== context.raw)
|
|
716
|
+
throw new Error('package.json 已变化,请重试迁移');
|
|
717
|
+
context.packageJson.heybox = { ...heybox, miniProgramId, ...profile };
|
|
718
|
+
await fs.writeFile(temp, JSON.stringify(context.packageJson, null, context.indent) + context.trailingNewline, { flag: 'wx' });
|
|
719
|
+
await fs.rename(temp, context.packageJsonPath);
|
|
720
|
+
return { changed: true, miniProgramId };
|
|
721
|
+
}
|
|
722
|
+
catch (error) {
|
|
723
|
+
// 若用户同时修改了 package,保留可能已被引用的素材供重试复用。
|
|
724
|
+
if ((await fs.readFile(context.packageJsonPath, 'utf8').catch(() => '')) === context.raw) {
|
|
725
|
+
await Promise.all(created.map((file) => fs.unlink(file).catch(() => { })));
|
|
726
|
+
}
|
|
727
|
+
throw error;
|
|
728
|
+
}
|
|
729
|
+
finally {
|
|
730
|
+
await fs.unlink(temp).catch(() => { });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
async function compareBasicInfo(cwd, detail, fetchImpl = fetch) {
|
|
734
|
+
const context = await gameBindingGuide.readMiniProgramProjectPackage(cwd);
|
|
735
|
+
const published = detail.published_basic_info;
|
|
736
|
+
let local;
|
|
737
|
+
try {
|
|
738
|
+
local = runtimePermissionEnv.parseMiniappBasicInfo(context.packageJson.heybox ?? {});
|
|
739
|
+
}
|
|
740
|
+
catch {
|
|
741
|
+
return { status: 'unavailable' };
|
|
742
|
+
}
|
|
743
|
+
if (!local || !published?.version)
|
|
744
|
+
return { status: 'unavailable', local, published };
|
|
745
|
+
try {
|
|
746
|
+
const pairs = [
|
|
747
|
+
{ local: local.icon, remote: published.icon_url, kind: 'icon' },
|
|
748
|
+
...local.coverImages.map((p, i) => ({ local: p, remote: published.cover_image_urls[i], kind: 'cover' })),
|
|
749
|
+
];
|
|
750
|
+
let changed = local.name !== runtimePermissionEnv.normalizeBasicInfoName(published.name) || local.coverImages.length !== published.cover_image_urls.length;
|
|
751
|
+
for (const pair of pairs) {
|
|
752
|
+
if (!pair.remote) {
|
|
753
|
+
changed = true;
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
const source = await readBasicInfoSource(context.projectRoot, pair.local, pair.kind);
|
|
757
|
+
const bytes = await downloadImage(pair.remote, fetchImpl);
|
|
758
|
+
const remote = await inspectRemoteBasicInfoImage(bytes, pair.kind);
|
|
759
|
+
changed ||= source.sha256 !== remote.sha256;
|
|
760
|
+
}
|
|
761
|
+
return { status: changed ? 'changed' : 'unchanged', local, published };
|
|
762
|
+
}
|
|
763
|
+
catch {
|
|
764
|
+
return { status: 'unavailable', local, published };
|
|
765
|
+
}
|
|
707
766
|
}
|
|
708
|
-
|
|
709
|
-
|
|
767
|
+
|
|
768
|
+
const CREATE_USER_MINIPROGRAM_UPLOAD_SESSION_API_PATH = '/mall/developer/user_miniprogram/version/upload_session/create';
|
|
769
|
+
const RECORD_USER_MINIPROGRAM_UPLOAD_RESULT_API_PATH = '/mall/developer/user_miniprogram/version/upload_session/record';
|
|
770
|
+
const COMPANION_FINALIZATION_TIMEOUT_MS = 30 * 60_000;
|
|
771
|
+
async function authorizeCompanionUpload(options, runtime = {}) {
|
|
772
|
+
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);
|
|
773
|
+
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)) {
|
|
774
|
+
throw new Error('Companion 上传凭证响应不完整');
|
|
775
|
+
}
|
|
710
776
|
return result;
|
|
711
777
|
}
|
|
712
|
-
async function
|
|
713
|
-
return
|
|
778
|
+
async function precheckUserMiniprogramVersion(options, runtime = {}) {
|
|
779
|
+
return postUserMiniprogramVersionForm(runtimePermissionEnv.PRECHECK_USER_MINIPROGRAM_VERSION_API_PATH, options, {
|
|
780
|
+
// 构建前轻预检不携带独立资料;权威准入读取构建 Manifest。
|
|
781
|
+
...(options.version ? { version: options.version } : {}),
|
|
782
|
+
...(options.manifest ? { manifest: JSON.stringify(options.manifest) } : {}),
|
|
783
|
+
release_note: options.releaseNote,
|
|
784
|
+
auto_publish: String(options.autoPublish),
|
|
785
|
+
}, runtime);
|
|
714
786
|
}
|
|
715
|
-
function
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
787
|
+
async function submitUserMiniprogramAudit(options, runtime = {}) {
|
|
788
|
+
return postUserMiniprogramVersionForm(runtimePermissionEnv.SUBMIT_USER_MINIPROGRAM_AUDIT_API_PATH, options, { session_id: options.sessionId, preflight_token: options.preflightToken, artifact_protocol_version: '2' }, runtime);
|
|
789
|
+
}
|
|
790
|
+
async function createUserMiniprogramUploadSession(options, runtime = {}) {
|
|
791
|
+
return postUserMiniprogramVersionForm(CREATE_USER_MINIPROGRAM_UPLOAD_SESSION_API_PATH, options, {
|
|
792
|
+
version: options.version,
|
|
793
|
+
artifact_protocol_version: '2',
|
|
794
|
+
artifact_signature: options.artifactSignature,
|
|
795
|
+
files: JSON.stringify(options.files),
|
|
796
|
+
manifest: JSON.stringify(options.manifest),
|
|
797
|
+
release_note: options.releaseNote,
|
|
798
|
+
auto_publish: String(options.autoPublish),
|
|
799
|
+
}, runtime);
|
|
800
|
+
}
|
|
801
|
+
async function recordUserMiniprogramUploadResult(options, runtime = {}) {
|
|
802
|
+
const fields = {
|
|
803
|
+
version: options.version,
|
|
804
|
+
artifact_protocol_version: '2',
|
|
805
|
+
session_id: options.sessionId,
|
|
806
|
+
files: JSON.stringify(options.files),
|
|
807
|
+
};
|
|
808
|
+
const deadline = Date.now() + COMPANION_FINALIZATION_TIMEOUT_MS;
|
|
809
|
+
for (;;) {
|
|
810
|
+
const result = await postUserMiniprogramVersionForm(RECORD_USER_MINIPROGRAM_UPLOAD_RESULT_API_PATH, options, fields, runtime);
|
|
811
|
+
if (result.artifact_protocol_version !== 2 || !Array.isArray(result.companion_files)) {
|
|
812
|
+
throw new Error('服务端未返回产物协议 v2 Finalize 状态');
|
|
720
813
|
}
|
|
814
|
+
const failed = result.companion_files.find((file) => file.state === 'failed');
|
|
815
|
+
if (failed)
|
|
816
|
+
throw new Error(failed.error || `Companion 归档验证失败:${failed.relative_path}`);
|
|
817
|
+
if (result.complete)
|
|
818
|
+
return;
|
|
819
|
+
if (Date.now() >= deadline)
|
|
820
|
+
throw new Error('Companion 归档验证超时,请稍后重试');
|
|
821
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(250, Math.min(result.retry_after_ms || 1000, 5000))));
|
|
721
822
|
}
|
|
722
|
-
const queryString = params.toString();
|
|
723
|
-
return queryString ? `${path}?${queryString}` : path;
|
|
724
823
|
}
|
|
725
|
-
function
|
|
824
|
+
async function postUserMiniprogramVersionForm(path, options, fields, runtime) {
|
|
825
|
+
const fetchImpl = runtime.fetchImpl ?? fetch;
|
|
826
|
+
const context = index.createHeyboxOpenPlatformRequestContext(options.session, path, {
|
|
827
|
+
contentType: 'application/x-www-form-urlencoded',
|
|
828
|
+
});
|
|
726
829
|
const body = new URLSearchParams();
|
|
830
|
+
body.set('mini_program_id', options.miniProgramId);
|
|
727
831
|
for (const [key, value] of Object.entries(fields)) {
|
|
728
|
-
|
|
729
|
-
continue;
|
|
730
|
-
}
|
|
731
|
-
if (Array.isArray(value)) {
|
|
732
|
-
body.set(key, value.join(','));
|
|
733
|
-
continue;
|
|
734
|
-
}
|
|
735
|
-
if (typeof value === 'object') {
|
|
736
|
-
body.set(key, JSON.stringify(value));
|
|
737
|
-
continue;
|
|
738
|
-
}
|
|
739
|
-
body.set(key, String(value));
|
|
832
|
+
body.set(key, value);
|
|
740
833
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
const env = options.env ?? process.env;
|
|
746
|
-
const apiBaseUrl = index.resolveHeyboxApiBaseUrl({ ...options, env });
|
|
747
|
-
const loginBaseUrl = index.resolveHeyboxLoginBaseUrl({ ...options, env });
|
|
748
|
-
const session = options.session ?? (await (runtime.requireAuthSession ?? index.requireHeyboxAuthSession)({ loginBaseUrl }));
|
|
749
|
-
return {
|
|
750
|
-
apiBaseUrl,
|
|
751
|
-
loginBaseUrl,
|
|
752
|
-
allowUnsafeApiBaseUrl: options.allowUnsafeApiBaseUrl === true || isTruthyEnvFlag(env.HB_SDK_ALLOW_UNSAFE_API_BASE_URL),
|
|
753
|
-
env,
|
|
754
|
-
fetchImpl: runtime.fetchImpl ?? options.fetchImpl ?? fetch,
|
|
755
|
-
session,
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
function createRemoteApiClientForEnvironment(environment) {
|
|
759
|
-
return createRemoteApiClient({
|
|
760
|
-
baseUrl: environment.apiBaseUrl,
|
|
761
|
-
fetchImpl: environment.fetchImpl,
|
|
762
|
-
session: environment.session,
|
|
834
|
+
const response = await fetchImpl(index.createHeyboxApiUrl(runtime.baseUrl ?? context.baseUrl, path, context.platformParams), {
|
|
835
|
+
method: 'POST',
|
|
836
|
+
headers: context.headers,
|
|
837
|
+
body: body.toString(),
|
|
763
838
|
});
|
|
839
|
+
const result = await index.readHeyboxApiEnvelope(response, {
|
|
840
|
+
pathWithQuery: path,
|
|
841
|
+
});
|
|
842
|
+
return result ?? {};
|
|
764
843
|
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
const
|
|
769
|
-
const
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
const
|
|
777
|
-
|
|
778
|
-
|
|
844
|
+
|
|
845
|
+
const DEFAULT_CONCURRENCY = 4;
|
|
846
|
+
async function runUpload(options, runtime = {}) {
|
|
847
|
+
const logger = runtime.logger ?? index.createCliLogger();
|
|
848
|
+
const concurrency = runtime.concurrency ?? DEFAULT_CONCURRENCY;
|
|
849
|
+
const fetchImpl = runtime.fetchImpl ?? fetch;
|
|
850
|
+
const getCDNUploadInfo = runtime.getCDNUploadInfo ?? index.getCDNUploadInfo;
|
|
851
|
+
const getCDNUploadToken = runtime.getCDNUploadToken ?? index.getCDNUploadToken;
|
|
852
|
+
const postCDNUploadCallback = runtime.postCDNUploadCallback ?? index.postCDNUploadCallback;
|
|
853
|
+
const recordUserMiniprogramUploadResult$1 = runtime.recordUserMiniprogramUploadResult ?? recordUserMiniprogramUploadResult;
|
|
854
|
+
const createReadStream = runtime.createReadStream ?? fs$1.createReadStream;
|
|
855
|
+
const cdnBaseUrl = runtime.cdnBaseUrl ?? runtime.baseUrl;
|
|
856
|
+
let createCosClient = runtime.createCosClient;
|
|
857
|
+
if (!createCosClient) {
|
|
858
|
+
const COS = await loadCosConstructor();
|
|
859
|
+
createCosClient = ({ uploadToken }) => createDefaultCosClient(uploadToken, COS);
|
|
779
860
|
}
|
|
780
|
-
const
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
861
|
+
const orderedFiles = runtimePermissionEnv.prepareMiniappArtifactFiles(options.files);
|
|
862
|
+
const batches = [false, true].flatMap(companion => chunkUploadFiles(orderedFiles.filter(file => file.relativePath.startsWith('companions/') === companion), runtimePermissionEnv.MINIAPP_UPLOAD_BATCH_SIZE));
|
|
863
|
+
await logger.task(`正在上传 ${orderedFiles.length} 个文件`, async (taskContext) => {
|
|
864
|
+
logger.debug(`上传并发数: ${concurrency}`);
|
|
865
|
+
logger.debug(`上传批次数: ${batches.length}`);
|
|
866
|
+
let completed = 0;
|
|
867
|
+
for (let batchIndex = 0; batchIndex < batches.length; batchIndex += 1) {
|
|
868
|
+
const batch = batches[batchIndex];
|
|
869
|
+
const companion = batch[0].relativePath.startsWith('companions/');
|
|
870
|
+
const grant = companion ? await (runtime.authorizeCompanionUpload ?? authorizeCompanionUpload)({
|
|
871
|
+
session: options.session, miniProgramId: options.miniProgramId, version: options.version, sessionId: options.uploadSessionId, relativePaths: batch.map(file => file.relativePath),
|
|
872
|
+
}, { baseUrl: runtime.baseUrl, fetchImpl }) : undefined;
|
|
873
|
+
logger.debug(`正在处理上传批次 ${batchIndex + 1}/${batches.length},文件数: ${batch.length}`);
|
|
874
|
+
logger.debug('正在获取 CDN 上传信息');
|
|
875
|
+
const fileInfos = createUploadFileInfos(batch);
|
|
876
|
+
const uploadInfo = grant ?? await getCDNUploadInfo({
|
|
877
|
+
session: options.session,
|
|
878
|
+
scope: runtimePermissionEnv.MINIAPP_UPLOAD_SCOPE,
|
|
879
|
+
fileInfos,
|
|
880
|
+
needCache: false,
|
|
881
|
+
}, { baseUrl: cdnBaseUrl, fetchImpl });
|
|
882
|
+
logger.debug(`CDN bucket: ${uploadInfo.bucket}`);
|
|
883
|
+
logger.debug(`CDN region: ${uploadInfo.region}`);
|
|
884
|
+
validateUploadInfoKeys(batch, uploadInfo.keys);
|
|
885
|
+
const indexedFiles = batch.map((file, index) => ({ file, key: uploadInfo.keys[index] }));
|
|
886
|
+
logger.debug('正在获取本批 CDN 上传凭证');
|
|
887
|
+
let uploadToken;
|
|
888
|
+
try {
|
|
889
|
+
uploadToken = grant ? {
|
|
890
|
+
credentials: { tmpSecretId: grant.tmp_secret_id, tmpSecretKey: grant.tmp_secret_key, sessionToken: grant.session_token },
|
|
891
|
+
startTime: grant.start_time, expiredTime: grant.expired_time,
|
|
892
|
+
} : await getCDNUploadToken({
|
|
893
|
+
session: options.session,
|
|
894
|
+
bucket: uploadInfo.bucket,
|
|
895
|
+
keys: indexedFiles.map((item) => item.key),
|
|
896
|
+
mimetypes: indexedFiles.map((item) => item.file.mimeType),
|
|
897
|
+
isMultipartUpload: 0,
|
|
898
|
+
}, { baseUrl: cdnBaseUrl, fetchImpl });
|
|
899
|
+
}
|
|
900
|
+
catch (error) {
|
|
901
|
+
throw new index.CliError(`获取 CDN 上传凭证失败:${readErrorMessage(error)}`);
|
|
902
|
+
}
|
|
903
|
+
const cos = createCosClient({ session: options.session, uploadToken });
|
|
904
|
+
const successfulKeys = [];
|
|
905
|
+
const queue = indexedFiles.slice();
|
|
906
|
+
let firstUploadError;
|
|
907
|
+
const workers = Array.from({ length: Math.min(concurrency, indexedFiles.length) }, async () => {
|
|
908
|
+
while (queue.length > 0 && !firstUploadError) {
|
|
909
|
+
const uploadTask = queue.shift();
|
|
910
|
+
if (!uploadTask) {
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
try {
|
|
914
|
+
await cos.putObject({
|
|
915
|
+
Bucket: uploadInfo.bucket,
|
|
916
|
+
Region: uploadInfo.region,
|
|
917
|
+
Key: uploadTask.key,
|
|
918
|
+
Body: createReadStream(uploadTask.file.absolutePath),
|
|
919
|
+
ContentLength: uploadTask.file.size,
|
|
920
|
+
ContentType: uploadTask.file.mimeType,
|
|
921
|
+
...(companion ? { Headers: { 'x-cos-forbid-overwrite': 'true' } } : {}),
|
|
922
|
+
}).catch(error => {
|
|
923
|
+
if (companion && isExistingCompanionObject(error))
|
|
924
|
+
return;
|
|
925
|
+
throw error;
|
|
926
|
+
});
|
|
927
|
+
successfulKeys.push(uploadTask.key);
|
|
928
|
+
completed += 1;
|
|
929
|
+
taskContext.update(`正在上传 ${completed}/${orderedFiles.length} 个文件`);
|
|
930
|
+
logger.debug(`[${String(completed).padStart(2)}/${orderedFiles.length}] ok ${uploadTask.file.relativePath} (${formatSize(uploadTask.file.size)})`);
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
completed += 1;
|
|
934
|
+
const message = readErrorMessage(error);
|
|
935
|
+
logger.debug(`[${String(completed).padStart(2)}/${orderedFiles.length}] error ${uploadTask.file.relativePath} -> ${message}`);
|
|
936
|
+
firstUploadError ??= new index.CliError(`上传文件失败:${uploadTask.file.relativePath} -> ${message}`, readVerboseUploadError(uploadTask.file.relativePath, error));
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
await Promise.all(workers);
|
|
941
|
+
if (successfulKeys.length > 0) {
|
|
942
|
+
logger.debug('正在确认 CDN 上传结果');
|
|
943
|
+
if (!companion)
|
|
944
|
+
await postCDNUploadCallback({ session: options.session, keys: successfulKeys, isFinished: true }, { baseUrl: cdnBaseUrl, fetchImpl });
|
|
945
|
+
await recordUserMiniprogramUploadResult$1({
|
|
946
|
+
session: options.session,
|
|
947
|
+
miniProgramId: options.miniProgramId,
|
|
948
|
+
version: options.version,
|
|
949
|
+
sessionId: options.uploadSessionId,
|
|
950
|
+
files: indexedFiles
|
|
951
|
+
.filter((item) => successfulKeys.includes(item.key))
|
|
952
|
+
.map((item) => ({ path: item.file.relativePath, size: item.file.size, sha256: item.file.sha256 })),
|
|
953
|
+
}, { baseUrl: runtime.baseUrl, fetchImpl });
|
|
954
|
+
}
|
|
955
|
+
if (firstUploadError) {
|
|
956
|
+
throw firstUploadError;
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}, { successText: `已上传 ${orderedFiles.length} 个文件` });
|
|
788
960
|
}
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
961
|
+
function chunkUploadFiles(files, batchSize) {
|
|
962
|
+
const batches = [];
|
|
963
|
+
for (let index = 0; index < files.length; index += batchSize) {
|
|
964
|
+
batches.push(files.slice(index, index + batchSize));
|
|
792
965
|
}
|
|
793
|
-
return
|
|
966
|
+
return batches;
|
|
794
967
|
}
|
|
795
|
-
function
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
968
|
+
function isExistingCompanionObject(error) {
|
|
969
|
+
if (!error || typeof error !== 'object')
|
|
970
|
+
return false;
|
|
971
|
+
const value = error;
|
|
972
|
+
return Number(value.statusCode) === 409 && value.code === 'ObjectAlreadyExists';
|
|
799
973
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
974
|
+
function createUploadFileInfos(files) {
|
|
975
|
+
return files.map((file) => ({
|
|
976
|
+
name: file.relativePath.split('/').pop() ?? file.relativePath,
|
|
977
|
+
mimetype: file.mimeType,
|
|
978
|
+
fsize: file.size,
|
|
979
|
+
path: file.key,
|
|
980
|
+
}));
|
|
981
|
+
}
|
|
982
|
+
function validateUploadInfoKeys(files, keys) {
|
|
983
|
+
if (keys.length !== files.length) {
|
|
984
|
+
throw new index.CliError(`CDN 上传接口返回 key 数量异常:期望 ${files.length},实际 ${keys.length}`);
|
|
985
|
+
}
|
|
986
|
+
for (let index$1 = 0; index$1 < files.length; index$1 += 1) {
|
|
987
|
+
const expectedKey = files[index$1].key;
|
|
988
|
+
const actualKey = keys[index$1];
|
|
989
|
+
if (actualKey !== expectedKey) {
|
|
990
|
+
throw new index.CliError(`CDN 上传接口返回 key 异常:${files[index$1].relativePath}`, [`CDN 上传接口返回 key 异常:${files[index$1].relativePath}`, `expected: ${expectedKey}`, `actual: ${actualKey}`].join('\n'));
|
|
991
|
+
}
|
|
814
992
|
}
|
|
993
|
+
}
|
|
994
|
+
function createDefaultCosClient(uploadToken, COS) {
|
|
995
|
+
const cos = new COS({
|
|
996
|
+
getAuthorization(_input, callback) {
|
|
997
|
+
callback({
|
|
998
|
+
TmpSecretId: uploadToken.credentials.tmpSecretId,
|
|
999
|
+
TmpSecretKey: uploadToken.credentials.tmpSecretKey,
|
|
1000
|
+
XCosSecurityToken: uploadToken.credentials.sessionToken,
|
|
1001
|
+
StartTime: uploadToken.startTime,
|
|
1002
|
+
ExpiredTime: uploadToken.expiredTime,
|
|
1003
|
+
});
|
|
1004
|
+
},
|
|
1005
|
+
});
|
|
815
1006
|
return {
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
1007
|
+
putObject(params) {
|
|
1008
|
+
return new Promise((resolve, reject) => {
|
|
1009
|
+
cos.putObject(params, (err, result) => {
|
|
1010
|
+
if (err) {
|
|
1011
|
+
reject(err);
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
resolve(result);
|
|
1015
|
+
});
|
|
1016
|
+
});
|
|
1017
|
+
},
|
|
826
1018
|
};
|
|
827
1019
|
}
|
|
828
|
-
function
|
|
829
|
-
return
|
|
1020
|
+
async function loadCosConstructor() {
|
|
1021
|
+
const cosModule = await Promise.resolve().then(function () { return require('./index-D4TFWbsi.cjs'); }).then(function (n) { return n.index; });
|
|
1022
|
+
return cosModule.default;
|
|
830
1023
|
}
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
? index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
|
|
840
|
-
localDevGrant: context.localDevGrant }).runtimePermissions
|
|
841
|
-
: context.runtimePermissions);
|
|
842
|
-
const networkRequest = parsed.permissions.network;
|
|
843
|
-
return parsed.valid && networkRequest
|
|
844
|
-
? {
|
|
845
|
-
networkRequest: {
|
|
846
|
-
status: networkRequest.status,
|
|
847
|
-
useOfficialDomain: networkRequest.config.useOfficialDomain === true,
|
|
848
|
-
},
|
|
849
|
-
}
|
|
850
|
-
: cloneDefaultPermissionState();
|
|
1024
|
+
function formatSize(bytes) {
|
|
1025
|
+
if (bytes < 1024) {
|
|
1026
|
+
return `${bytes} B`;
|
|
1027
|
+
}
|
|
1028
|
+
if (bytes < 1024 * 1024) {
|
|
1029
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
1030
|
+
}
|
|
1031
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
851
1032
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
return { schema_version: 1, entries: [] };
|
|
1033
|
+
function readErrorMessage(error) {
|
|
1034
|
+
if (error instanceof Error && error.message) {
|
|
1035
|
+
return error.message;
|
|
856
1036
|
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
const
|
|
860
|
-
|
|
1037
|
+
if (isRecord(error)) {
|
|
1038
|
+
const primary = readStringField(error, ['message', 'Message', 'errorMessage', 'msg']);
|
|
1039
|
+
const code = readStringField(error, ['code', 'Code', 'errorCode', 'name']);
|
|
1040
|
+
const statusCode = readStringField(error, ['statusCode']);
|
|
1041
|
+
return [code, statusCode, primary].filter(Boolean).join(' ') || JSON.stringify(error);
|
|
861
1042
|
}
|
|
862
|
-
return
|
|
1043
|
+
return String(error);
|
|
863
1044
|
}
|
|
864
|
-
function
|
|
865
|
-
return {
|
|
866
|
-
networkRequest: { ...DEFAULT_PERMISSION_STATE.networkRequest },
|
|
867
|
-
};
|
|
1045
|
+
function readVerboseUploadError(relativePath, error) {
|
|
1046
|
+
return [`上传文件失败:${relativePath}`, `原始错误:${readErrorMessage(error)}`].join('\n');
|
|
868
1047
|
}
|
|
869
|
-
function
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
continue;
|
|
879
|
-
entries.push(key === 'network'
|
|
880
|
-
? {
|
|
881
|
-
key,
|
|
882
|
-
status: state.networkRequest.status,
|
|
883
|
-
config: { useOfficialDomain },
|
|
884
|
-
}
|
|
885
|
-
: key === 'user_game_data' || key === 'post'
|
|
886
|
-
? {
|
|
887
|
-
key,
|
|
888
|
-
status: entry.status,
|
|
889
|
-
// 浏览器模拟不能丢掉资源清单或关联帖的读写声明。
|
|
890
|
-
config: { ...entry.config },
|
|
891
|
-
}
|
|
892
|
-
: {
|
|
893
|
-
key,
|
|
894
|
-
status: entry.status,
|
|
895
|
-
config: {},
|
|
896
|
-
});
|
|
1048
|
+
function readStringField(record, fields) {
|
|
1049
|
+
for (const field of fields) {
|
|
1050
|
+
const value = record[field];
|
|
1051
|
+
if (typeof value === 'string' && value.trim()) {
|
|
1052
|
+
return value.trim();
|
|
1053
|
+
}
|
|
1054
|
+
if (typeof value === 'number') {
|
|
1055
|
+
return String(value);
|
|
1056
|
+
}
|
|
897
1057
|
}
|
|
898
|
-
|
|
899
|
-
? snapshot.revision
|
|
900
|
-
: undefined;
|
|
901
|
-
return {
|
|
902
|
-
schema_version: 1,
|
|
903
|
-
...(revision === undefined ? {} : { revision }),
|
|
904
|
-
entries,
|
|
905
|
-
};
|
|
1058
|
+
return '';
|
|
906
1059
|
}
|
|
907
|
-
function
|
|
908
|
-
return
|
|
1060
|
+
function isRecord(value) {
|
|
1061
|
+
return Object.prototype.toString.call(value) === '[object Object]';
|
|
909
1062
|
}
|
|
910
1063
|
|
|
911
1064
|
/** 发布提示使用显式声明与远端主体批准策略,不消费本地调试授权。 */
|
|
@@ -926,11 +1079,6 @@ function getUnapprovedPermissionWarning(local, approvals, partyType) {
|
|
|
926
1079
|
return missing.length ? `以下本地声明权限线上未批准,发布后不可用:${missing.join('、')}。本地调试可用不代表线上已批准。` : undefined;
|
|
927
1080
|
}
|
|
928
1081
|
|
|
929
|
-
const SUPPORTED_PACKAGE_MANAGERS = [
|
|
930
|
-
{ name: 'pnpm', lockfile: 'pnpm-lock.yaml' },
|
|
931
|
-
{ name: 'yarn', lockfile: 'yarn.lock' },
|
|
932
|
-
{ name: 'npm', lockfile: 'package-lock.json' },
|
|
933
|
-
];
|
|
934
1082
|
const MIME_BY_EXT = {
|
|
935
1083
|
'.css': 'text/css',
|
|
936
1084
|
'.gif': 'image/gif',
|
|
@@ -964,11 +1112,12 @@ async function runDeployCommand(options, runtime = {}) {
|
|
|
964
1112
|
if (typeof miniProgramId !== 'string' || !miniProgramId.trim()) {
|
|
965
1113
|
throw new Error('未在 package.json 中找到 heybox.miniProgramId,请先配置 mini program id');
|
|
966
1114
|
}
|
|
967
|
-
if (runtime.expectedProject &&
|
|
968
|
-
packageJson.version !== runtime.expectedProject.version)) {
|
|
1115
|
+
if (runtime.expectedProject &&
|
|
1116
|
+
(miniProgramId.trim() !== runtime.expectedProject.miniProgramId || packageJson.version !== runtime.expectedProject.version)) {
|
|
969
1117
|
throw new index.CliError('项目 ID 或版本已变化,请刷新上传发布面板后重新核对');
|
|
970
1118
|
}
|
|
971
1119
|
const declaredPlatforms = runtimePermissionEnv.readMiniappPlatformsFromPackageJson(projectRoot);
|
|
1120
|
+
logger.info(`${getPcAdaptationSuggestion(declaredPlatforms)} PC 适配:${PC_ADAPTATION_GUIDE_URL} 客户端下载:${PC_CLIENT_DOWNLOAD_URL}`);
|
|
972
1121
|
const declaredWindow = runtimePermissionEnv.readMiniappWindowFromPackageJson(projectRoot);
|
|
973
1122
|
let declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
|
|
974
1123
|
const declaredCategory = runtimePermissionEnv.readMiniappCategoryFromPackageJson(projectRoot);
|
|
@@ -979,7 +1128,10 @@ async function runDeployCommand(options, runtime = {}) {
|
|
|
979
1128
|
const deploy = async () => {
|
|
980
1129
|
if (!options.skipGameBindingGuide) {
|
|
981
1130
|
await gameBindingGuide.guideGameBindings(gameBindingGuide.createGameBindingsBackend(projectRoot, { session, fetchImpl: runtime.fetchImpl }), {
|
|
982
|
-
isTTY: runtime.isTTY,
|
|
1131
|
+
isTTY: runtime.isTTY,
|
|
1132
|
+
stdin: runtime.stdin,
|
|
1133
|
+
stderr: runtime.stderr,
|
|
1134
|
+
question: runtime.gameBindingQuestion,
|
|
983
1135
|
});
|
|
984
1136
|
packageJson = await readPackageJson(projectRoot);
|
|
985
1137
|
declaredBindAppIds = runtimePermissionEnv.readMiniappBindAppIdsFromPackageJson(projectRoot);
|
|
@@ -1028,7 +1180,8 @@ async function runDeployCommand(options, runtime = {}) {
|
|
|
1028
1180
|
firstParty = detail.party_type === 'first_party';
|
|
1029
1181
|
skipPlatformCsp = shouldSkipMiniappPlatformCsp(effectivePermissions);
|
|
1030
1182
|
networkPolicy = effectivePermissions.entries.some((entry) => entry.key === 'network' && entry.status === 'enabled')
|
|
1031
|
-
? detail.network_policy
|
|
1183
|
+
? detail.network_policy
|
|
1184
|
+
: undefined;
|
|
1032
1185
|
const permissionWarning = getUnapprovedPermissionWarning(localPermissions, detail.runtime_permissions, detail.party_type);
|
|
1033
1186
|
if (permissionWarning)
|
|
1034
1187
|
logger.warn(permissionWarning);
|
|
@@ -1201,7 +1354,7 @@ async function runDeployCommand(options, runtime = {}) {
|
|
|
1201
1354
|
}
|
|
1202
1355
|
try {
|
|
1203
1356
|
const submitOptions = { session, miniProgramId, sessionId: uploadSessionId, preflightToken };
|
|
1204
|
-
submitAuditResult = await logger.task('正在提交审核', () => (runtime.submitUserMiniprogramAudit ?? submitUserMiniprogramAudit
|
|
1357
|
+
submitAuditResult = await logger.task('正在提交审核', () => (runtime.submitUserMiniprogramAudit ?? submitUserMiniprogramAudit)(submitOptions, {
|
|
1205
1358
|
baseUrl: apiBaseUrl,
|
|
1206
1359
|
fetchImpl: runtime.fetchImpl,
|
|
1207
1360
|
}), { successText: '审核提交完成' });
|
|
@@ -1226,7 +1379,7 @@ async function runDeployCommand(options, runtime = {}) {
|
|
|
1226
1379
|
version,
|
|
1227
1380
|
};
|
|
1228
1381
|
};
|
|
1229
|
-
return (runtime.withDeployLock ?? index.withDeployLock)({ apiBaseUrl, miniProgramId, version: uploadVersion }, deploy);
|
|
1382
|
+
return (runtime.withDeployLock ?? index.withDeployLock)({ apiBaseUrl, miniProgramId, version: uploadVersion }, () => withProjectArtifactLock(projectRoot, deploy));
|
|
1230
1383
|
}
|
|
1231
1384
|
function printDeploySuccess(options) {
|
|
1232
1385
|
options.logger.success(`提交审核成功:${options.miniProgramId} ${options.version}`);
|
|
@@ -1290,78 +1443,20 @@ async function maybePromptReleaseNote(runtime) {
|
|
|
1290
1443
|
async function runVersionPrecheck(options, runtime, apiBaseUrl, projectRoot, logger) {
|
|
1291
1444
|
try {
|
|
1292
1445
|
const label = options.version ?? '';
|
|
1293
|
-
return await logger.task(`正在预检版本 ${label}`, () => (runtime.precheckUserMiniprogramVersion ?? precheckUserMiniprogramVersion
|
|
1446
|
+
return await logger.task(`正在预检版本 ${label}`, () => (runtime.precheckUserMiniprogramVersion ?? precheckUserMiniprogramVersion)(options, {
|
|
1294
1447
|
baseUrl: apiBaseUrl,
|
|
1295
1448
|
fetchImpl: runtime.fetchImpl,
|
|
1296
1449
|
}), { successText: `版本 ${label} 预检通过` });
|
|
1297
1450
|
}
|
|
1298
1451
|
catch (error) {
|
|
1299
|
-
throw translateHeyboxDeployError(error, {
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
if (fs$1.existsSync(path.join(projectRoot, candidate.lockfile))) {
|
|
1305
|
-
return candidate.name;
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
return 'npm';
|
|
1309
|
-
}
|
|
1310
|
-
async function runBuildScript(pm, cwd, spawnImpl, options) {
|
|
1311
|
-
const buildScript = await readProjectBuildScript(cwd);
|
|
1312
|
-
await new Promise((resolve, reject) => {
|
|
1313
|
-
const pipeStdoutToStderr = options.outputMode === 'stderr';
|
|
1314
|
-
const buildArgs = createBuildArgs(pm, options.mode, buildScript);
|
|
1315
|
-
const isWindows = options.platform === 'win32';
|
|
1316
|
-
const [executable, args] = isWindows ? createWindowsBuildCommand(pm, buildArgs) : [pm, buildArgs];
|
|
1317
|
-
const child = spawnImpl(executable, args, {
|
|
1318
|
-
cwd,
|
|
1319
|
-
env: { ...process.env, ...options.env },
|
|
1320
|
-
...(isWindows ? { shell: false, windowsVerbatimArguments: true } : {}),
|
|
1321
|
-
stdio: pipeStdoutToStderr ? ['inherit', 'pipe', 'inherit'] : 'inherit',
|
|
1322
|
-
});
|
|
1323
|
-
if (pipeStdoutToStderr) {
|
|
1324
|
-
child.stdout?.on('data', (chunk) => {
|
|
1325
|
-
(options.stderr ?? process.stderr).write(chunk);
|
|
1326
|
-
});
|
|
1327
|
-
}
|
|
1328
|
-
child.on('error', reject);
|
|
1329
|
-
child.on('exit', (code) => {
|
|
1330
|
-
if (code === 0) {
|
|
1331
|
-
resolve();
|
|
1332
|
-
}
|
|
1333
|
-
else {
|
|
1334
|
-
reject(new Error(`${pm} run build exited with code ${code ?? 'null'}`));
|
|
1335
|
-
}
|
|
1452
|
+
throw translateHeyboxDeployError(error, {
|
|
1453
|
+
projectRoot,
|
|
1454
|
+
stage: 'precheck',
|
|
1455
|
+
version: options.version ?? '',
|
|
1456
|
+
workbench: Boolean(runtime.expectedProject),
|
|
1336
1457
|
});
|
|
1337
|
-
});
|
|
1338
|
-
}
|
|
1339
|
-
function createWindowsBuildCommand(pm, buildArgs) {
|
|
1340
|
-
const command = `${pm}.cmd ${buildArgs.map(escapeWindowsCommandArgument).join(' ')}`;
|
|
1341
|
-
return ['cmd.exe', ['/d', '/s', '/c', `"${command}"`]];
|
|
1342
|
-
}
|
|
1343
|
-
function validateBuildMode(mode, platform) {
|
|
1344
|
-
if (platform === 'win32' && mode && !/^[A-Za-z0-9._-]+$/.test(mode)) {
|
|
1345
|
-
throw new Error('Windows 下 HB_SDK_ENV 仅支持字母、数字、点、下划线和连字符');
|
|
1346
|
-
}
|
|
1347
|
-
return mode;
|
|
1348
|
-
}
|
|
1349
|
-
function escapeWindowsCommandArgument(argument) {
|
|
1350
|
-
return `"${argument}"`;
|
|
1351
|
-
}
|
|
1352
|
-
async function readProjectBuildScript(projectRoot) {
|
|
1353
|
-
try {
|
|
1354
|
-
const packageJson = JSON.parse(await fs.readFile(path.join(projectRoot, 'package.json'), 'utf8'));
|
|
1355
|
-
return typeof packageJson.scripts?.build === 'string' ? packageJson.scripts.build : '';
|
|
1356
|
-
}
|
|
1357
|
-
catch {
|
|
1358
|
-
return '';
|
|
1359
1458
|
}
|
|
1360
1459
|
}
|
|
1361
|
-
function createBuildArgs(pm, mode, buildScript) {
|
|
1362
|
-
const modeOption = /\bhb-sdk\s+build\b/.test(buildScript) ? '--env' : '--mode';
|
|
1363
|
-
return ['run', 'build', ...(mode ? [...(pm === 'npm' ? ['--'] : []), modeOption, mode] : [])];
|
|
1364
|
-
}
|
|
1365
1460
|
function inferMimeType(fileName) {
|
|
1366
1461
|
return MIME_BY_EXT[path.extname(fileName).toLowerCase()] || 'application/octet-stream';
|
|
1367
1462
|
}
|
|
@@ -2565,14 +2660,24 @@ var remote = /*#__PURE__*/Object.freeze({
|
|
|
2565
2660
|
runRemoteCommand: runRemoteCommand
|
|
2566
2661
|
});
|
|
2567
2662
|
|
|
2663
|
+
exports.PC_ONBOARDING_EVENT_PATH = PC_ONBOARDING_EVENT_PATH;
|
|
2664
|
+
exports.PC_ONBOARDING_PATH = PC_ONBOARDING_PATH;
|
|
2665
|
+
exports.computeMiniappArtifactReceipt = computeMiniappArtifactReceipt;
|
|
2568
2666
|
exports.createBrowserDevPermissionState = createBrowserDevPermissionState;
|
|
2569
2667
|
exports.createLocalDevLaunchToken = createLocalDevLaunchToken;
|
|
2570
2668
|
exports.createMobileDevSessionRuntimePermissions = createMobileDevSessionRuntimePermissions;
|
|
2669
|
+
exports.detectPackageManager = detectPackageManager;
|
|
2571
2670
|
exports.getBoundMiniProgram = getBoundMiniProgram;
|
|
2671
|
+
exports.getPcAdaptationSuggestion = getPcAdaptationSuggestion;
|
|
2572
2672
|
exports.migrateBasicInfo = migrateBasicInfo;
|
|
2673
|
+
exports.parsePcOnboardingEvent = parsePcOnboardingEvent;
|
|
2573
2674
|
exports.readRemoteMiniProgramPreview = readRemoteMiniProgramPreview;
|
|
2574
2675
|
exports.remote = remote;
|
|
2575
2676
|
exports.resolveBrowserFakeContext = resolveBrowserFakeContext;
|
|
2677
|
+
exports.resolveRemoteEnvironment = resolveRemoteEnvironment;
|
|
2678
|
+
exports.runBuildScript = runBuildScript;
|
|
2576
2679
|
exports.runRemoteCommand = runRemoteCommand;
|
|
2577
2680
|
exports.shouldSkipMiniappPlatformCsp = shouldSkipMiniappPlatformCsp;
|
|
2681
|
+
exports.validateBuildMode = validateBuildMode;
|
|
2578
2682
|
exports.validateDeployReleaseNote = validateDeployReleaseNote;
|
|
2683
|
+
exports.withProjectArtifactLock = withProjectArtifactLock;
|