@shiqianjiang/ceru-plugin-cli 0.3.16 → 3.0.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.
Files changed (302) hide show
  1. package/README.md +26 -7
  2. package/assets/compatibility.json +18 -0
  3. package/dist/compatibility.d.ts +24 -0
  4. package/dist/compatibility.js +119 -0
  5. package/dist/component.d.ts +6 -0
  6. package/dist/component.js +60 -0
  7. package/dist/dev-music.d.ts +19 -0
  8. package/dist/dev-music.js +81 -0
  9. package/dist/dev-plugin-services.d.ts +10 -0
  10. package/dist/dev-plugin-services.js +67 -0
  11. package/dist/dev.d.ts +1 -9
  12. package/dist/dev.js +53 -713
  13. package/dist/frameworks.d.ts +5 -2
  14. package/dist/frameworks.js +43 -6
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +54 -23
  17. package/dist/init.js +3 -3
  18. package/dist/migrate.d.ts +3 -0
  19. package/dist/migrate.js +109 -0
  20. package/dist/project.d.ts +5 -2
  21. package/dist/project.js +131 -43
  22. package/dist/test-hooks.d.ts +1 -0
  23. package/dist/test-hooks.js +209 -0
  24. package/dist/test-services.d.ts +4 -0
  25. package/dist/test-services.js +54 -0
  26. package/dist/watch-vue-types.d.ts +17 -0
  27. package/dist/watch-vue-types.js +145 -0
  28. package/package.json +10 -6
  29. package/schemas/config.schema.json +954 -452
  30. package/templates/account-qrcode/js/.vscode/extensions.json +3 -0
  31. package/templates/account-qrcode/js/.vscode/launch.json +19 -0
  32. package/templates/account-qrcode/js/.vscode/settings.json +20 -0
  33. package/templates/account-qrcode/js/.vscode/tasks.json +43 -0
  34. package/templates/account-qrcode/js/README.md +15 -0
  35. package/templates/account-qrcode/js/_gitignore +6 -0
  36. package/templates/account-qrcode/js/ceru-plugin.code-workspace +8 -0
  37. package/templates/account-qrcode/js/ceru.plugin.json +62 -0
  38. package/templates/account-qrcode/js/package.json +24 -0
  39. package/templates/account-qrcode/js/src/Login.vue +25 -0
  40. package/templates/account-qrcode/js/src/index.js +25 -0
  41. package/templates/account-qrcode/js/src/login-html.js +23 -0
  42. package/templates/account-qrcode/js/tsconfig.json +17 -0
  43. package/templates/account-qrcode/ts/.vscode/extensions.json +3 -0
  44. package/templates/account-qrcode/ts/.vscode/launch.json +19 -0
  45. package/templates/account-qrcode/ts/.vscode/settings.json +20 -0
  46. package/templates/account-qrcode/ts/.vscode/tasks.json +43 -0
  47. package/templates/account-qrcode/ts/README.md +15 -0
  48. package/templates/account-qrcode/ts/_gitignore +6 -0
  49. package/templates/account-qrcode/ts/ceru-plugin.code-workspace +8 -0
  50. package/templates/account-qrcode/ts/ceru.plugin.json +62 -0
  51. package/templates/account-qrcode/ts/package.json +24 -0
  52. package/templates/account-qrcode/ts/src/Login.vue +25 -0
  53. package/templates/account-qrcode/ts/src/index.ts +25 -0
  54. package/templates/account-qrcode/ts/src/login-html.ts +23 -0
  55. package/templates/account-qrcode/ts/tsconfig.json +17 -0
  56. package/templates/connected-library/js/.vscode/launch.json +12 -29
  57. package/templates/connected-library/js/.vscode/tasks.json +2 -3
  58. package/templates/connected-library/js/README.md +26 -12
  59. package/templates/connected-library/js/ceru.plugin.json +122 -50
  60. package/templates/connected-library/js/package.json +5 -5
  61. package/templates/connected-library/js/src/index.js +46 -5
  62. package/templates/connected-library/js/src/settings.js +28 -0
  63. package/templates/connected-library/ts/.vscode/launch.json +12 -29
  64. package/templates/connected-library/ts/.vscode/tasks.json +2 -3
  65. package/templates/connected-library/ts/README.md +26 -12
  66. package/templates/connected-library/ts/ceru.plugin.json +122 -50
  67. package/templates/connected-library/ts/package.json +5 -5
  68. package/templates/connected-library/ts/src/index.ts +46 -5
  69. package/templates/connected-library/ts/src/settings.ts +28 -0
  70. package/templates/encrypted-source/README.md +86 -0
  71. package/templates/encrypted-source/js/.prettierrc.json +5 -0
  72. package/templates/encrypted-source/js/.vscode/ceru.code-snippets +55 -0
  73. package/templates/encrypted-source/js/.vscode/extensions.json +3 -0
  74. package/templates/encrypted-source/js/.vscode/launch.json +15 -0
  75. package/templates/encrypted-source/js/.vscode/settings.json +20 -0
  76. package/templates/encrypted-source/js/.vscode/tasks.json +40 -0
  77. package/templates/encrypted-source/js/DEMO.md +77 -0
  78. package/templates/encrypted-source/js/README.md +13 -0
  79. package/templates/encrypted-source/js/_gitignore +6 -0
  80. package/templates/encrypted-source/js/ceru-plugin.code-workspace +8 -0
  81. package/templates/encrypted-source/js/ceru.plugin.json +95 -0
  82. package/templates/encrypted-source/js/package.json +26 -0
  83. package/templates/encrypted-source/js/resources/xor-byte.wasm +0 -0
  84. package/templates/encrypted-source/js/resources/xor-byte.wat +5 -0
  85. package/templates/encrypted-source/js/src/demo.js +200 -0
  86. package/templates/encrypted-source/js/src/fixtures.js +118 -0
  87. package/templates/encrypted-source/js/src/index.js +4 -0
  88. package/templates/encrypted-source/js/tests/demo.test.mjs +357 -0
  89. package/templates/encrypted-source/js/tsconfig.json +16 -0
  90. package/templates/encrypted-source/ts/.prettierrc.json +5 -0
  91. package/templates/encrypted-source/ts/.vscode/ceru.code-snippets +55 -0
  92. package/templates/encrypted-source/ts/.vscode/extensions.json +3 -0
  93. package/templates/encrypted-source/ts/.vscode/launch.json +15 -0
  94. package/templates/encrypted-source/ts/.vscode/settings.json +20 -0
  95. package/templates/encrypted-source/ts/.vscode/tasks.json +40 -0
  96. package/templates/encrypted-source/ts/DEMO.md +77 -0
  97. package/templates/encrypted-source/ts/README.md +13 -0
  98. package/templates/encrypted-source/ts/_gitignore +6 -0
  99. package/templates/encrypted-source/ts/ceru-plugin.code-workspace +8 -0
  100. package/templates/encrypted-source/ts/ceru.plugin.json +95 -0
  101. package/templates/encrypted-source/ts/package.json +26 -0
  102. package/templates/encrypted-source/ts/resources/xor-byte.wasm +0 -0
  103. package/templates/encrypted-source/ts/resources/xor-byte.wat +5 -0
  104. package/templates/encrypted-source/ts/src/demo.ts +212 -0
  105. package/templates/encrypted-source/ts/src/fixtures.ts +125 -0
  106. package/templates/encrypted-source/ts/src/index.ts +4 -0
  107. package/templates/encrypted-source/ts/tests/demo.test.mjs +357 -0
  108. package/templates/encrypted-source/ts/tsconfig.json +17 -0
  109. package/templates/guest-adapter/js/.vscode/launch.json +12 -29
  110. package/templates/guest-adapter/js/.vscode/tasks.json +2 -3
  111. package/templates/guest-adapter/js/README.md +10 -10
  112. package/templates/guest-adapter/js/ceru.plugin.json +67 -62
  113. package/templates/guest-adapter/js/package.json +5 -5
  114. package/templates/guest-adapter/js/src/index.js +1 -1
  115. package/templates/guest-adapter/js/src/settings.js +8 -0
  116. package/templates/guest-adapter/ts/.vscode/launch.json +12 -29
  117. package/templates/guest-adapter/ts/.vscode/tasks.json +2 -3
  118. package/templates/guest-adapter/ts/README.md +10 -10
  119. package/templates/guest-adapter/ts/ceru.plugin.json +67 -62
  120. package/templates/guest-adapter/ts/package.json +5 -5
  121. package/templates/guest-adapter/ts/src/index.ts +1 -1
  122. package/templates/guest-adapter/ts/src/settings.ts +8 -0
  123. package/templates/importer/js/.vscode/launch.json +12 -29
  124. package/templates/importer/js/.vscode/tasks.json +2 -3
  125. package/templates/importer/js/README.md +10 -10
  126. package/templates/importer/js/ceru.plugin.json +23 -21
  127. package/templates/importer/js/package.json +5 -5
  128. package/templates/importer/ts/.vscode/launch.json +12 -29
  129. package/templates/importer/ts/.vscode/tasks.json +2 -3
  130. package/templates/importer/ts/README.md +10 -10
  131. package/templates/importer/ts/ceru.plugin.json +23 -21
  132. package/templates/importer/ts/package.json +5 -5
  133. package/templates/page-extension/js/.vscode/extensions.json +3 -0
  134. package/templates/page-extension/js/.vscode/launch.json +19 -0
  135. package/templates/page-extension/js/.vscode/settings.json +20 -0
  136. package/templates/page-extension/js/.vscode/tasks.json +43 -0
  137. package/templates/page-extension/js/README.md +9 -0
  138. package/templates/page-extension/js/_gitignore +6 -0
  139. package/templates/page-extension/js/ceru-plugin.code-workspace +8 -0
  140. package/templates/page-extension/js/ceru.plugin.json +94 -0
  141. package/templates/page-extension/js/package.json +24 -0
  142. package/templates/page-extension/js/src/Open.vue +6 -0
  143. package/templates/page-extension/js/src/Search.vue +62 -0
  144. package/templates/page-extension/js/src/index.js +54 -0
  145. package/templates/page-extension/js/tsconfig.json +17 -0
  146. package/templates/page-extension/ts/.vscode/extensions.json +3 -0
  147. package/templates/page-extension/ts/.vscode/launch.json +19 -0
  148. package/templates/page-extension/ts/.vscode/settings.json +20 -0
  149. package/templates/page-extension/ts/.vscode/tasks.json +43 -0
  150. package/templates/page-extension/ts/README.md +9 -0
  151. package/templates/page-extension/ts/_gitignore +6 -0
  152. package/templates/page-extension/ts/ceru-plugin.code-workspace +8 -0
  153. package/templates/page-extension/ts/ceru.plugin.json +94 -0
  154. package/templates/page-extension/ts/package.json +24 -0
  155. package/templates/page-extension/ts/src/Open.vue +6 -0
  156. package/templates/page-extension/ts/src/Search.vue +62 -0
  157. package/templates/page-extension/ts/src/index.ts +54 -0
  158. package/templates/page-extension/ts/tsconfig.json +17 -0
  159. package/templates/playback-hook/js/.prettierrc.json +5 -0
  160. package/templates/playback-hook/js/.vscode/extensions.json +3 -0
  161. package/templates/playback-hook/js/.vscode/launch.json +19 -0
  162. package/templates/playback-hook/js/.vscode/settings.json +20 -0
  163. package/templates/playback-hook/js/.vscode/tasks.json +50 -0
  164. package/templates/playback-hook/js/README.md +24 -0
  165. package/templates/playback-hook/js/_gitignore +6 -0
  166. package/templates/playback-hook/js/ceru-plugin.code-workspace +8 -0
  167. package/templates/playback-hook/js/ceru.plugin.json +36 -0
  168. package/templates/playback-hook/js/package.json +23 -0
  169. package/templates/playback-hook/js/src/index.js +25 -0
  170. package/templates/playback-hook/js/tests/hooks.json +316 -0
  171. package/templates/playback-hook/js/tsconfig.json +16 -0
  172. package/templates/playback-hook/ts/.prettierrc.json +5 -0
  173. package/templates/playback-hook/ts/.vscode/extensions.json +3 -0
  174. package/templates/playback-hook/ts/.vscode/launch.json +19 -0
  175. package/templates/playback-hook/ts/.vscode/settings.json +20 -0
  176. package/templates/playback-hook/ts/.vscode/tasks.json +50 -0
  177. package/templates/playback-hook/ts/README.md +24 -0
  178. package/templates/playback-hook/ts/_gitignore +6 -0
  179. package/templates/playback-hook/ts/ceru-plugin.code-workspace +8 -0
  180. package/templates/playback-hook/ts/ceru.plugin.json +36 -0
  181. package/templates/playback-hook/ts/package.json +23 -0
  182. package/templates/playback-hook/ts/src/index.ts +25 -0
  183. package/templates/playback-hook/ts/tests/hooks.json +316 -0
  184. package/templates/playback-hook/ts/tsconfig.json +16 -0
  185. package/templates/player-skin/js/.vscode/extensions.json +3 -0
  186. package/templates/player-skin/js/.vscode/launch.json +19 -0
  187. package/templates/player-skin/js/.vscode/settings.json +20 -0
  188. package/templates/player-skin/js/.vscode/tasks.json +43 -0
  189. package/templates/player-skin/js/README.md +11 -0
  190. package/templates/player-skin/js/_gitignore +6 -0
  191. package/templates/player-skin/js/assets/studio-preview.svg +15 -0
  192. package/templates/player-skin/js/ceru-plugin.code-workspace +8 -0
  193. package/templates/player-skin/js/ceru.plugin.json +77 -0
  194. package/templates/player-skin/js/package.json +24 -0
  195. package/templates/player-skin/js/src/Artwork.vue +9 -0
  196. package/templates/player-skin/js/src/Background.vue +15 -0
  197. package/templates/player-skin/js/src/BuiltinLyrics.vue +15 -0
  198. package/templates/player-skin/js/src/Lyrics.vue +28 -0
  199. package/templates/player-skin/js/tsconfig.json +17 -0
  200. package/templates/player-skin/ts/.vscode/extensions.json +3 -0
  201. package/templates/player-skin/ts/.vscode/launch.json +19 -0
  202. package/templates/player-skin/ts/.vscode/settings.json +20 -0
  203. package/templates/player-skin/ts/.vscode/tasks.json +43 -0
  204. package/templates/player-skin/ts/README.md +11 -0
  205. package/templates/player-skin/ts/_gitignore +6 -0
  206. package/templates/player-skin/ts/assets/studio-preview.svg +15 -0
  207. package/templates/player-skin/ts/ceru-plugin.code-workspace +8 -0
  208. package/templates/player-skin/ts/ceru.plugin.json +77 -0
  209. package/templates/player-skin/ts/package.json +24 -0
  210. package/templates/player-skin/ts/src/Artwork.vue +9 -0
  211. package/templates/player-skin/ts/src/Background.vue +15 -0
  212. package/templates/player-skin/ts/src/BuiltinLyrics.vue +15 -0
  213. package/templates/player-skin/ts/src/Lyrics.vue +28 -0
  214. package/templates/player-skin/ts/tsconfig.json +17 -0
  215. package/templates/react/js/.vscode/launch.json +12 -29
  216. package/templates/react/js/.vscode/tasks.json +2 -3
  217. package/templates/react/js/README.md +10 -10
  218. package/templates/react/js/ceru.plugin.json +27 -22
  219. package/templates/react/js/package.json +5 -5
  220. package/templates/react/js/src/index.js +1 -1
  221. package/templates/react/ts/.vscode/launch.json +12 -29
  222. package/templates/react/ts/.vscode/tasks.json +2 -3
  223. package/templates/react/ts/README.md +10 -10
  224. package/templates/react/ts/ceru.plugin.json +27 -22
  225. package/templates/react/ts/package.json +5 -5
  226. package/templates/react/ts/src/index.ts +1 -1
  227. package/templates/snapshot.json +152 -6
  228. package/templates/source/js/.vscode/launch.json +12 -29
  229. package/templates/source/js/.vscode/tasks.json +2 -3
  230. package/templates/source/js/README.md +12 -10
  231. package/templates/source/js/ceru.plugin.json +44 -26
  232. package/templates/source/js/package.json +5 -5
  233. package/templates/source/js/src/index.js +10 -8
  234. package/templates/source/ts/.vscode/launch.json +12 -29
  235. package/templates/source/ts/.vscode/tasks.json +2 -3
  236. package/templates/source/ts/README.md +12 -10
  237. package/templates/source/ts/ceru.plugin.json +44 -26
  238. package/templates/source/ts/package.json +5 -5
  239. package/templates/source/ts/src/index.ts +10 -8
  240. package/templates/vue/js/.vscode/launch.json +12 -29
  241. package/templates/vue/js/.vscode/tasks.json +2 -3
  242. package/templates/vue/js/README.md +10 -10
  243. package/templates/vue/js/ceru.plugin.json +27 -22
  244. package/templates/vue/js/package.json +5 -5
  245. package/templates/vue/js/src/index.js +1 -1
  246. package/templates/vue/ts/.vscode/launch.json +12 -29
  247. package/templates/vue/ts/.vscode/tasks.json +2 -3
  248. package/templates/vue/ts/README.md +10 -10
  249. package/templates/vue/ts/ceru.plugin.json +27 -22
  250. package/templates/vue/ts/package.json +5 -5
  251. package/templates/vue/ts/src/index.ts +1 -1
  252. package/templates/vue-tsx/js/.vscode/launch.json +12 -29
  253. package/templates/vue-tsx/js/.vscode/tasks.json +2 -3
  254. package/templates/vue-tsx/js/README.md +10 -10
  255. package/templates/vue-tsx/js/ceru.plugin.json +27 -22
  256. package/templates/vue-tsx/js/package.json +5 -5
  257. package/templates/vue-tsx/js/src/index.js +1 -1
  258. package/templates/vue-tsx/ts/.vscode/launch.json +12 -29
  259. package/templates/vue-tsx/ts/.vscode/tasks.json +2 -3
  260. package/templates/vue-tsx/ts/README.md +10 -10
  261. package/templates/vue-tsx/ts/ceru.plugin.json +27 -22
  262. package/templates/vue-tsx/ts/package.json +5 -5
  263. package/templates/vue-tsx/ts/src/index.ts +1 -1
  264. package/templates/web-dist/js/.vscode/launch.json +12 -29
  265. package/templates/web-dist/js/.vscode/tasks.json +2 -3
  266. package/templates/web-dist/js/README.md +10 -10
  267. package/templates/web-dist/js/ceru.plugin.json +27 -22
  268. package/templates/web-dist/js/package.json +5 -5
  269. package/templates/web-dist/js/src/index.js +1 -1
  270. package/templates/web-dist/ts/.vscode/launch.json +12 -29
  271. package/templates/web-dist/ts/.vscode/tasks.json +2 -3
  272. package/templates/web-dist/ts/README.md +10 -10
  273. package/templates/web-dist/ts/ceru.plugin.json +27 -22
  274. package/templates/web-dist/ts/package.json +5 -5
  275. package/templates/web-dist/ts/src/index.ts +1 -1
  276. package/templates/web-surface/js/.vscode/launch.json +12 -29
  277. package/templates/web-surface/js/.vscode/tasks.json +2 -3
  278. package/templates/web-surface/js/README.md +10 -10
  279. package/templates/web-surface/js/ceru.plugin.json +35 -35
  280. package/templates/web-surface/js/package.json +5 -5
  281. package/templates/web-surface/js/src/index.js +1 -1
  282. package/templates/web-surface/ts/.vscode/launch.json +12 -29
  283. package/templates/web-surface/ts/.vscode/tasks.json +2 -3
  284. package/templates/web-surface/ts/README.md +10 -10
  285. package/templates/web-surface/ts/ceru.plugin.json +35 -35
  286. package/templates/web-surface/ts/package.json +5 -5
  287. package/templates/web-surface/ts/src/index.ts +1 -1
  288. package/assets/core-contracts.js +0 -1
  289. package/assets/electron-app/main.cjs +0 -1
  290. package/assets/electron-app/package.json +0 -8
  291. package/assets/electron.cjs +0 -42
  292. package/assets/index.html +0 -94
  293. package/assets/native-view.js +0 -197
  294. package/assets/playground.js +0 -883
  295. package/assets/sandbox.js +0 -67
  296. package/assets/style.css +0 -337
  297. package/dist/socket-broker.d.ts +0 -23
  298. package/dist/socket-broker.js +0 -229
  299. package/templates/connected-library/js/ui/settings.json +0 -24
  300. package/templates/connected-library/ts/ui/settings.json +0 -24
  301. package/templates/guest-adapter/js/ui/settings.json +0 -14
  302. package/templates/guest-adapter/ts/ui/settings.json +0 -14
package/dist/project.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { readFile, realpath, mkdir, writeFile, rename, readdir, stat, unlink, } from 'node:fs/promises';
2
2
  import { dirname, resolve, relative, isAbsolute, sep, extname, basename } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { randomUUID } from 'node:crypto';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
5
  import { build } from 'esbuild';
6
6
  import ts from 'typescript';
7
7
  import { spawnSync } from 'node:child_process';
8
8
  import { createRequire } from 'node:module';
9
+ import { isBuiltin } from 'node:module';
9
10
  import { stylesheetPlugin, vuePlugin, webDistEntry } from './frameworks.js';
11
+ import { buildComponent } from './component.js';
10
12
  import { hostModulesPlugin, assertBundledDependencies } from './dependencies.js';
11
13
  import { canonical, encodeArtifact, parseJsonStrict, readArtifact, validateManifest, LIMITS, } from '@shiqianjiang/ceru-plugin-issuer';
12
14
  async function resolveConfigValue(root, value, stack = new Set(), depth = 0) {
@@ -114,9 +116,7 @@ async function writeConfigTypes(root, config) {
114
116
  }
115
117
  function entryFunctionName(id, suffix) {
116
118
  const words = id.split(/[^a-zA-Z0-9]+/).filter(Boolean);
117
- const name = words
118
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
119
- .join('');
119
+ const name = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('');
120
120
  const base = name || 'Plugin';
121
121
  const safe = /^[A-Za-z_$]/.test(base) ? base : 'Plugin' + base;
122
122
  return safe.startsWith(suffix) || safe.endsWith(suffix) ? safe : safe + suffix;
@@ -150,6 +150,39 @@ async function inside(root, path) {
150
150
  throw new Error('Input escapes project root: ' + path);
151
151
  return target;
152
152
  }
153
+ function resolveAuthorEntries(raw) {
154
+ if (!raw.manifest?.entry || raw.manifest.manifestVersion !== 3)
155
+ return;
156
+ raw.entries ??= {};
157
+ if (!raw.entries || typeof raw.entries !== 'object' || Array.isArray(raw.entries))
158
+ throw new Error('entries must be an object');
159
+ const mapModule = (declaration, fallback) => {
160
+ const file = declaration?.module;
161
+ if (typeof file !== 'string' ||
162
+ Object.hasOwn(raw.entries, file) ||
163
+ Object.hasOwn(raw.webDist ?? {}, file))
164
+ return;
165
+ if (!/\.(?:[cm]?[jt]sx?|vue)$/.test(file))
166
+ return;
167
+ const existing = Object.keys(raw.entries).find((key) => raw.entries[key] === file);
168
+ if (existing) {
169
+ declaration.module = existing;
170
+ return;
171
+ }
172
+ if (Object.hasOwn(raw.entries, fallback) || Object.hasOwn(raw.webDist ?? {}, fallback))
173
+ throw new Error('Conflicting module id: ' + fallback);
174
+ raw.entries[fallback] = file;
175
+ declaration.module = fallback;
176
+ };
177
+ const entry = raw.manifest.entry;
178
+ mapModule(entry.logic, 'logic.main');
179
+ mapModule(entry.share, 'share.main');
180
+ mapModule(entry.server, 'server.main');
181
+ if (Array.isArray(entry.views))
182
+ for (const view of entry.views)
183
+ if (view?.kind === 'web' || view?.kind === 'component')
184
+ mapModule(view, 'view.' + view.id);
185
+ }
153
186
  export async function loadProject(project) {
154
187
  const root = await realpath(resolve(project));
155
188
  const source = parseJsonStrict(await readFile(resolve(root, 'ceru.plugin.json'), 'utf8'));
@@ -181,6 +214,7 @@ export async function loadProject(project) {
181
214
  raw.manifest.config = raw.config;
182
215
  if (raw.framework && !['vanilla', 'vue', 'react'].includes(raw.framework))
183
216
  throw new Error('Unsupported framework');
217
+ resolveAuthorEntries(raw);
184
218
  validateManifest(raw.manifest);
185
219
  if (!raw.entries || typeof raw.entries !== 'object' || Array.isArray(raw.entries))
186
220
  throw new Error('entries must map module IDs to source paths');
@@ -212,16 +246,23 @@ function checkTypes(root, extraFiles = []) {
212
246
  }
213
247
  return program;
214
248
  }
215
- export async function buildProject(project = '.', options = {}) {
216
- const { root, config } = await loadProject(project);
217
- if (config.framework === 'vue') {
249
+ async function projectProgram(root, config, watchVueTypes) {
250
+ const configTypes = await writeConfigTypes(root, config.config ?? {});
251
+ if (config.framework === 'vue' && !watchVueTypes) {
218
252
  const executable = createRequire(import.meta.url).resolve('vue-tsc/bin/vue-tsc.js');
219
253
  const result = spawnSync(process.execPath, [executable, '--noEmit', '--pretty', 'false', '-p', resolve(root, 'tsconfig.json')], { cwd: root, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 });
220
254
  if (result.status !== 0)
221
255
  throw new Error(result.stdout + result.stderr);
222
256
  }
223
- const configTypes = await writeConfigTypes(root, config.config ?? {});
224
- const program = checkTypes(root, [configTypes]);
257
+ return config.framework === 'vue' && watchVueTypes ? watchVueTypes(root, configTypes) : checkTypes(root, [configTypes]);
258
+ }
259
+ export async function typecheckProject(project = '.') {
260
+ const { root, config } = await loadProject(project);
261
+ await projectProgram(root, config);
262
+ }
263
+ export async function buildProject(project = '.', options = {}, watchVueTypes, isCurrent = () => true, componentCache) {
264
+ const { root, config } = await loadProject(project);
265
+ const program = await projectProgram(root, config, watchVueTypes);
225
266
  const checker = program.getTypeChecker();
226
267
  const chunks = new Map();
227
268
  const chunkNames = new Map();
@@ -237,9 +278,9 @@ export async function buildProject(project = '.', options = {}) {
237
278
  return name;
238
279
  };
239
280
  const devModules = {};
240
- const surfaceEntries = new Set((config.manifest.modules.surfaces ?? [])
281
+ const surfaceEntries = new Set((config.manifest.entry.views ?? [])
241
282
  .filter((surface) => surface.kind === 'web')
242
- .map((surface) => surface.entry));
283
+ .map((surface) => surface.module));
243
284
  const plugins = [hostModulesPlugin(), vuePlugin(root, config.framework), stylesheetPlugin()];
244
285
  const defines = {
245
286
  'process.env.NODE_ENV': '"production"',
@@ -249,6 +290,14 @@ export async function buildProject(project = '.', options = {}) {
249
290
  };
250
291
  for (const [id, file] of Object.entries(config.entries)) {
251
292
  const entry = await inside(root, file);
293
+ const nodeServer = config.manifest.entry.server?.runtime === 'node' && config.manifest.entry.server.module === id;
294
+ if (config.manifest.entry.views?.some(view => view.kind === 'component' && view.module === id)) {
295
+ const factory = await buildComponent(root, entry, uniqueEntryName(id, 'Surface'), defines, componentCache);
296
+ chunks.set(id, factory);
297
+ if (options.development)
298
+ devModules[id] = 'export default ' + factory;
299
+ continue;
300
+ }
252
301
  const sourceFile = program.getSourceFile(entry);
253
302
  const moduleSymbol = sourceFile && checker.getSymbolAtLocation(sourceFile);
254
303
  const defaultExport = moduleSymbol &&
@@ -258,14 +307,14 @@ export async function buildProject(project = '.', options = {}) {
258
307
  !checker.getSignaturesOfType(checker.getTypeOfSymbolAtLocation(defaultExport, sourceFile), ts.SignatureKind.Call).length) {
259
308
  throw new Error('Entry must be included in tsconfig and default-export a function: ' + file);
260
309
  }
261
- const result = await build({
310
+ const buildEntry = (optional = new Set()) => build({
262
311
  absWorkingDir: root,
263
312
  entryPoints: [entry],
264
313
  bundle: true,
265
314
  write: false,
266
315
  format: 'iife',
267
316
  globalName: '__ceru_entry',
268
- platform: 'browser',
317
+ platform: config.manifest.entry.server?.runtime === 'node' && config.manifest.entry.server.module === id ? 'node' : 'browser',
269
318
  target: 'es2022',
270
319
  charset: 'utf8',
271
320
  minify: false,
@@ -276,7 +325,17 @@ export async function buildProject(project = '.', options = {}) {
276
325
  tsconfig: resolve(root, 'tsconfig.json'),
277
326
  outfile: 'entry.js',
278
327
  legalComments: 'inline',
279
- plugins,
328
+ plugins: [...plugins, {
329
+ name: 'ceru-optional-node-dependencies',
330
+ setup(builder) {
331
+ builder.onResolve({ filter: /.*/ }, args => optional.has(args.path)
332
+ ? { path: args.path, namespace: 'ceru-missing-optional' } : undefined);
333
+ builder.onLoad({ filter: /.*/, namespace: 'ceru-missing-optional' }, args => ({
334
+ contents: 'const error = new Error(' + JSON.stringify('Cannot find module ' + args.path) + '); error.code = "MODULE_NOT_FOUND"; throw error;',
335
+ loader: 'js',
336
+ }));
337
+ },
338
+ }],
280
339
  define: defines,
281
340
  loader: {
282
341
  '.svg': 'dataurl',
@@ -288,19 +347,32 @@ export async function buildProject(project = '.', options = {}) {
288
347
  '.woff2': 'dataurl',
289
348
  },
290
349
  });
350
+ let result = await buildEntry();
351
+ // esbuild only tolerates unresolved require() inside try/catch. Bundle a
352
+ // throwing module for those absent optional dependencies (e.g. Express's
353
+ // debug -> supports-color), preserving the catch without external files.
354
+ // Missing required dependencies already failed the first build.
355
+ if (nodeServer) {
356
+ const optional = new Set(Object.values(result.metafile.outputs).flatMap(info => info.imports.filter(item => item.external && item.kind === 'require-call' && !isBuiltin(item.path)).map(item => item.path)));
357
+ if (optional.size)
358
+ result = await buildEntry(optional);
359
+ }
291
360
  if (result.outputFiles.length !== 1)
292
361
  throw new Error('Entry emitted sidecar files: ' + id);
293
362
  for (const info of Object.values(result.metafile.outputs))
294
- if (info.imports.length)
363
+ if (info.imports.some(item => !(config.manifest.entry.server?.runtime === 'node' && config.manifest.entry.server.module === id && item.external && isBuiltin(item.path))))
295
364
  throw new Error('Unbundled import in ' + id);
296
365
  const source = result.outputFiles[0].text.replace(/(^|\n)var __ceru_entry =/, '$1const __ceru_entry =');
297
- assertBundledDependencies(source);
298
- const entryName = uniqueEntryName(id, id === config.manifest.modules.logic?.entry
366
+ if (!(config.manifest.entry.server?.runtime === 'node' && config.manifest.entry.server.module === id))
367
+ assertBundledDependencies(source);
368
+ const entryName = uniqueEntryName(id, id === config.manifest.entry.logic?.module
299
369
  ? 'Logic'
300
370
  : surfaceEntries.has(id)
301
371
  ? 'Surface'
302
372
  : 'Module');
303
- chunks.set(id, 'async function ' + entryName + '(ctx) {\n' +
373
+ chunks.set(id, 'async function ' +
374
+ entryName +
375
+ '(ctx) {\n' +
304
376
  source +
305
377
  '\nif (typeof __ceru_entry.default !== "function") throw new Error("Entry must default-export a function");\nreturn __ceru_entry.default(ctx);\n}');
306
378
  if (options.development) {
@@ -311,7 +383,7 @@ export async function buildProject(project = '.', options = {}) {
311
383
  write: false,
312
384
  format: 'iife',
313
385
  globalName: '__ceru_entry',
314
- platform: 'browser',
386
+ platform: config.manifest.entry.server?.runtime === 'node' && config.manifest.entry.server.module === id ? 'node' : 'browser',
315
387
  target: 'es2022',
316
388
  charset: 'utf8',
317
389
  sourcemap: 'inline',
@@ -362,7 +434,9 @@ export async function buildProject(project = '.', options = {}) {
362
434
  const source = result.outputFiles[0].text.replace(/(^|\n)var __ceru_entry =/, '$1const __ceru_entry =');
363
435
  assertBundledDependencies(source);
364
436
  const entryName = uniqueEntryName(id, 'Surface');
365
- chunks.set(id, 'async function ' + entryName + '(ctx) {\n' +
437
+ chunks.set(id, 'async function ' +
438
+ entryName +
439
+ '(ctx) {\n' +
366
440
  source +
367
441
  '\nreturn __ceru_entry.default(ctx);\n}');
368
442
  if (options.development) {
@@ -377,6 +451,7 @@ export async function buildProject(project = '.', options = {}) {
377
451
  }
378
452
  }
379
453
  const resources = Object.create(null);
454
+ const nativeResources = new Set((config.manifest.entry.native ?? []).flatMap(item => Object.values(item.platforms)));
380
455
  for (const [id, input] of Object.entries(config.resources ?? {})) {
381
456
  if (!input ||
382
457
  !['json', 'text', 'base64'].includes(input.type) ||
@@ -402,12 +477,13 @@ export async function buildProject(project = '.', options = {}) {
402
477
  type: 'base64',
403
478
  value: bytes.toString('base64'),
404
479
  mime: input.mime ?? 'application/octet-stream',
480
+ ...(nativeResources.has(id) ? { sha256: 'sha256:' + createHash('sha256').update(bytes).digest('hex') } : {}),
405
481
  };
406
482
  }
407
483
  const emitted = new Set();
408
484
  const definitions = [];
409
485
  const exports = [];
410
- const logicEntry = config.manifest.modules.logic?.entry;
486
+ const logicEntry = config.manifest.entry.logic?.module;
411
487
  if (logicEntry) {
412
488
  const logic = chunks.get(logicEntry);
413
489
  const name = chunkNames.get(logicEntry);
@@ -415,24 +491,20 @@ export async function buildProject(project = '.', options = {}) {
415
491
  throw new Error('Missing compiled logic entry: ' + logicEntry);
416
492
  if (!name)
417
493
  throw new Error('Missing compiled logic name: ' + logicEntry);
418
- definitions.push('// Invisible plugin logic\nconst ' +
419
- name +
420
- ' = /* @ceru-self-contained */ ' +
421
- logic +
422
- ';');
494
+ definitions.push('// Invisible plugin logic\nconst ' + name + ' = /* @ceru-self-contained */ ' + logic + ';');
423
495
  exports.push('exports.activate = ' + name + ';');
424
496
  emitted.add(logicEntry);
425
497
  }
426
- const visibleSurfaces = (config.manifest.modules.surfaces ?? []).filter((surface) => surface.kind === 'web');
498
+ const visibleSurfaces = (config.manifest.entry.views ?? []).filter((surface) => surface.kind === 'web' || surface.kind === 'component');
427
499
  if (visibleSurfaces.length) {
428
500
  const entries = visibleSurfaces.map((surface) => {
429
- const entry = chunks.get(surface.entry);
430
- const name = chunkNames.get(surface.entry);
501
+ const entry = chunks.get(surface.module);
502
+ const name = chunkNames.get(surface.module);
431
503
  if (!entry)
432
- throw new Error('Missing compiled Surface entry: ' + surface.entry);
504
+ throw new Error('Missing compiled Surface entry: ' + surface.module);
433
505
  if (!name)
434
- throw new Error('Missing compiled Surface name: ' + surface.entry);
435
- emitted.add(surface.entry);
506
+ throw new Error('Missing compiled Surface name: ' + surface.module);
507
+ emitted.add(surface.module);
436
508
  definitions.push('// Visible plugin surface: ' +
437
509
  surface.id +
438
510
  '\nconst ' +
@@ -480,12 +552,14 @@ export async function buildProject(project = '.', options = {}) {
480
552
  const rel = relative(root, output);
481
553
  if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel))
482
554
  throw new Error('Build output must stay inside project');
483
- await writeAtomic(output, artifact, options.overwrite ?? true);
555
+ if (isCurrent())
556
+ await writeAtomic(output, artifact, options.overwrite ?? true);
484
557
  return { path: output, bytes: artifact.length, devModules };
485
558
  }
486
559
  export const TEMPLATES = [
487
560
  'source',
488
561
  'connected-library',
562
+ 'account-qrcode',
489
563
  'importer',
490
564
  'guest-adapter',
491
565
  'web-surface',
@@ -493,11 +567,20 @@ export const TEMPLATES = [
493
567
  'vue-tsx',
494
568
  'react',
495
569
  'web-dist',
570
+ 'page-extension',
571
+ 'playback-hook',
572
+ 'player-skin',
573
+ 'encrypted-source',
496
574
  ];
497
575
  // 与根 README 的模板表保持一致;Record 保证新增模板必须补说明。
498
576
  export const TEMPLATE_INFO = {
577
+ 'player-skin': 'Vue 歌词、封面与背景区域',
499
578
  source: '本地搜索 demo、标准 Provider、结构化解析结果',
579
+ 'encrypted-source': '内置解密、WASM 变换和本机服务三个音源',
580
+ 'playback-hook': '拦截点播和队列,内置无桌面测试',
581
+ 'page-extension': 'Vue 侧边栏、设置页及歌单按钮',
500
582
  'connected-library': '连接表单与状态更新 demo',
583
+ 'account-qrcode': '扫码登录:宿主模板或插件自定义内部 UI',
501
584
  importer: '曲目去重与导入计划预览',
502
585
  'guest-adapter': '父插件与 Guest bootstrap 的边界',
503
586
  'web-surface': '普通 DOM 页面',
@@ -522,10 +605,14 @@ export async function scaffoldProject(destination, options = {}) {
522
605
  if (error.code !== 'ENOENT')
523
606
  throw error;
524
607
  }
525
- const slug = basename(root)
526
- .toLowerCase()
527
- .replace(/[^a-z0-9-]/g, '-')
528
- .replace(/^-+|-+$/g, '') || 'my-plugin';
608
+ const directoryName = basename(root).normalize('NFC');
609
+ const lowerName = directoryName.toLowerCase();
610
+ const stem = lowerName.replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || 'my-plugin';
611
+ const maxSlugLength = 128 - 'local.'.length;
612
+ const suffix = createHash('sha256').update(directoryName).digest('hex').slice(0, 12);
613
+ const slug = stem === lowerName && stem.length <= maxSlugLength ? stem :
614
+ stem.slice(0, maxSlugLength - suffix.length - 1).replace(/-+$/, '') + '-' + suffix;
615
+ const displayName = Array.from(directoryName.replace(/[\u0000-\u001f\u007f]/g, ' ').trim()).slice(0, 120).join('') || slug;
529
616
  const base = fileURLToPath(new URL('../templates/', import.meta.url));
530
617
  const snapshot = JSON.parse(await readFile(resolve(base, 'snapshot.json'), 'utf8'));
531
618
  const prefix = template + '/' + language + '/';
@@ -542,23 +629,24 @@ export async function scaffoldProject(destination, options = {}) {
542
629
  if (name === 'package.json') {
543
630
  const pkg = JSON.parse(bytes.toString('utf8'));
544
631
  pkg.name = slug;
632
+ pkg.scripts = { ...pkg.scripts, 'check:compat': 'ceru-plugin check-compat' };
545
633
  contents = JSON.stringify(pkg, null, 2) + '\n';
546
634
  }
547
635
  if (name === 'ceru.plugin.json') {
548
636
  const cfg = JSON.parse(bytes.toString('utf8'));
549
637
  const old = cfg.manifest.name;
550
638
  cfg.manifest.id = 'local.' + slug;
551
- cfg.manifest.name = slug;
552
- for (const provider of cfg.manifest.contributes?.providers ?? [])
639
+ cfg.manifest.name = displayName;
640
+ for (const provider of cfg.manifest.provides?.providers ?? [])
553
641
  if (provider.name === old)
554
- provider.name = slug;
555
- for (const item of cfg.manifest.contributes?.sidebarItems ?? [])
642
+ provider.name = displayName;
643
+ for (const item of cfg.manifest.ui?.pages ?? [])
556
644
  if (item.title === old)
557
- item.title = slug;
645
+ item.title = displayName;
558
646
  contents = JSON.stringify(cfg, null, 2) + '\n';
559
647
  }
560
648
  if (name === 'README.md')
561
- contents = bytes.toString('utf8').replace(/^# .*/, '# ' + slug);
649
+ contents = bytes.toString('utf8').replace(/^# .*/, () => '# ' + displayName);
562
650
  await writeAtomic(resolve(root, name), contents);
563
651
  }
564
652
  return realpath(root);
@@ -0,0 +1 @@
1
+ export declare function testHooks(project: string, fixture?: string, report?: (text: string) => void): Promise<void>;
@@ -0,0 +1,209 @@
1
+ import assert from 'node:assert/strict';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { resolve } from 'node:path';
4
+ import { readPluginArtifact } from '@shiqianjiang/ceru-plugin-core';
5
+ import { NodePluginSandbox } from '@shiqianjiang/ceru-plugin-core/node';
6
+ import { OperationBus, OperationEngine, ACCOUNT_OPERATIONS, WINDOW_OPERATIONS, windowCloseInput, LYRIC_OPERATIONS, lyricInput, lyricResult, isLyricOperation, DOWNLOAD_OPERATIONS, downloadInput, isDownloadOperation, SHARING_OPERATIONS, shareInput, shareResult, SYSTEM_OPERATIONS, systemInput, isSystemOperation, RESOLVE_OPERATIONS, resolveInput, LIBRARY_OPERATIONS, libraryInput, isLibraryOperation, accountSwitchInput, SEARCH_OPERATIONS, searchInput, isSearchOperation, isPlaybackOperation, playbackInput, } from '@shiqianjiang/ceru-plugin-core/operations';
7
+ import { parseJsonStrict } from '@shiqianjiang/ceru-plugin-issuer';
8
+ import { buildProject } from './project.js';
9
+ import { operationEventPermission } from '@shiqianjiang/ceru-plugin-sdk';
10
+ function scenarioSource(value) {
11
+ if (value === undefined)
12
+ return { kind: 'ui', location: 'scaffold-test' };
13
+ if (!value || typeof value !== 'object' || Array.isArray(value))
14
+ throw Error('Invalid hook source');
15
+ const source = value;
16
+ if (source.kind === 'ui' || source.kind === 'system') {
17
+ if (Object.keys(source).every(key => key === 'kind' || key === 'location') &&
18
+ (source.location === undefined || typeof source.location === 'string'))
19
+ return { kind: source.kind, ...(source.location === undefined ? {} : { location: source.location }) };
20
+ }
21
+ else if (source.kind === 'plugin' && typeof source.pluginId === 'string' &&
22
+ /^[a-z0-9][a-z0-9._-]{2,127}$/.test(source.pluginId) && (source.runtime === 2 || source.runtime === 3) &&
23
+ Object.keys(source).every(key => ['kind', 'pluginId', 'runtime'].includes(key))) {
24
+ return { kind: 'plugin', pluginId: source.pluginId, runtime: source.runtime };
25
+ }
26
+ throw Error('Invalid hook source');
27
+ }
28
+ export async function testHooks(project, fixture = 'tests/hooks.json', report = console.log) {
29
+ const path = resolve(project, fixture);
30
+ if ((await stat(path)).size > 1024 * 1024)
31
+ throw Error('Hook fixture must be at most 1 MiB');
32
+ const cases = parseJsonStrict(await readFile(path, 'utf8'));
33
+ if (!Array.isArray(cases) || !cases.length || cases.length > 100)
34
+ throw Error('Expected 1–100 hook scenarios');
35
+ const built = await buildProject(project), { artifact } = readPluginArtifact(await readFile(built.path));
36
+ const manifest = artifact.header.manifest;
37
+ for (const [index, row] of cases.entries()) {
38
+ const label = typeof row?.name === 'string' ? row.name : 'case ' + (index + 1);
39
+ try {
40
+ if ((!isPlaybackOperation(row.operation) && !isSystemOperation(row.operation) && row.operation !== 'share.create' && !isDownloadOperation(row.operation) && !isLyricOperation(row.operation) && row.operation !== 'window.close' && row.operation !== 'player.resolve' && row.operation !== 'account.switch' && !isLibraryOperation(row.operation) && !isSearchOperation(row.operation)) ||
41
+ typeof row.granted !== 'boolean' ||
42
+ !row.expect ||
43
+ typeof row.expect.prevented !== 'boolean')
44
+ throw Error('Expected operation, granted and expect.prevented');
45
+ const name = row.operation, parse = (value) => isSystemOperation(name) ? systemInput(name, value) : name === 'share.create' ? shareInput(name, value) : isDownloadOperation(name) ? downloadInput(name, value) : isLyricOperation(name) ? lyricInput(name, value) : name === 'window.close' ? windowCloseInput(name, value) : name === 'player.resolve' ? resolveInput(name, value) : name === 'account.switch' ? accountSwitchInput(name, value) : isLibraryOperation(name) ? libraryInput(name, value) : isSearchOperation(name) ? searchInput(name, value) : playbackInput(name, value), input = parse(row.input), source = scenarioSource(row.source);
46
+ if (!row.expect.prevented && !Object.hasOwn(row.expect, 'input'))
47
+ throw Error('Expected default input when not prevented');
48
+ if (row.expect.prevented && Object.hasOwn(row.expect, 'input'))
49
+ throw Error('Prevented scenarios cannot expect a default input');
50
+ const warnings = [];
51
+ const bus = new OperationBus(() => { }, (id, op) => warnings.push(id + ': ' + op));
52
+ const accounts = new OperationEngine(ACCOUNT_OPERATIONS, accountSwitchInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
53
+ const windows = new OperationEngine(WINDOW_OPERATIONS, windowCloseInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
54
+ const lyrics = new OperationEngine(LYRIC_OPERATIONS, lyricInput, () => { }, (id, op) => warnings.push(id + ': ' + op), undefined, undefined, undefined, lyricResult);
55
+ const downloads = new OperationEngine(DOWNLOAD_OPERATIONS, downloadInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
56
+ const sharing = new OperationEngine(SHARING_OPERATIONS, shareInput, () => { }, (id, op) => warnings.push(id + ': ' + op), undefined, undefined, undefined, shareResult);
57
+ const system = new OperationEngine(SYSTEM_OPERATIONS, systemInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
58
+ const resolves = new OperationEngine(RESOLVE_OPERATIONS, resolveInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
59
+ const library = new OperationEngine(LIBRARY_OPERATIONS, libraryInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
60
+ const searches = new OperationEngine(SEARCH_OPERATIONS, searchInput, () => { }, (id, op) => warnings.push(id + ': ' + op));
61
+ const declares = (permission) => manifest.uses?.permissions?.some(item => item.name === permission) === true;
62
+ const operationPermission = (operation) => isSystemOperation(operation) ? SYSTEM_OPERATIONS[operation].intercept : operation === 'share.create' ? 'sharing.intercept' : isDownloadOperation(operation) ? 'downloads.intercept' : isLyricOperation(operation) ? 'lyrics.intercept' : operation === 'window.close' ? 'window.intercept' : operation === 'account.switch' ? 'account.intercept' : isLibraryOperation(operation) ? 'library.intercept' : isSearchOperation(operation) ? 'search.intercept' : 'player.intercept';
63
+ const permission = operationPermission(name);
64
+ const worker = new NodePluginSandbox(async (method, data) => {
65
+ if (method === 'events.register') {
66
+ const done = typeof data.name === 'string' && data.name.endsWith(':done');
67
+ const name = done ? data.name.slice(0, -5) : data.name;
68
+ const required = operationEventPermission(data.name);
69
+ if (!required || !declares(required))
70
+ throw Error('Undeclared event permission');
71
+ const selected = isSystemOperation(name) ? systemOwner : name === 'share.create' ? sharingOwner : isDownloadOperation(name) ? downloadOwner : isLyricOperation(name) ? lyricOwner : name === 'window.close' ? windowOwner : name === 'account.switch' ? accountOwner : name === 'player.resolve' ? resolveOwner : isLibraryOperation(name) ? libraryOwner : isSearchOperation(name) ? searchOwner : owner;
72
+ selected.registerEvent(name, done, data.active);
73
+ return null;
74
+ }
75
+ if (method === 'hooks.register' && declares(operationPermission(data.name))) {
76
+ if (isSystemOperation(data.name))
77
+ systemOwner.register(data.name, data.priority);
78
+ else if (data.name === 'share.create')
79
+ sharingOwner.register(data.name, data.priority);
80
+ else if (isDownloadOperation(data.name))
81
+ downloadOwner.register(data.name, data.priority);
82
+ else if (isLyricOperation(data.name))
83
+ lyricOwner.register(data.name, data.priority);
84
+ else if (data.name === 'window.close')
85
+ windowOwner.register(data.name, data.priority);
86
+ else if (data.name === 'account.switch')
87
+ accountOwner.register(data.name, data.priority);
88
+ else if (data.name === 'player.resolve')
89
+ resolveOwner.register(data.name, data.priority);
90
+ else if (isLibraryOperation(data.name))
91
+ libraryOwner.register(data.name, data.priority);
92
+ else if (isSearchOperation(data.name))
93
+ searchOwner.register(data.name, data.priority);
94
+ else
95
+ owner.register(data.name, data.priority);
96
+ return null;
97
+ }
98
+ if (method === 'hooks.accountNext' && declares('account.intercept') && row.granted)
99
+ return accountOwner.next(data.token, data.input);
100
+ if (method === 'hooks.windowNext' && declares('window.intercept') && row.granted)
101
+ return windowOwner.next(data.token, data.input);
102
+ if (method === 'hooks.lyricsNext' && declares('lyrics.intercept') && row.granted)
103
+ return lyricOwner.next(data.token, data.input);
104
+ if (method === 'hooks.downloadsNext' && declares('downloads.intercept') && row.granted)
105
+ return downloadOwner.next(data.token, data.input);
106
+ if (method === 'hooks.sharingNext' && declares('sharing.intercept') && row.granted)
107
+ return sharingOwner.next(data.token, data.input);
108
+ if (method === 'hooks.linksNext' && declares('links.intercept') && row.granted)
109
+ return systemOwner.next(data.token, data.input);
110
+ if (method === 'hooks.notificationsNext' && declares('notifications.intercept') && row.granted)
111
+ return systemOwner.next(data.token, data.input);
112
+ if (method === 'hooks.resolveNext' && declares('player.intercept') && row.granted)
113
+ return resolveOwner.next(data.token, data.input);
114
+ if (method === 'hooks.libraryNext' && declares('library.intercept') && row.granted)
115
+ return libraryOwner.next(data.token, data.input);
116
+ if (method === 'hooks.searchNext' && declares('search.intercept') && row.granted)
117
+ return searchOwner.next(data.token, data.input);
118
+ if (method === 'hooks.next' && declares('player.intercept') && row.granted)
119
+ return owner.next(data.token, data.input);
120
+ if (method === 'config.get')
121
+ return manifest.config ?? {};
122
+ if (method === 'permissions.query')
123
+ return {
124
+ status: manifest.uses?.permissions?.some((p) => p.key === data.key && p.name === permission)
125
+ ? row.granted
126
+ ? 'granted'
127
+ : 'denied'
128
+ : 'undeclared',
129
+ };
130
+ throw Error('Unsupported hook test RPC: ' + method);
131
+ }, () => { });
132
+ const events = {
133
+ granted: (name, done) => {
134
+ const required = operationEventPermission(name + (done ? ':done' : ''));
135
+ return !!required && declares(required) && row.granted;
136
+ },
137
+ invoke: (name, done, payload, signal) => worker.invoke('operation-event', name + (done ? ':done' : ''), '', [payload], signal),
138
+ };
139
+ const owner = bus.connect(manifest.id, () => declares('player.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
140
+ const accountOwner = accounts.connect(manifest.id, () => declares('account.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
141
+ const windowOwner = windows.connect(manifest.id, () => declares('window.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
142
+ const lyricOwner = lyrics.connect(manifest.id, () => declares('lyrics.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
143
+ const downloadOwner = downloads.connect(manifest.id, () => declares('downloads.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
144
+ const sharingOwner = sharing.connect(manifest.id, () => declares('sharing.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
145
+ const systemOwner = system.connect(manifest.id, () => declares(permission) && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
146
+ const resolveOwner = resolves.connect(manifest.id, () => declares('player.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
147
+ const searchOwner = searches.connect(manifest.id, () => declares('search.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
148
+ const libraryOwner = library.connect(manifest.id, () => declares('library.intercept') && row.granted, (op, token, value, source, signal) => worker.invoke('operation-hook', op, '', [token, value, source], signal), events);
149
+ try {
150
+ await worker.start(artifact);
151
+ owner.attach();
152
+ resolveOwner.attach();
153
+ accountOwner.attach();
154
+ windowOwner.attach();
155
+ lyricOwner.attach();
156
+ downloadOwner.attach();
157
+ sharingOwner.attach();
158
+ systemOwner.attach();
159
+ searchOwner.attach();
160
+ libraryOwner.attach();
161
+ const defaults = [];
162
+ const localDefault = async (value) => {
163
+ defaults.push(value);
164
+ if (name === 'share.create')
165
+ return shareResult(name, row.defaultResult);
166
+ if (isLyricOperation(name))
167
+ return lyricResult(name, row.defaultResult, input);
168
+ if (name === 'player.resolve') {
169
+ const ok = row.resolveResults?.[defaults.length - 1];
170
+ if (typeof ok !== 'boolean')
171
+ throw Error('Expected a boolean resolveResults entry for each attempt');
172
+ return { ok };
173
+ }
174
+ };
175
+ const outcome = isSystemOperation(name) ? await system.run(name, input, source, localDefault) : name === 'share.create' ? await sharing.run(name, input, source, localDefault) : isDownloadOperation(name) ? await downloads.run(name, input, source, localDefault) : isLyricOperation(name) ? await lyrics.run(name, input, source, localDefault) : name === 'window.close' ? await windows.run(name, input, source, localDefault) : name === 'player.resolve' ? await resolves.run(name, input, source, localDefault) : name === 'account.switch' ? await accounts.run(name, input, source, localDefault) : isLibraryOperation(name) ? await library.run(name, input, source, localDefault) : isSearchOperation(name) ? await searches.run(name, input, source, localDefault) : await bus.run(name, input, source, localDefault);
176
+ assert.deepEqual(warnings, [], 'Hook timed out or threw an error');
177
+ assert.equal(outcome.prevented, row.expect.prevented);
178
+ assert.deepEqual(defaults, row.expect.prevented || row.expect.defaultCalled === false ? [] : name === 'player.resolve' && defaults.length === 2 ? [input, parse(row.expect.input)] : [parse(row.expect.input)]);
179
+ if (isLyricOperation(name))
180
+ assert.deepEqual(outcome.result, lyricResult(name, row.expect.result, input));
181
+ if (name === 'share.create')
182
+ assert.deepEqual(outcome.result, shareResult(name, row.expect.result));
183
+ if (name === 'player.resolve')
184
+ assert.equal(defaults.length, row.resolveResults.length, 'Unexpected resolve attempt count');
185
+ report('PASS ' + label);
186
+ }
187
+ finally {
188
+ owner.dispose();
189
+ resolveOwner.dispose();
190
+ accountOwner.dispose();
191
+ windowOwner.dispose();
192
+ lyricOwner.dispose();
193
+ downloadOwner.dispose();
194
+ sharingOwner.dispose();
195
+ systemOwner.dispose();
196
+ searchOwner.dispose();
197
+ libraryOwner.dispose();
198
+ worker.dispose();
199
+ }
200
+ }
201
+ catch (error) {
202
+ throw Error('Hook scenario “' +
203
+ label +
204
+ '” failed: ' +
205
+ (error instanceof Error ? error.message : String(error)));
206
+ }
207
+ }
208
+ report(cases.length + ' hook scenarios passed (local mock; no desktop or real playback).');
209
+ }
@@ -0,0 +1,4 @@
1
+ export declare function testServices(project: string, fixture?: string, report?: {
2
+ (...data: any[]): void;
3
+ (message?: any, ...optionalParams: any[]): void;
4
+ }): Promise<void>;
@@ -0,0 +1,54 @@
1
+ import assert from 'node:assert/strict';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { resolve } from 'node:path';
4
+ import { readPluginArtifact } from '@shiqianjiang/ceru-plugin-core';
5
+ import { createDispatcher } from '@shiqianjiang/ceru-plugin-core/dispatch';
6
+ import { NodePluginSandbox } from '@shiqianjiang/ceru-plugin-core/node';
7
+ import { parseJsonStrict } from '@shiqianjiang/ceru-plugin-issuer';
8
+ import { buildProject } from './project.js';
9
+ import { developmentPluginServices, readMockServices } from './dev-plugin-services.js';
10
+ export async function testServices(project, fixture = 'tests/services.json', report = console.log) {
11
+ const path = resolve(project, fixture);
12
+ if ((await stat(path)).size > 1024 * 1024)
13
+ throw Error('Service fixture must be at most 1 MiB');
14
+ const cases = parseJsonStrict(await readFile(path, 'utf8'));
15
+ if (!Array.isArray(cases) || !cases.length || cases.length > 100)
16
+ throw Error('Expected 1–100 service scenarios');
17
+ const mocks = await readMockServices(project);
18
+ const built = await buildProject(project);
19
+ const { artifact } = readPluginArtifact(await readFile(built.path));
20
+ const manifest = artifact.header.manifest;
21
+ for (const [index, scenario] of cases.entries()) {
22
+ const label = scenario?.name ?? 'case ' + (index + 1);
23
+ if (!scenario || !manifest.provides?.actions?.some(action => action.id === scenario.action) ||
24
+ typeof scenario.granted !== 'boolean' || Object.hasOwn(scenario, 'expect') === Object.hasOwn(scenario, 'error') ||
25
+ (Object.hasOwn(scenario, 'error') && (typeof scenario.error !== 'string' || !scenario.error)))
26
+ throw Error('Invalid service scenario: ' + label);
27
+ const services = developmentPluginServices(manifest, mocks);
28
+ const dispatch = createDispatcher(services, {
29
+ manifest, pluginId: manifest.id, log: { debug() { }, info() { }, warn() { }, error() { } },
30
+ async authorize(key, permission) {
31
+ if (permission !== 'services.consume' || !scenario.granted ||
32
+ !manifest.uses?.permissions?.some(item => item.key === key && item.name === permission))
33
+ throw Error('Permission denied: ' + permission);
34
+ },
35
+ });
36
+ const worker = new NodePluginSandbox(dispatch, () => { });
37
+ try {
38
+ await worker.start(artifact);
39
+ const action = worker.invoke('action', scenario.action, '', [scenario.input ?? null]);
40
+ if (Object.hasOwn(scenario, 'error'))
41
+ await assert.rejects(action, { message: `[action:${scenario.action}] ${scenario.error}` });
42
+ else
43
+ assert.deepEqual(await action, structuredClone(scenario.expect));
44
+ report('PASS ' + label);
45
+ }
46
+ catch (error) {
47
+ throw Error('Service scenario “' + label + '” failed: ' + (error instanceof Error ? error.message : String(error)));
48
+ }
49
+ finally {
50
+ worker.dispose();
51
+ }
52
+ }
53
+ report(cases.length + ' service scenarios passed (local mock; no desktop or real provider).');
54
+ }