@heybox/hb-sdk 0.1.3 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +149 -345
  2. package/bin/hb-sdk.cjs +3 -0
  3. package/dist/cli.cjs +10117 -0
  4. package/dist/devtools/mock-host/index.html +252 -0
  5. package/dist/devtools/mock-host/main.js +975 -0
  6. package/dist/index.cjs.js +474 -85
  7. package/dist/index.esm.js +465 -71
  8. package/dist/protocol.cjs.js +163 -0
  9. package/dist/protocol.esm.js +148 -0
  10. package/dist/templates/vue3-vite-ts/.gitignore.ejs +5 -0
  11. package/dist/templates/vue3-vite-ts/README.md.ejs +42 -0
  12. package/dist/templates/vue3-vite-ts/index.html.ejs +12 -0
  13. package/dist/templates/vue3-vite-ts/package.json.ejs +28 -0
  14. package/dist/templates/vue3-vite-ts/src/App.vue +63 -0
  15. package/dist/templates/vue3-vite-ts/src/__tests__/App.spec.ts +67 -0
  16. package/dist/templates/vue3-vite-ts/src/main.ts +5 -0
  17. package/dist/templates/vue3-vite-ts/src/styles.css +60 -0
  18. package/dist/templates/vue3-vite-ts/src/vite-env.d.ts +1 -0
  19. package/dist/templates/vue3-vite-ts/tsconfig.app.json +17 -0
  20. package/dist/templates/vue3-vite-ts/tsconfig.json +11 -0
  21. package/dist/templates/vue3-vite-ts/tsconfig.node.json +11 -0
  22. package/dist/templates/vue3-vite-ts/vite.config.ts +6 -0
  23. package/dist/templates/vue3-vite-ts/vitest.config.ts +10 -0
  24. package/package.json +30 -5
  25. package/skill/SKILL.md +95 -0
  26. package/skill/references/api-protocol.md +135 -0
  27. package/skill/references/api-root.md +346 -0
  28. package/skill/references/cli.md +360 -0
  29. package/skill/references/examples.md +107 -0
  30. package/skill/references/llms-index.md +44 -0
  31. package/skill/references/recipes.md +374 -0
  32. package/skill/references/safety-boundaries.md +28 -0
  33. package/skill/references/smoke-evaluation.md +24 -0
  34. package/skill/scripts/check-references.mjs +14 -0
  35. package/skill/scripts/package-skill.mjs +60 -0
  36. package/skill/scripts/package-skill.sh +6 -0
  37. package/skill/scripts/skill-metadata.mjs +74 -0
  38. package/skill/scripts/sync-references.mjs +541 -0
  39. package/skill/scripts/validate-skill.mjs +233 -0
  40. package/skill/skill.json +11 -0
  41. package/types/core/client.d.ts +23 -3
  42. package/types/core/errors.d.ts +45 -2
  43. package/types/core/sdk.d.ts +78 -10
  44. package/types/core/singleton.d.ts +33 -7
  45. package/types/core/utils.d.ts +2 -0
  46. package/types/index.d.ts +14 -6
  47. package/types/modules/auth/index.d.ts +35 -0
  48. package/types/modules/network/index.d.ts +120 -0
  49. package/types/modules/share/index.d.ts +9 -5
  50. package/types/modules/share/screenshot.d.ts +9 -3
  51. package/types/modules/share/show-share-menu.d.ts +9 -3
  52. package/types/modules/share/types.d.ts +24 -4
  53. package/types/modules/storage/index.d.ts +56 -0
  54. package/types/modules/user/get-info.d.ts +6 -2
  55. package/types/modules/user/index.d.ts +8 -10
  56. package/types/modules/user/types.d.ts +1 -0
  57. package/types/modules/viewport/index.d.ts +71 -0
  58. package/types/protocol/capabilities.d.ts +180 -0
  59. package/types/protocol/guards.d.ts +6 -1
  60. package/types/protocol/types.d.ts +19 -4
  61. package/types/protocol.d.ts +13 -0
  62. package/types/modules/system/get-storage.d.ts +0 -15
  63. package/types/modules/system/get-window-info.d.ts +0 -16
  64. package/types/modules/system/index.d.ts +0 -23
  65. package/types/modules/system/set-storage.d.ts +0 -12
  66. package/types/modules/system/types.d.ts +0 -34
  67. package/types/modules/user/login.d.ts +0 -18
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heybox/hb-sdk",
3
- "version": "0.1.3",
3
+ "version": "0.2.0-alpha.1",
4
4
  "description": "",
5
5
  "exports": {
6
6
  ".": {
@@ -9,25 +9,46 @@
9
9
  "node": "./dist/index.cjs.js",
10
10
  "browser": "./dist/index.esm.js",
11
11
  "default": "./dist/index.esm.js"
12
+ },
13
+ "./protocol": {
14
+ "types": "./types/protocol.d.ts",
15
+ "heybox": "./src/protocol.ts",
16
+ "node": "./dist/protocol.cjs.js",
17
+ "browser": "./dist/protocol.esm.js",
18
+ "default": "./dist/protocol.esm.js"
12
19
  }
13
20
  },
21
+ "bin": {
22
+ "hb-sdk": "./bin/hb-sdk.cjs"
23
+ },
14
24
  "files": [
25
+ "bin",
15
26
  "dist",
27
+ "skill",
16
28
  "types"
17
29
  ],
18
30
  "keywords": [],
19
31
  "author": "",
20
32
  "license": "ISC",
21
- "dependencies": {
22
- "@heybox/utils": "^2.1.1"
23
- },
24
33
  "devDependencies": {
34
+ "@rollup/plugin-commonjs": "^28.0.6",
35
+ "@rollup/plugin-json": "^6.1.0",
36
+ "@rollup/plugin-node-resolve": "^16.0.1",
25
37
  "@heybox/hb-types": "^1.0.1",
26
38
  "@vitejs/plugin-vue2": "^2.3.3",
27
39
  "@rollup/plugin-typescript": "^11.1.6",
40
+ "@types/ejs": "^3.1.5",
41
+ "@types/fs-extra": "^11.0.4",
28
42
  "@types/node": "24.10.1",
29
43
  "@vitest/coverage-v8": "^3.2.4",
44
+ "commander": "^12.1.0",
45
+ "ejs": "^3.1.10",
46
+ "env-paths": "^2.2.1",
47
+ "fs-extra": "^11.3.0",
48
+ "get-port": "^7.1.0",
30
49
  "happy-dom": "^19.0.2",
50
+ "open": "^10.2.0",
51
+ "picocolors": "^1.1.1",
31
52
  "rimraf": "^5.0.5",
32
53
  "rollup": "^4.52.4",
33
54
  "typescript": "^5.9.3",
@@ -57,10 +78,14 @@
57
78
  },
58
79
  "scripts": {
59
80
  "dev": "vite",
60
- "build:package": "nx exec -- sh -c \"pnpm run clean && pnpm run build:lib && pnpm run build:types\"",
81
+ "build:package": "nx exec -- sh -c \"pnpm run clean && pnpm run build:lib && pnpm run build:cli && pnpm run build:mock-host && pnpm run build:templates && pnpm run build:types\"",
61
82
  "build:watch": "pnpm run build:lib -w & pnpm run build:types -w",
62
83
  "build:lib": "rollup -c rollup.config.ts --configPlugin 'typescript={\"tsconfig\":\"tsconfig.build.json\"}'",
84
+ "build:cli": "rollup -c rollup.config.ts --environment HB_SDK_BUILD:cli --configPlugin 'typescript={\"tsconfig\":\"tsconfig.build.json\"}'",
85
+ "build:mock-host": "node scripts/copy-mock-host.cjs",
86
+ "build:templates": "node scripts/copy-cli-templates.cjs",
63
87
  "build:types": "tsc -p tsconfig.dts.json",
88
+ "check:boundary": "node scripts/check-boundary.cjs",
64
89
  "clean": "rimraf ./dist && rimraf ./types",
65
90
  "test:unit": "NODE_OPTIONS='--conditions=heybox' vitest run",
66
91
  "test:unit:coverage": "NODE_OPTIONS='--conditions=heybox' vitest run --coverage",
package/skill/SKILL.md ADDED
@@ -0,0 +1,95 @@
1
+ ---
2
+ name: hb-sdk
3
+ description: Uses @heybox/hb-sdk and its hb-sdk CLI for Heybox external mini-program iframe pages, local mock development, template creation, skill version checks, and host/runtime protocol integration. Use for ready/auth/user/share/viewport/storage/network APIs, lifecycle events, hb-sdk create/dev/login/doctor, mock runtime debugging, custom SDK instances, or @heybox/hb-sdk/protocol contracts. Don't use for raw postMessage bridge construction in app code, direct cookie/token access, internal Heybox client protocols, separate mock runtimes, or non-Heybox SDKs.
4
+ ---
5
+
6
+ # hb-sdk Agent Procedure
7
+
8
+ Apply these instructions when writing, reviewing, or debugging code that consumes `@heybox/hb-sdk` or uses the companion `hb-sdk` CLI.
9
+
10
+ ## Step 1: Classify the task
11
+
12
+ 1. If the task is iframe mini-program business code, use the root package import path `@heybox/hb-sdk`.
13
+ 2. If the task is parent-container runtime, bridge-server, protocol contract, or `@heybox/hb-sdk-runtime` work, use `@heybox/hb-sdk/protocol` only for shared constants and types.
14
+ 3. If the task is project scaffolding, local Vite startup, browser mock runtime, CLI login cache, Agent Skill version diagnosis, or CLI troubleshooting, use the `hb-sdk` CLI workflow.
15
+ 4. If the task asks for direct login-state extraction, cookies, tokens, raw Heybox client protocols, or internal hb-sdk package paths, refuse that approach and use the public SDK or CLI boundary instead.
16
+ 5. If the task is not about Heybox external mini-program SDK usage, CLI usage, mock runtime, or protocol contracts, do not apply this skill.
17
+
18
+ ## Step 2: Load only the needed reference
19
+
20
+ 1. For root SDK imports, singleton usage, modules, and errors, read `references/api-root.md`.
21
+ 2. For host/runtime protocol contracts only, read `references/api-protocol.md`. Do not use this reference to build iframe business-code bridge messages.
22
+ 3. For common business flows, read `references/recipes.md`.
23
+ 4. For CLI commands, local mock runtime, generated templates, CLI login cache, Agent Skill doctor, and update reminders, read `references/cli.md`.
24
+ 5. For allowed/forbidden capabilities and security boundaries, read `references/safety-boundaries.md`.
25
+ 6. For generated documentation provenance and deeper API lookup paths, read `references/llms-index.md`.
26
+ 7. For smoke-test expectations, positive examples, and anti-examples, read `references/examples.md`.
27
+ 8. For evaluating whether another agent followed this skill, read `references/smoke-evaluation.md`.
28
+
29
+ ## Step 3: Follow import rules
30
+
31
+ 1. Import app-facing SDK APIs from `@heybox/hb-sdk`.
32
+ 2. Import protocol contracts from `@heybox/hb-sdk/protocol` only in host/runtime/protocol-maintenance code.
33
+ 3. Never import from internal hb-sdk implementation paths; only use the documented package entrypoints.
34
+ 4. Prefer named imports for focused code and the default `hbSDK` singleton for compact page-level examples.
35
+
36
+ ## Step 4: Implement iframe mini-program code
37
+
38
+ 1. Call `await ready()` or `await hbSDK.ready()` near page startup when the page uses SDK capabilities.
39
+ 2. Use `user.getInfo()` to read current login state without triggering login.
40
+ 3. Use `auth.login()` only when the user action requires login.
41
+ 4. Handle `HbMiniProgramSDKError` for bridge/runtime/protocol failures.
42
+ 5. Handle `HbMiniProgramNetworkError` separately when HTTP completed but `validateStatus` rejected the status.
43
+ 6. Cancel lifecycle/event subscriptions returned by `on()` when the page or component unmounts.
44
+ 7. Call `destroy()` on independent instances created by `createMiniProgramSDK()` when they are no longer needed.
45
+
46
+ ## Step 5: Use CLI workflows
47
+
48
+ 1. Use `hb-sdk create <project-name>` to scaffold a standalone external mini-program template.
49
+ 2. Use `hb-sdk dev` for local browser debugging through the built-in mock runtime host.
50
+ 3. Use the Mock runtime host's "在 Mac 版 APP 中启动" button when the page needs to be loaded by the real Heybox mini-program container.
51
+ 4. Use `--port`, `--mock-port`, `--host`, and `--no-open` when the default Vite/mock ports, host, or browser opening behavior need to be controlled.
52
+ 5. Use `hb-sdk login`, `hb-sdk login status`, and `hb-sdk login clear` only for the CLI's own Heybox auth cache.
53
+ 6. Use `hb-sdk doctor` to diagnose whether the local `hb-sdk` skill matches the installed SDK and remote latest skill metadata.
54
+ 7. Do not use `hb-sdk doctor` to auto-install skills; when installation or refresh is needed, tell the user to run `npx skills add https://open.xiaoheihe.cn/agent-skills/hb-sdk`.
55
+ 8. If doctor reports `SDK_MISMATCH`, upgrade `@heybox/hb-sdk@latest` before reinstalling the skill.
56
+ 9. Do not treat CLI login cache as iframe SDK login state; it does not change `auth.login()`, `user.getInfo()`, `network.request()`, or mock-user behavior.
57
+ 10. Keep the CLI and mock runtime under `@heybox/hb-sdk`; do not create or revive a separate mock runtime package.
58
+
59
+ ## Step 6: Preserve capability boundaries
60
+
61
+ For iframe mini-program business code:
62
+
63
+ 1. Do not read or request tokens, cookies, phone numbers, or private credentials from the SDK.
64
+ 2. Do not expose raw share protocol fields, JS callbacks, activity reporting, custom buttons, post publishing, or upload-only flows.
65
+ 3. Do not use unsupported storage operations such as delete, clear, info listing, or global client storage access.
66
+ 4. Do not pass raw host protocol fields through `network.request`; use only the public axios-like request config.
67
+ 5. Do not construct bridge envelopes, nonce logic, or raw `postMessage` calls.
68
+
69
+ For CLI and local development:
70
+
71
+ 1. Do not print, persist in templates, or pass through pkey, cookies, tokens, or private credentials.
72
+ 2. Do not use `hb-sdk login` as a workaround for iframe SDK authentication.
73
+ 3. Do not bypass `hb-sdk dev` by adding a second browser mock host.
74
+
75
+ For host/runtime/protocol-maintenance code:
76
+
77
+ 1. Use `@heybox/hb-sdk/protocol` for shared constants and type contracts.
78
+ 2. Keep raw protocol details inside the host/runtime boundary; do not leak them into app-facing SDK examples or iframe business code.
79
+ 3. Keep bridge handshake and nonce behavior idempotent and compatible with existing SDK clients.
80
+
81
+ ## Step 7: Validate changes
82
+
83
+ 1. Run the nearest package tests and builds with repo-native commands when editing this repository.
84
+ 2. When modifying this repo's source skill at `packages/hb-sdk/skill`, run:
85
+ - `node packages/hb-sdk/skill/scripts/check-references.mjs`
86
+ - `node packages/hb-sdk/skill/scripts/validate-skill.mjs`
87
+ - `node packages/hb-sdk/skill/scripts/package-skill.mjs`
88
+ 3. When modifying CLI, mock runtime, package exports, or package dependency direction, also run:
89
+ - `pnpm --filter @heybox/hb-sdk run check:boundary`
90
+ - `pnpm --filter @heybox/hb-sdk run test:unit`
91
+ 4. Inspect the generated zip before distribution:
92
+ - `unzip -l packages/hb-sdk/hb-sdk.zip | sed -n '1,120p'`
93
+ 5. Verify public payload sync before publishing:
94
+ - `pnpm --filter @heybox-spa/open run sync:agent-skills`
95
+ - `pnpm --filter @heybox-spa/open run check:agent-skills`
@@ -0,0 +1,135 @@
1
+ # Protocol API reference
2
+
3
+ > Generated by `node packages/hb-sdk/skill/scripts/sync-references.mjs` from the public hb-sdk source/docs. Do not edit by hand; update sources or this generator instead.
4
+
5
+ ## Sources
6
+
7
+ - packages/hb-sdk/src/protocol.ts
8
+ - packages/hb-sdk/README.md
9
+ - apps/h5/docs/hb_sdk/src/.vuepress/public/llms/reference/README.md
10
+
11
+ ## Contents
12
+
13
+ - [Host/runtime-only warning](#hostruntime-only-warning)
14
+ - [Public protocol entrypoint](#public-protocol-entrypoint)
15
+ - [Protocol context](#protocol-context)
16
+ - [Generated reference index](#generated-reference-index)
17
+ ## Host/runtime-only warning
18
+
19
+ Use `@heybox/hb-sdk/protocol` only for parent-container runtime, bridge-server, protocol-contract, or `@heybox/hb-sdk-runtime` integration tasks. Iframe mini-program business code must use root SDK APIs and must not construct bridge envelopes, nonce handling, or raw `postMessage` flows.
20
+
21
+ ## Public protocol entrypoint
22
+
23
+ ```ts
24
+ export {
25
+ MINI_PROGRAM_BRIDGE_NONCE_PARAM,
26
+ MINI_PROGRAM_MESSAGE_NAMESPACE,
27
+ MINI_PROGRAM_MESSAGE_VERSION,
28
+ SDK_HANDSHAKE_METHOD,
29
+ } from './protocol/constants';
30
+ export { isMiniProgramBridgeMessage } from './protocol/guards';
31
+ export type {
32
+ MiniProgramBridgeError,
33
+ MiniProgramBridgeMessage,
34
+ MiniProgramBridgeMessageType,
35
+ MiniProgramEventHandler,
36
+ MiniProgramEventName,
37
+ MiniProgramEventPayloadMap,
38
+ } from './protocol/types';
39
+ export {
40
+ AUTH_LOGIN_METHOD,
41
+ MINI_PROGRAM_PROTOCOL_CAPABILITIES,
42
+ NETWORK_REQUEST_METHOD,
43
+ SHARE_SCREENSHOT_METHOD,
44
+ SHARE_SHOW_SHARE_MENU_METHOD,
45
+ STORAGE_GET_STORAGE_METHOD,
46
+ STORAGE_SET_STORAGE_METHOD,
47
+ USER_GET_INFO_METHOD,
48
+ VIEWPORT_GET_WINDOW_INFO_METHOD,
49
+ } from './protocol/capabilities';
50
+ export type {
51
+ MiniProgramAuthMethod,
52
+ MiniProgramBridgeMethod,
53
+ MiniProgramCapabilityDefinition,
54
+ MiniProgramCapabilityModule,
55
+ MiniProgramCapabilityPayload,
56
+ MiniProgramCapabilityPayloadMap,
57
+ MiniProgramCapabilityResult,
58
+ MiniProgramCapabilityResultMap,
59
+ MiniProgramCapabilityRisk,
60
+ MiniProgramNetworkMethod,
61
+ MiniProgramShareMethod,
62
+ MiniProgramStorageMethod,
63
+ MiniProgramUserMethod,
64
+ MiniProgramViewportMethod,
65
+ } from './protocol/capabilities';
66
+ export type { LoginPayload, LoginResult } from './modules/auth';
67
+ export type {
68
+ GetUserInfoPayload,
69
+ GetUserInfoResult,
70
+ MiniProgramUserInfo,
71
+ MiniProgramUserInfoResult,
72
+ } from './modules/user';
73
+ export type { ScreenshotPayload, ScreenshotResult } from './modules/share/screenshot';
74
+ export type { ShowShareMenuPayload, ShowShareMenuResult } from './modules/share/show-share-menu';
75
+ export type {
76
+ MiniProgramScreenshotOptions,
77
+ MiniProgramScreenshotRect,
78
+ MiniProgramShareChannel,
79
+ MiniProgramShowShareMenuOptions,
80
+ } from './modules/share';
81
+ export type {
82
+ GetStoragePayload,
83
+ GetStorageResult,
84
+ SetStoragePayload,
85
+ } from './modules/storage';
86
+ export type {
87
+ GetWindowInfoPayload,
88
+ GetWindowInfoResult,
89
+ MiniProgramSafeArea,
90
+ MiniProgramWindowInfoResult,
91
+ } from './modules/viewport';
92
+ export type {
93
+ MiniProgramNetworkHeaders,
94
+ MiniProgramNetworkParams,
95
+ MiniProgramNetworkRequestConfig,
96
+ MiniProgramNetworkRequestMethod,
97
+ MiniProgramNetworkResponse,
98
+ MiniProgramNetworkValidateStatus,
99
+ NetworkRequestPayload,
100
+ NetworkResponsePayload,
101
+ } from './modules/network';
102
+ ```
103
+
104
+ ## Protocol context
105
+
106
+ ## SDK 与 Runtime
107
+
108
+ `@heybox/hb-sdk` 跑在 iframe 内部,由外部小程序业务页面使用。`@heybox/hb-sdk-runtime` 跑在 iframe 外部,由黑盒宿主壳层使用,负责启动 iframe、注入 nonce、维护 bridge server、注册能力 handler、转发宿主生命周期与登录态变化。
109
+
110
+ 两者共享同一套 bridge 协议。协议字段、事件名或能力 payload 发生变化时,应按同一批次联动升级 SDK 与 runtime;不要只升级其中一侧后假定另一侧自动兼容。
111
+
112
+ ## Generated reference index
113
+
114
+
115
+ # Reference
116
+
117
+ Reference 由 `packages/hb-sdk` 的公开导出与源码注释自动生成,不重复 Guide 的接入流程。
118
+
119
+ | 导出面 | 说明 |
120
+ | --- | --- |
121
+ | [Root API](./root/README.md) | 来自 `src/index.ts` 的默认导出、命名导出与公开能力。 |
122
+ | [Protocol API](./protocol/README.md) | 来自 `src/protocol.ts` 的协议常量、消息类型与 method 契约。 |
123
+
124
+ ## 查询建议
125
+
126
+ - 想查业务接入路径:先看 [Guide](../guide/README.md)。
127
+ - 想查导出符号:从 Root API 或 Protocol API 进入对应分类页。
128
+ - 想看场景化用法:优先看 Guide / Recipes 页面中的“进一步阅读”。
129
+
130
+ ## 统计
131
+
132
+ | 导出面 | Classes | Functions | Interfaces | Types | Constants |
133
+ | --- | ---: | ---: | ---: | ---: | ---: |
134
+ | Root API | 3 | 5 | 28 | 29 | 12 |
135
+ | Protocol API | 0 | 1 | 20 | 29 | 13 |
@@ -0,0 +1,346 @@
1
+ # Root API reference
2
+
3
+ > Generated by `node packages/hb-sdk/skill/scripts/sync-references.mjs` from the public hb-sdk source/docs. Do not edit by hand; update sources or this generator instead.
4
+
5
+ ## Sources
6
+
7
+ - packages/hb-sdk/package.json
8
+ - packages/hb-sdk/src/index.ts
9
+ - packages/hb-sdk/README.md
10
+
11
+ ## Contents
12
+
13
+ - [Package metadata](#package-metadata)
14
+ - [Public root entrypoint](#public-root-entrypoint)
15
+ - [App-facing concepts](#app-facing-concepts)
16
+ - [Public modules](#public-modules)
17
+ ## Package metadata
18
+
19
+ - Package: `@heybox/hb-sdk`
20
+ - Version at generation time: `0.2.0-alpha.1`
21
+ - Public root export: `@heybox/hb-sdk`
22
+ - Protocol export: `@heybox/hb-sdk/protocol`
23
+
24
+ ## Public root entrypoint
25
+
26
+ ```ts
27
+ export { createMiniProgramSDK, MiniProgramSDK } from './core/sdk';
28
+ export { HbMiniProgramSDKError, HbMiniProgramNetworkError } from './core/errors';
29
+ export type { MiniProgramRequester, MiniProgramSDKOptions } from './core/client';
30
+ export { ready, on, off, auth, user, share, viewport, storage, network } from './core/singleton';
31
+ export {
32
+ MINI_PROGRAM_BRIDGE_NONCE_PARAM,
33
+ MINI_PROGRAM_MESSAGE_NAMESPACE,
34
+ MINI_PROGRAM_MESSAGE_VERSION,
35
+ SDK_HANDSHAKE_METHOD,
36
+ } from './protocol/constants';
37
+ export { isMiniProgramBridgeMessage } from './protocol/guards';
38
+ export type {
39
+ MiniProgramBridgeError,
40
+ MiniProgramBridgeMessage,
41
+ MiniProgramBridgeMessageType,
42
+ MiniProgramEventHandler,
43
+ MiniProgramEventName,
44
+ MiniProgramEventPayloadMap,
45
+ } from './protocol/types';
46
+ export {
47
+ AUTH_LOGIN_METHOD,
48
+ NETWORK_REQUEST_METHOD,
49
+ SHARE_SCREENSHOT_METHOD,
50
+ SHARE_SHOW_SHARE_MENU_METHOD,
51
+ STORAGE_GET_STORAGE_METHOD,
52
+ STORAGE_SET_STORAGE_METHOD,
53
+ USER_GET_INFO_METHOD,
54
+ VIEWPORT_GET_WINDOW_INFO_METHOD,
55
+ } from './protocol/capabilities';
56
+ export type {
57
+ MiniProgramAuthMethod,
58
+ MiniProgramBridgeMethod,
59
+ MiniProgramCapabilityDefinition,
60
+ MiniProgramCapabilityModule,
61
+ MiniProgramCapabilityPayload,
62
+ MiniProgramCapabilityPayloadMap,
63
+ MiniProgramCapabilityResult,
64
+ MiniProgramCapabilityResultMap,
65
+ MiniProgramCapabilityRisk,
66
+ MiniProgramNetworkMethod,
67
+ MiniProgramShareMethod,
68
+ MiniProgramStorageMethod,
69
+ MiniProgramUserMethod,
70
+ MiniProgramViewportMethod,
71
+ } from './protocol/capabilities';
72
+ export type { LoginPayload, LoginResult, MiniProgramAuthModule } from './modules/auth';
73
+ export type {
74
+ GetUserInfoPayload,
75
+ GetUserInfoResult,
76
+ MiniProgramUserInfo,
77
+ MiniProgramUserInfoResult,
78
+ MiniProgramUserModule,
79
+ } from './modules/user';
80
+ export type {
81
+ MiniProgramScreenshotOptions,
82
+ MiniProgramScreenshotRect,
83
+ MiniProgramShareChannel,
84
+ MiniProgramShareModule,
85
+ MiniProgramShowShareMenuOptions,
86
+ ScreenshotPayload,
87
+ ScreenshotResult,
88
+ ShowShareMenuPayload,
89
+ ShowShareMenuResult,
90
+ } from './modules/share';
91
+ export type {
92
+ GetWindowInfoPayload,
93
+ GetWindowInfoResult,
94
+ MiniProgramSafeArea,
95
+ MiniProgramViewportModule,
96
+ MiniProgramWindowInfoResult,
97
+ } from './modules/viewport';
98
+ export type {
99
+ GetStoragePayload,
100
+ GetStorageResult,
101
+ MiniProgramStorageModule,
102
+ SetStoragePayload,
103
+ } from './modules/storage';
104
+ export type {
105
+ MiniProgramNetworkHeaders,
106
+ MiniProgramNetworkModule,
107
+ MiniProgramNetworkParams,
108
+ MiniProgramNetworkRequestConfig,
109
+ MiniProgramNetworkRequestMethod,
110
+ MiniProgramNetworkResponse,
111
+ MiniProgramNetworkValidateStatus,
112
+ NetworkRequestPayload,
113
+ NetworkResponsePayload,
114
+ } from './modules/network';
115
+
116
+ import { auth, network, off, on, ready, share, storage, viewport, user } from './core/singleton';
117
+
118
+ const hbSDK = {
119
+ ready,
120
+ on,
121
+ off,
122
+ auth,
123
+ user,
124
+ share,
125
+ viewport,
126
+ storage,
127
+ network,
128
+ };
129
+
130
+ export default hbSDK;
131
+ ```
132
+
133
+ ## App-facing concepts
134
+
135
+ ## 快速开始
136
+
137
+ 创建一个新的外部小程序项目:
138
+
139
+ ```bash
140
+ npx @heybox/hb-sdk create my-miniapp
141
+ cd my-miniapp
142
+ npm install
143
+ npm run dev
144
+ ```
145
+
146
+ 模板默认使用 Vue 3、Vite、TypeScript 和 npm。`npm run dev` 会启动小程序页面服务,并打开 `hb-sdk` 内置的浏览器 mock 宿主环境,适合在普通浏览器里调试 SDK 能力;调试页内可点击按钮在 Mac 版 APP 中启动同一页面。
147
+
148
+ 在已有项目中安装:
149
+
150
+ ```bash
151
+ npm install @heybox/hb-sdk
152
+ ```
153
+
154
+ 然后在页面入口等待父容器 ready:
155
+
156
+ ```ts
157
+ import hbSDK from '@heybox/hb-sdk';
158
+
159
+ await hbSDK.ready();
160
+
161
+ const user = await hbSDK.user.getInfo();
162
+
163
+ if (user.isLogin) {
164
+ console.log(user.userInfo.nickname);
165
+ }
166
+ ```
167
+
168
+ 也可以按需导入:
169
+
170
+ ```ts
171
+ import { auth, ready, user } from '@heybox/hb-sdk';
172
+
173
+ await ready();
174
+
175
+ const currentUser = await user.getInfo();
176
+
177
+ if (!currentUser.isLogin) {
178
+ await auth.login();
179
+ }
180
+ ```
181
+
182
+ ## 运行环境
183
+
184
+ SDK 需要在黑盒小程序 iframe 容器内运行。父容器会为页面注入 bridge nonce,并通过 `postMessage` 与 SDK 通信。普通浏览器直接打开小程序页面时通常无法完成握手;本地开发请优先使用:
185
+
186
+ ```bash
187
+ npm run dev
188
+ ```
189
+
190
+ 调试页会通过 iframe 加载本地页面并补齐小程序 bridge 环境;如果需要真实黑盒小程序容器加载同一页面,点击调试页里的「在 Mac 版 APP 中启动」按钮。
191
+
192
+ 在未使用脚手架的 Vite 项目中,可以把命令加到 `package.json`:
193
+
194
+ ```json
195
+ {
196
+ "scripts": {
197
+ "dev": "hb-sdk dev"
198
+ }
199
+ }
200
+ ```
201
+
202
+ ## 错误处理
203
+
204
+ bridge、父容器运行时、协议校验或能力调用失败时会抛出 `HbMiniProgramSDKError`,其中包含稳定的 `code`、开发者可读的 `message` 和可选 `data`。
205
+
206
+ ```ts
207
+ import { HbMiniProgramSDKError, ready } from '@heybox/hb-sdk';
208
+
209
+ try {
210
+ await ready();
211
+ } catch (error) {
212
+ if (error instanceof HbMiniProgramSDKError) {
213
+ console.log(error.code, error.message, error.data);
214
+ }
215
+ }
216
+ ```
217
+
218
+ 网络请求已完成但 HTTP 状态不满足 `validateStatus` 时会抛出 `HbMiniProgramNetworkError`,其 `response` 字段包含标准化后的 `status`、`headers`、`data` 和原始公共请求配置快照。
219
+
220
+ ## Public modules
221
+
222
+ ## 常用能力
223
+
224
+ ### 用户与登录
225
+
226
+ `user.getInfo()` 只读取当前登录态,不会主动唤起登录。需要用户操作时再调用 `auth.login()`。
227
+
228
+ ```ts
229
+ import { auth, user } from '@heybox/hb-sdk';
230
+
231
+ const result = await user.getInfo();
232
+
233
+ if (!result.isLogin) {
234
+ const loginResult = await auth.login();
235
+ console.log(loginResult.userInfo);
236
+ }
237
+ ```
238
+
239
+ SDK 只返回允许暴露给外部小程序的公开资料,不会返回 token、cookie、手机号或其他私有凭据。
240
+
241
+ ### 分享
242
+
243
+ ```ts
244
+ import { share } from '@heybox/hb-sdk';
245
+
246
+ await share.showShareMenu({
247
+ title: '我的小程序页面',
248
+ desc: '来自黑盒小程序的分享',
249
+ url: window.location.href,
250
+ imageUrl: 'https://imgheybox.max-c.com/demo.png',
251
+ });
252
+ ```
253
+
254
+ 截图分享:
255
+
256
+ ```ts
257
+ await share.screenshot({
258
+ delay: 100,
259
+ saveToAlbum: true,
260
+ });
261
+ ```
262
+
263
+ ### 窗口信息
264
+
265
+ ```ts
266
+ import { viewport } from '@heybox/hb-sdk';
267
+
268
+ const windowInfo = await viewport.getWindowInfo();
269
+
270
+ console.log(windowInfo.windowWidth, windowInfo.windowHeight, windowInfo.safeArea.top);
271
+ ```
272
+
273
+ ### 隔离 Storage
274
+
275
+ ```ts
276
+ import { storage } from '@heybox/hb-sdk';
277
+
278
+ await storage.setStorage({
279
+ key: 'settings',
280
+ data: {
281
+ theme: 'dark',
282
+ },
283
+ });
284
+
285
+ const { data } = await storage.getStorage<{ theme: string }>({
286
+ key: 'settings',
287
+ });
288
+ ```
289
+
290
+ storage key 只允许 1-128 位字母、数字、下划线和连字符。父容器会按小程序维度隔离 key,外部小程序不能读写黑盒客户端全局 storage。
291
+
292
+ ### 网络请求
293
+
294
+ `network.request()` 提供窄化的 axios-like 接口。SDK 只接受公开请求字段,真实请求由父容器运行时映射到宿主网络能力。
295
+
296
+ ```ts
297
+ import { HbMiniProgramNetworkError, network } from '@heybox/hb-sdk';
298
+
299
+ try {
300
+ const response = await network.request<{ ok: boolean }>({
301
+ url: 'https://api.example.com/demo',
302
+ method: 'GET',
303
+ headers: {
304
+ accept: 'application/json',
305
+ },
306
+ });
307
+
308
+ console.log(response.status, response.data.ok);
309
+ } catch (error) {
310
+ if (error instanceof HbMiniProgramNetworkError) {
311
+ console.log(error.response.status, error.response.data);
312
+ }
313
+ }
314
+ ```
315
+
316
+ 默认只有 `2xx` 会 resolve;`4xx/5xx` 这类已完成 HTTP 响应会抛出 `HbMiniProgramNetworkError`。可以用 `validateStatus` 调整 SDK 本地判定逻辑,函数不会跨 bridge 传给父容器。
317
+
318
+ ```ts
319
+ await network.request({
320
+ url: 'https://api.example.com/demo',
321
+ validateStatus: status => status < 500,
322
+ });
323
+ ```
324
+
325
+ 支持的 HTTP method 为 `GET`、`POST`、`PUT`、`PATCH`、`DELETE`、`HEAD`、`OPTIONS`。
326
+
327
+ ## 生命周期事件
328
+
329
+ 使用 `on()` 监听父容器派发的小程序事件。`on()` 会返回取消监听函数,组件卸载或页面销毁时应及时调用。
330
+
331
+ ```ts
332
+ import { on } from '@heybox/hb-sdk';
333
+
334
+ const unsubscribeShow = on('show', payload => {
335
+ console.log('页面展示', payload.timestamp, payload.source);
336
+ });
337
+
338
+ const unsubscribeAuth = on('authChange', payload => {
339
+ console.log('登录态变化', payload.isLogin, payload.userInfo);
340
+ });
341
+
342
+ unsubscribeShow();
343
+ unsubscribeAuth();
344
+ ```
345
+
346
+ 当前可监听事件包括 `launch`、`ready`、`show`、`hide`、`unload`、`error`、`authChange`。