@shiqianjiang/ceru-plugin-cli 0.1.1 → 0.2.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 (153) hide show
  1. package/README.md +9 -5
  2. package/assets/catalog.json +1 -1
  3. package/assets/core-contracts.js +1 -0
  4. package/assets/index.html +94 -93
  5. package/assets/playground.js +293 -30
  6. package/assets/sandbox.js +50 -19
  7. package/assets/style.css +16 -0
  8. package/dist/dependencies.d.ts +6 -0
  9. package/dist/dependencies.js +45 -0
  10. package/dist/dev.d.ts +2 -0
  11. package/dist/dev.js +297 -144
  12. package/dist/frameworks.d.ts +2 -2
  13. package/dist/frameworks.js +11 -29
  14. package/dist/index.js +12 -4
  15. package/dist/project.d.ts +1 -0
  16. package/dist/project.js +48 -21
  17. package/dist/socket-broker.d.ts +23 -0
  18. package/dist/socket-broker.js +230 -0
  19. package/package.json +71 -67
  20. package/schemas/config.schema.json +349 -0
  21. package/templates/connected-library/js/.vscode/ceru.code-snippets +37 -9
  22. package/templates/connected-library/js/.vscode/launch.json +36 -46
  23. package/templates/connected-library/js/.vscode/tasks.json +11 -3
  24. package/templates/connected-library/js/README.md +7 -2
  25. package/templates/connected-library/js/ceru-plugin.code-workspace +8 -0
  26. package/templates/connected-library/js/package.json +4 -3
  27. package/templates/connected-library/js/src/index.js +7 -5
  28. package/templates/connected-library/ts/.vscode/ceru.code-snippets +37 -9
  29. package/templates/connected-library/ts/.vscode/launch.json +36 -46
  30. package/templates/connected-library/ts/.vscode/tasks.json +11 -3
  31. package/templates/connected-library/ts/README.md +7 -2
  32. package/templates/connected-library/ts/ceru-plugin.code-workspace +8 -0
  33. package/templates/connected-library/ts/package.json +4 -3
  34. package/templates/connected-library/ts/src/index.ts +7 -5
  35. package/templates/guest-adapter/js/.vscode/ceru.code-snippets +37 -9
  36. package/templates/guest-adapter/js/.vscode/launch.json +36 -46
  37. package/templates/guest-adapter/js/.vscode/tasks.json +11 -3
  38. package/templates/guest-adapter/js/README.md +7 -2
  39. package/templates/guest-adapter/js/ceru-plugin.code-workspace +8 -0
  40. package/templates/guest-adapter/js/package.json +4 -3
  41. package/templates/guest-adapter/ts/.vscode/ceru.code-snippets +37 -9
  42. package/templates/guest-adapter/ts/.vscode/launch.json +36 -46
  43. package/templates/guest-adapter/ts/.vscode/tasks.json +11 -3
  44. package/templates/guest-adapter/ts/README.md +7 -2
  45. package/templates/guest-adapter/ts/ceru-plugin.code-workspace +8 -0
  46. package/templates/guest-adapter/ts/package.json +4 -3
  47. package/templates/importer/js/.vscode/ceru.code-snippets +37 -9
  48. package/templates/importer/js/.vscode/launch.json +36 -46
  49. package/templates/importer/js/.vscode/tasks.json +11 -3
  50. package/templates/importer/js/README.md +8 -3
  51. package/templates/importer/js/ceru-plugin.code-workspace +8 -0
  52. package/templates/importer/js/ceru.plugin.json +8 -24
  53. package/templates/importer/js/package.json +4 -3
  54. package/templates/importer/js/src/index.js +28 -34
  55. package/templates/importer/ts/.vscode/ceru.code-snippets +37 -9
  56. package/templates/importer/ts/.vscode/launch.json +36 -46
  57. package/templates/importer/ts/.vscode/tasks.json +11 -3
  58. package/templates/importer/ts/README.md +8 -3
  59. package/templates/importer/ts/ceru-plugin.code-workspace +8 -0
  60. package/templates/importer/ts/ceru.plugin.json +8 -24
  61. package/templates/importer/ts/package.json +4 -3
  62. package/templates/importer/ts/src/index.ts +28 -34
  63. package/templates/react/js/.vscode/ceru.code-snippets +37 -9
  64. package/templates/react/js/.vscode/launch.json +36 -46
  65. package/templates/react/js/.vscode/tasks.json +11 -3
  66. package/templates/react/js/README.md +7 -2
  67. package/templates/react/js/ceru-plugin.code-workspace +8 -0
  68. package/templates/react/js/ceru.plugin.json +1 -5
  69. package/templates/react/js/package.json +4 -3
  70. package/templates/react/ts/.vscode/ceru.code-snippets +37 -9
  71. package/templates/react/ts/.vscode/launch.json +36 -46
  72. package/templates/react/ts/.vscode/tasks.json +11 -3
  73. package/templates/react/ts/README.md +7 -2
  74. package/templates/react/ts/ceru-plugin.code-workspace +8 -0
  75. package/templates/react/ts/ceru.plugin.json +1 -5
  76. package/templates/react/ts/package.json +4 -3
  77. package/templates/snapshot.json +22 -2
  78. package/templates/source/js/.vscode/ceru.code-snippets +37 -9
  79. package/templates/source/js/.vscode/launch.json +36 -46
  80. package/templates/source/js/.vscode/tasks.json +11 -3
  81. package/templates/source/js/README.md +7 -2
  82. package/templates/source/js/ceru-plugin.code-workspace +8 -0
  83. package/templates/source/js/ceru.plugin.json +9 -0
  84. package/templates/source/js/package.json +4 -3
  85. package/templates/source/js/src/index.js +29 -26
  86. package/templates/source/ts/.vscode/ceru.code-snippets +37 -9
  87. package/templates/source/ts/.vscode/launch.json +36 -46
  88. package/templates/source/ts/.vscode/tasks.json +11 -3
  89. package/templates/source/ts/README.md +7 -2
  90. package/templates/source/ts/ceru-plugin.code-workspace +8 -0
  91. package/templates/source/ts/ceru.plugin.json +9 -0
  92. package/templates/source/ts/package.json +4 -3
  93. package/templates/source/ts/src/index.ts +29 -26
  94. package/templates/vue/js/.vscode/ceru.code-snippets +37 -9
  95. package/templates/vue/js/.vscode/launch.json +36 -46
  96. package/templates/vue/js/.vscode/tasks.json +11 -3
  97. package/templates/vue/js/README.md +7 -2
  98. package/templates/vue/js/ceru-plugin.code-workspace +8 -0
  99. package/templates/vue/js/ceru.plugin.json +1 -4
  100. package/templates/vue/js/package.json +4 -3
  101. package/templates/vue/ts/.vscode/ceru.code-snippets +37 -9
  102. package/templates/vue/ts/.vscode/launch.json +36 -46
  103. package/templates/vue/ts/.vscode/tasks.json +11 -3
  104. package/templates/vue/ts/README.md +7 -2
  105. package/templates/vue/ts/ceru-plugin.code-workspace +8 -0
  106. package/templates/vue/ts/ceru.plugin.json +1 -4
  107. package/templates/vue/ts/package.json +4 -3
  108. package/templates/vue-tsx/js/.vscode/ceru.code-snippets +37 -9
  109. package/templates/vue-tsx/js/.vscode/launch.json +36 -46
  110. package/templates/vue-tsx/js/.vscode/tasks.json +11 -3
  111. package/templates/vue-tsx/js/README.md +7 -2
  112. package/templates/vue-tsx/js/ceru-plugin.code-workspace +8 -0
  113. package/templates/vue-tsx/js/ceru.plugin.json +1 -4
  114. package/templates/vue-tsx/js/package.json +4 -3
  115. package/templates/vue-tsx/ts/.vscode/ceru.code-snippets +37 -9
  116. package/templates/vue-tsx/ts/.vscode/launch.json +36 -46
  117. package/templates/vue-tsx/ts/.vscode/tasks.json +11 -3
  118. package/templates/vue-tsx/ts/README.md +7 -2
  119. package/templates/vue-tsx/ts/ceru-plugin.code-workspace +8 -0
  120. package/templates/vue-tsx/ts/ceru.plugin.json +1 -4
  121. package/templates/vue-tsx/ts/package.json +4 -3
  122. package/templates/web-dist/js/.vscode/ceru.code-snippets +37 -9
  123. package/templates/web-dist/js/.vscode/launch.json +36 -46
  124. package/templates/web-dist/js/.vscode/tasks.json +11 -3
  125. package/templates/web-dist/js/README.md +7 -2
  126. package/templates/web-dist/js/ceru-plugin.code-workspace +8 -0
  127. package/templates/web-dist/js/package.json +4 -3
  128. package/templates/web-dist/ts/.vscode/ceru.code-snippets +37 -9
  129. package/templates/web-dist/ts/.vscode/launch.json +36 -46
  130. package/templates/web-dist/ts/.vscode/tasks.json +11 -3
  131. package/templates/web-dist/ts/README.md +7 -2
  132. package/templates/web-dist/ts/ceru-plugin.code-workspace +8 -0
  133. package/templates/web-dist/ts/package.json +4 -3
  134. package/templates/web-surface/js/.vscode/ceru.code-snippets +37 -9
  135. package/templates/web-surface/js/.vscode/launch.json +36 -46
  136. package/templates/web-surface/js/.vscode/tasks.json +11 -3
  137. package/templates/web-surface/js/README.md +7 -2
  138. package/templates/web-surface/js/ceru-plugin.code-workspace +8 -0
  139. package/templates/web-surface/js/ceru.plugin.json +9 -0
  140. package/templates/web-surface/js/package.json +4 -3
  141. package/templates/web-surface/js/src/view.js +4 -1
  142. package/templates/web-surface/js/ui/search-note.css +3 -0
  143. package/templates/web-surface/ts/.vscode/ceru.code-snippets +37 -9
  144. package/templates/web-surface/ts/.vscode/launch.json +36 -46
  145. package/templates/web-surface/ts/.vscode/tasks.json +11 -3
  146. package/templates/web-surface/ts/README.md +7 -2
  147. package/templates/web-surface/ts/ceru-plugin.code-workspace +8 -0
  148. package/templates/web-surface/ts/ceru.plugin.json +9 -0
  149. package/templates/web-surface/ts/package.json +4 -3
  150. package/templates/web-surface/ts/src/view.ts +4 -1
  151. package/templates/web-surface/ts/ui/search-note.css +3 -0
  152. package/assets/shared-react.js +0 -77
  153. package/assets/shared-vue.js +0 -44
@@ -8,15 +8,6 @@ import { transformAsync } from '@babel/core';
8
8
  import vueJsx from '@vue/babel-plugin-jsx';
9
9
  import { parse as parseHtml, serialize } from 'parse5';
10
10
  import { parse as parseJs } from 'acorn';
11
- export const SHARED_IMPORTS = {
12
- vue: 'vue',
13
- 'vue/jsx-runtime': 'vue',
14
- react: 'react',
15
- 'react/jsx-runtime': 'react',
16
- 'react/jsx-dev-runtime': 'react',
17
- 'react-dom': 'react-dom',
18
- 'react-dom/client': 'react-dom',
19
- };
20
11
  const mime = {
21
12
  '.png': 'image/png',
22
13
  '.jpg': 'image/jpeg',
@@ -64,29 +55,20 @@ async function cssBundle(css, directory) {
64
55
  throw new Error('CSS emitted an external resource');
65
56
  return result.outputFiles[0].text;
66
57
  }
67
- export function sharedPlugin(libraries = {}) {
68
- if (!!libraries.react !== !!libraries['react-dom'])
69
- throw new Error('Share react and react-dom together to avoid duplicate React runtimes');
58
+ /** Side-effect stylesheet imports must survive single-file builds (React/Vue/vanilla). */
59
+ export function stylesheetPlugin() {
70
60
  return {
71
- name: 'ceru-host-libraries',
61
+ name: 'ceru-inline-stylesheets',
72
62
  setup(ctx) {
73
- ctx.onResolve({ filter: /^(vue(?:\/.*)?|react(?:\/.*)?|react-dom(?:\/.*)?)$/ }, (args) => {
74
- const root = SHARED_IMPORTS[args.path];
75
- const family = args.path.startsWith('vue')
76
- ? 'vue'
77
- : args.path.startsWith('react-dom')
78
- ? 'react-dom'
79
- : 'react';
80
- if (!libraries[family])
81
- return;
82
- if (!root)
83
- return { errors: [{ text: 'Unsupported shared runtime import: ' + args.path }] };
84
- return { path: args.path, namespace: 'ceru-host-library' };
63
+ ctx.onLoad({ filter: /\.css$/ }, async (args) => {
64
+ const css = await cssBundle(await readFile(args.path, 'utf8'), dirname(args.path));
65
+ const id = createHash('sha256').update(css).digest('hex').slice(0, 16);
66
+ return {
67
+ contents: 'export default ' + JSON.stringify(css) + ';' + styleCode(css, id),
68
+ loader: 'js',
69
+ resolveDir: dirname(args.path),
70
+ };
85
71
  });
86
- ctx.onLoad({ filter: /.*/, namespace: 'ceru-host-library' }, (args) => ({
87
- contents: 'module.exports = globalThis.__ceruSharedRequire(' + JSON.stringify(args.path) + ');',
88
- loader: 'js',
89
- }));
90
72
  },
91
73
  };
92
74
  }
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { createTemplate, generateSigningKeys, parseJsonStrict, PreparedIssuer, r
6
6
  import { buildProject, scaffoldProject, TEMPLATES, writeAtomic } from './project.js';
7
7
  import { runDev } from './dev.js';
8
8
  export { buildProject, loadProject, scaffoldProject, TEMPLATES } from './project.js';
9
- const VERSION = '0.1.0';
9
+ const VERSION = '0.2.0';
10
10
  const HELP = 'Ceru Plugin CLI ' +
11
11
  VERSION +
12
12
  '\n\n' +
@@ -16,6 +16,7 @@ const HELP = 'Ceru Plugin CLI ' +
16
16
  ' list-templates\n' +
17
17
  ' build [--project directory] [--out dist/plugin.js]\n' +
18
18
  ' dev [--project directory] [--port 4179] [--debug-port 9223] [--no-open]\n' +
19
+ ' preview <plugin.js> [--port 4179] [--debug-port 9223] [--no-open]\n' +
19
20
  ' validate <plugin.js> [--trusted-key publisher.public.pem] [--json]\n' +
20
21
  ' keygen --out .keys/publisher\n' +
21
22
  ' sign <plugin.js> --key private.pem [--out signed.js] [--force]\n' +
@@ -24,8 +25,8 @@ const HELP = 'Ceru Plugin CLI ' +
24
25
  'TypeScript is type-checked before build. Final output is one .js file.\n' +
25
26
  'v2 Host integration is required. Validation does not execute or sandbox plugin code.\n';
26
27
  async function jsOutput(path, bytes, force) {
27
- if (!['.js', '.jsx'].includes(extname(path)))
28
- throw new Error('Output must be .js or .jsx containing compiled JavaScript');
28
+ if (extname(path) !== '.js')
29
+ throw new Error('Output must be .js containing compiled JavaScript');
29
30
  await writeAtomic(resolve(path), bytes, force);
30
31
  console.log('Wrote ' + resolve(path) + ' (' + bytes.length + ' bytes)');
31
32
  }
@@ -43,6 +44,7 @@ export async function runCli(argv = process.argv.slice(2)) {
43
44
  port: { type: 'string' },
44
45
  'debug-port': { type: 'string' },
45
46
  'no-open': { type: 'boolean' },
47
+ 'ensure-running': { type: 'boolean' },
46
48
  hidden: { type: 'boolean' },
47
49
  electron: { type: 'string' },
48
50
  key: { type: 'string' },
@@ -121,13 +123,17 @@ export async function runCli(argv = process.argv.slice(2)) {
121
123
  console.log('Built ' + output.path + ' (' + output.bytes + ' bytes)');
122
124
  return;
123
125
  }
124
- if (command === 'dev') {
126
+ if (command === 'dev' || command === 'preview') {
127
+ if (command === 'preview' && !positionals[1])
128
+ throw new Error('An artifact file is required');
125
129
  await runDev(flags.project ?? '.', {
126
130
  port: Number(flags.port ?? 4179),
127
131
  debugPort: Number(flags['debug-port'] ?? 9223),
128
132
  noOpen: flags['no-open'],
129
133
  hidden: flags.hidden,
130
134
  electron: flags.electron,
135
+ artifact: command === 'preview' ? resolve(positionals[1]) : undefined,
136
+ ensureRunning: flags['ensure-running'],
131
137
  });
132
138
  return;
133
139
  }
@@ -166,6 +172,8 @@ export async function runCli(argv = process.argv.slice(2)) {
166
172
  bytes: bytes.length,
167
173
  modules: Object.keys(result.modules),
168
174
  resources: Object.keys(result.resources),
175
+ sourceFormat: result.sourceFormat,
176
+ migrationWarnings: result.migrationWarnings,
169
177
  signature: result.signatureStatus,
170
178
  codeDigest: result.codeDigest,
171
179
  templateDigest: result.templateDigest,
package/dist/project.d.ts CHANGED
@@ -9,6 +9,7 @@ export interface BuildConfig {
9
9
  }>;
10
10
  output?: string;
11
11
  framework?: 'vanilla' | 'vue' | 'react';
12
+ /** @deprecated Accepted to migrate 0.1.0 projects; frameworks are now always bundled. */
12
13
  sharedLibraries?: Partial<Record<'vue' | 'react' | 'react-dom', string>>;
13
14
  webDist?: Record<string, string>;
14
15
  }
package/dist/project.js CHANGED
@@ -6,7 +6,8 @@ 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 { sharedPlugin, vuePlugin, webDistEntry } from './frameworks.js';
9
+ import { stylesheetPlugin, vuePlugin, webDistEntry } from './frameworks.js';
10
+ import { hostModulesPlugin, assertBundledDependencies } from './dependencies.js';
10
11
  import { encodeArtifact, parseJsonStrict, readArtifact, validateManifest, LIMITS, } from '@shiqianjiang/ceru-plugin-issuer';
11
12
  export async function writeAtomic(path, data, overwrite = false, mode = 0o644) {
12
13
  await mkdir(dirname(path), { recursive: true });
@@ -51,8 +52,10 @@ export async function loadProject(project) {
51
52
  'webDist',
52
53
  ].includes(key))
53
54
  throw new Error('Unknown build config key: ' + key);
54
- if (raw.sharedLibraries !== undefined)
55
- raw.manifest.engines.libraries = raw.sharedLibraries;
55
+ // Older scaffolds declared Host-provided Vue/React. Always migrate their output
56
+ // to standalone bundles, without requiring authors to rewrite their source.
57
+ if (raw.manifest?.engines)
58
+ delete raw.manifest.engines.libraries;
56
59
  if (raw.framework && !['vanilla', 'vue', 'react'].includes(raw.framework))
57
60
  throw new Error('Unsupported framework');
58
61
  validateManifest(raw.manifest);
@@ -93,9 +96,9 @@ export async function buildProject(project = '.', options = {}) {
93
96
  }
94
97
  const program = checkTypes(root);
95
98
  const checker = program.getTypeChecker();
96
- const chunks = [];
99
+ const chunks = new Map();
97
100
  const devModules = {};
98
- const plugins = [sharedPlugin(config.sharedLibraries), vuePlugin(root, config.framework)];
101
+ const plugins = [hostModulesPlugin(), vuePlugin(root, config.framework), stylesheetPlugin()];
99
102
  const defines = {
100
103
  'process.env.NODE_ENV': '"production"',
101
104
  __VUE_OPTIONS_API__: 'true',
@@ -134,7 +137,7 @@ export async function buildProject(project = '.', options = {}) {
134
137
  plugins,
135
138
  define: defines,
136
139
  loader: {
137
- '.svg': 'text',
140
+ '.svg': 'dataurl',
138
141
  '.css': 'text',
139
142
  '.png': 'dataurl',
140
143
  '.jpg': 'dataurl',
@@ -149,8 +152,8 @@ export async function buildProject(project = '.', options = {}) {
149
152
  if (info.imports.length)
150
153
  throw new Error('Unbundled import in ' + id);
151
154
  const source = result.outputFiles[0].text;
152
- chunks.push(JSON.stringify(id) +
153
- ': async function(ctx) {\n' +
155
+ assertBundledDependencies(source);
156
+ chunks.set(id, 'async function(ctx) {\n' +
154
157
  source +
155
158
  '\nif (typeof __ceru_entry.default !== "function") throw new Error("Entry must default-export a function");\nreturn __ceru_entry.default(ctx);\n}');
156
159
  if (options.development) {
@@ -172,9 +175,10 @@ export async function buildProject(project = '.', options = {}) {
172
175
  outfile: 'entry.js',
173
176
  plugins,
174
177
  define: defines,
175
- footer: { js: 'globalThis.__ceruStart(__ceru_entry.default);' },
178
+ banner: { js: 'globalThis.__ceruStart(async function(ctx) {' },
179
+ footer: { js: 'return __ceru_entry.default(ctx); });' },
176
180
  loader: {
177
- '.svg': 'text',
181
+ '.svg': 'dataurl',
178
182
  '.css': 'text',
179
183
  '.png': 'dataurl',
180
184
  '.jpg': 'dataurl',
@@ -208,8 +212,8 @@ export async function buildProject(project = '.', options = {}) {
208
212
  const result = await build(base);
209
213
  if (result.outputFiles.length !== 1)
210
214
  throw new Error('webDist emitted an external file');
211
- chunks.push(JSON.stringify(id) +
212
- ': async function(ctx) {\n' +
215
+ assertBundledDependencies(result.outputFiles[0].text);
216
+ chunks.set(id, 'async function(ctx) {\n' +
213
217
  result.outputFiles[0].text +
214
218
  '\nreturn __ceru_entry.default(ctx);\n}');
215
219
  if (options.development) {
@@ -217,7 +221,8 @@ export async function buildProject(project = '.', options = {}) {
217
221
  ...base,
218
222
  sourcemap: 'inline',
219
223
  sourceRoot: 'ceru:///',
220
- footer: { js: 'globalThis.__ceruStart(__ceru_entry.default);' },
224
+ banner: { js: 'globalThis.__ceruStart(async function(ctx) {' },
225
+ footer: { js: 'return __ceru_entry.default(ctx); });' },
221
226
  });
222
227
  devModules[id] = debug.outputFiles[0].text;
223
228
  }
@@ -250,22 +255,44 @@ export async function buildProject(project = '.', options = {}) {
250
255
  mime: input.mime ?? 'application/octet-stream',
251
256
  };
252
257
  }
253
- const body = 'CeruPlugin.define({\nmodules: {\n' +
254
- chunks.join(',\n') +
255
- '\n},\nresources: ' +
256
- JSON.stringify(resources) +
257
- '\n})\n';
258
+ const emitted = new Set();
259
+ const body = [];
260
+ const logicEntry = config.manifest.modules.logic?.entry;
261
+ if (logicEntry) {
262
+ const logic = chunks.get(logicEntry);
263
+ if (!logic)
264
+ throw new Error('Missing compiled logic entry: ' + logicEntry);
265
+ body.push('exports.activate = ' + logic + ';');
266
+ emitted.add(logicEntry);
267
+ }
268
+ const visibleSurfaces = (config.manifest.modules.surfaces ?? []).filter((surface) => surface.kind === 'web');
269
+ if (visibleSurfaces.length) {
270
+ const entries = visibleSurfaces.map((surface) => {
271
+ const entry = chunks.get(surface.entry);
272
+ if (!entry)
273
+ throw new Error('Missing compiled Surface entry: ' + surface.entry);
274
+ emitted.add(surface.entry);
275
+ return JSON.stringify(surface.id) + ': ' + entry;
276
+ });
277
+ body.push('exports.surfaces = {\n' + entries.join(',\n') + '\n};');
278
+ }
279
+ const modules = [...chunks].filter(([id]) => !emitted.has(id));
280
+ if (modules.length)
281
+ body.push('exports.modules = {\n' +
282
+ modules.map(([id, entry]) => JSON.stringify(id) + ': ' + entry).join(',\n') +
283
+ '\n};');
284
+ body.push('exports.resources = ' + JSON.stringify(resources) + ';');
258
285
  const header = {
259
286
  formatVersion: 2,
260
287
  syntax: 'js',
261
288
  manifest: config.manifest,
262
289
  signature: null,
263
290
  };
264
- const artifact = encodeArtifact(header, body);
291
+ const artifact = encodeArtifact(header, body.join('\n') + '\n');
265
292
  readArtifact(artifact);
266
293
  const output = resolve(root, options.out ?? config.output ?? 'dist/plugin.js');
267
- if (!['.js', '.jsx'].includes(extname(output)))
268
- throw new Error('Final output must be a .js or .jsx file containing compiled JavaScript');
294
+ if (extname(output) !== '.js')
295
+ throw new Error('Final output must be a .js file containing compiled JavaScript');
269
296
  const rel = relative(root, output);
270
297
  if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel))
271
298
  throw new Error('Build output must stay inside project');
@@ -0,0 +1,23 @@
1
+ interface SocketEvent {
2
+ id: string;
3
+ event: string;
4
+ data: unknown;
5
+ }
6
+ /** Network libraries live in the Host. Plugins receive bounded JSON events and opaque handles. */
7
+ export declare class SocketBroker {
8
+ private readonly connections;
9
+ private events;
10
+ private generation;
11
+ private connecting;
12
+ connect(input: any, privateAllowed: boolean, reservedPorts: number[]): Promise<{
13
+ id: string;
14
+ }>;
15
+ private push;
16
+ send(id: string, event: string, data: unknown): void;
17
+ private release;
18
+ disconnect(id: string): void;
19
+ revoke(key: string): void;
20
+ closeAll(): void;
21
+ drain(): SocketEvent[];
22
+ }
23
+ export {};
@@ -0,0 +1,230 @@
1
+ import { lookup } from 'node:dns/promises';
2
+ import { isIP } from 'node:net';
3
+ import { Agent as HttpAgent } from 'node:http';
4
+ import { Agent as HttpsAgent } from 'node:https';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { io } from 'socket.io-client';
7
+ import WebSocket from 'ws';
8
+ const privateAddress = (address) => {
9
+ const value = address.toLowerCase();
10
+ if (value.startsWith('::ffff:'))
11
+ return privateAddress(value.slice('::ffff:'.length));
12
+ if (value.includes(':'))
13
+ return (value === '::1' ||
14
+ value.startsWith('fc') ||
15
+ value.startsWith('fd') ||
16
+ value.startsWith('fe80'));
17
+ const parts = value.split('.').map(Number);
18
+ return (parts[0] === 0 ||
19
+ parts[0] === 10 ||
20
+ parts[0] === 127 ||
21
+ (parts[0] === 169 && parts[1] === 254) ||
22
+ (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) ||
23
+ (parts[0] === 198 && (parts[1] === 18 || parts[1] === 19)) ||
24
+ parts[0] >= 224 ||
25
+ (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
26
+ (parts[0] === 192 && parts[1] === 168));
27
+ };
28
+ const reservedEvents = new Set([
29
+ 'connect',
30
+ 'connect_error',
31
+ 'disconnect',
32
+ 'disconnecting',
33
+ 'newListener',
34
+ 'removeListener',
35
+ 'error',
36
+ '__proto__',
37
+ 'constructor',
38
+ 'prototype',
39
+ ]);
40
+ /** Network libraries live in the Host. Plugins receive bounded JSON events and opaque handles. */
41
+ export class SocketBroker {
42
+ connections = new Map();
43
+ events = [];
44
+ generation = 0;
45
+ connecting = 0;
46
+ async connect(input, privateAllowed, reservedPorts) {
47
+ if (this.connections.size + this.connecting >= 8)
48
+ throw new Error('Socket connection limit reached');
49
+ this.connecting++;
50
+ const generation = this.generation;
51
+ try {
52
+ const kind = input.kind;
53
+ if (!['websocket', 'socket.io'].includes(kind))
54
+ throw new Error('Unknown socket protocol');
55
+ const url = new URL(input.url);
56
+ if (url.username ||
57
+ url.password ||
58
+ url.hash ||
59
+ (kind === 'websocket'
60
+ ? !['ws:', 'wss:'].includes(url.protocol)
61
+ : !['http:', 'https:'].includes(url.protocol)))
62
+ throw new Error('Unsupported socket URL');
63
+ const path = kind === 'socket.io' ? String(input.path || '/socket.io/') : url.pathname;
64
+ if (!path.startsWith('/') || path.startsWith('//') || /[?#\\]|%(?:2f|5c)/i.test(path))
65
+ throw new Error('Invalid socket path');
66
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
67
+ const addresses = isIP(hostname)
68
+ ? [{ address: hostname, family: isIP(hostname) }]
69
+ : await lookup(hostname, { all: true });
70
+ if (!addresses.length)
71
+ throw new Error('No socket address found');
72
+ if (addresses.some((item) => privateAddress(item.address)) && !privateAllowed)
73
+ throw new Error('Private network access is not granted');
74
+ const defaultPort = ['https:', 'wss:'].includes(url.protocol) ? 443 : 80;
75
+ if (reservedPorts.includes(Number(url.port) || defaultPort))
76
+ throw new Error('Development ports are reserved');
77
+ const chosen = addresses[0];
78
+ const Agent = ['https:', 'wss:'].includes(url.protocol) ? HttpsAgent : HttpAgent;
79
+ const agent = new Agent({
80
+ lookup: ((_hostname, options, callback) => options?.all
81
+ ? callback(null, [chosen])
82
+ : callback(null, chosen.address, chosen.family)),
83
+ });
84
+ const id = randomUUID();
85
+ let socket;
86
+ if (kind === 'socket.io') {
87
+ const auth = input.auth ?? {};
88
+ if (Buffer.byteLength(JSON.stringify(auth)) > 16384) {
89
+ agent.destroy();
90
+ throw new Error('Socket auth is too large');
91
+ }
92
+ socket = io(url.href, {
93
+ path,
94
+ auth,
95
+ autoConnect: false,
96
+ forceNew: true,
97
+ transports: ['websocket'],
98
+ upgrade: false,
99
+ reconnection: input.reconnection !== false,
100
+ reconnectionAttempts: 5,
101
+ reconnectionDelay: 1000,
102
+ reconnectionDelayMax: 10000,
103
+ timeout: 10000,
104
+ transportOptions: { websocket: { agent, followRedirects: false, maxPayload: 65536 } },
105
+ });
106
+ socket.on('connect', () => this.push(id, 'connect', null));
107
+ socket.on('disconnect', (reason) => this.push(id, 'disconnect', reason));
108
+ socket.on('connect_error', () => this.push(id, 'error', 'Socket.IO connection failed'));
109
+ socket.onAny((event, ...args) => this.push(id, String(event), args));
110
+ }
111
+ else {
112
+ socket = new WebSocket(url.href, {
113
+ agent,
114
+ followRedirects: false,
115
+ handshakeTimeout: 10000,
116
+ maxPayload: 65536,
117
+ });
118
+ socket.on('open', () => this.push(id, 'connect', null));
119
+ socket.on('close', (code) => {
120
+ this.push(id, 'disconnect', { code });
121
+ this.release(id);
122
+ });
123
+ socket.on('error', () => this.push(id, 'error', 'WebSocket connection failed'));
124
+ socket.on('message', (data, binary) => {
125
+ if (binary) {
126
+ this.push(id, 'error', 'Binary frames are not supported by this JSON channel');
127
+ return;
128
+ }
129
+ this.push(id, 'message', data.toString());
130
+ });
131
+ }
132
+ this.connections.set(id, {
133
+ key: String(input.permissionKey),
134
+ kind,
135
+ socket,
136
+ agent,
137
+ lastSend: Date.now(),
138
+ sends: 0,
139
+ });
140
+ if (generation !== this.generation) {
141
+ this.disconnect(id);
142
+ throw new Error('Plugin was stopped while connecting');
143
+ }
144
+ if (kind === 'socket.io')
145
+ socket.connect();
146
+ return { id };
147
+ }
148
+ finally {
149
+ this.connecting--;
150
+ }
151
+ }
152
+ push(id, event, data) {
153
+ if (!this.connections.has(id))
154
+ return;
155
+ let text;
156
+ try {
157
+ text = JSON.stringify(data ?? null);
158
+ }
159
+ catch {
160
+ this.disconnect(id);
161
+ return;
162
+ }
163
+ if (Buffer.byteLength(text) > 65536 || this.events.length >= 256) {
164
+ this.disconnect(id);
165
+ return;
166
+ }
167
+ this.events.push({ id, event, data: JSON.parse(text) });
168
+ }
169
+ send(id, event, data) {
170
+ const entry = this.connections.get(id);
171
+ if (!entry)
172
+ throw new Error('Socket is closed');
173
+ const text = JSON.stringify(data ?? null);
174
+ if (Buffer.byteLength(text) > 65536)
175
+ throw new Error('Socket message is too large');
176
+ if (Date.now() - entry.lastSend >= 1000) {
177
+ entry.lastSend = Date.now();
178
+ entry.sends = 0;
179
+ }
180
+ if (++entry.sends > 100)
181
+ throw new Error('Socket send rate exceeded');
182
+ if (entry.kind === 'socket.io') {
183
+ if (typeof event !== 'string' || event.length > 128 || reservedEvents.has(event))
184
+ throw new Error('Invalid Socket.IO event');
185
+ const socket = entry.socket;
186
+ if (!socket.connected)
187
+ throw new Error('Socket is not connected');
188
+ socket.emit(event, data);
189
+ }
190
+ else {
191
+ const socket = entry.socket;
192
+ if (socket.readyState !== WebSocket.OPEN)
193
+ throw new Error('Socket is not connected');
194
+ socket.send(typeof data === 'string' ? data : text);
195
+ }
196
+ }
197
+ release(id) {
198
+ const entry = this.connections.get(id);
199
+ this.connections.delete(id);
200
+ entry?.agent.destroy();
201
+ }
202
+ disconnect(id) {
203
+ const entry = this.connections.get(id);
204
+ if (!entry)
205
+ return;
206
+ this.connections.delete(id);
207
+ if (entry.kind === 'socket.io')
208
+ entry.socket.disconnect();
209
+ else
210
+ entry.socket.terminate();
211
+ entry.agent.destroy();
212
+ this.events = this.events.filter((event) => event.id !== id);
213
+ }
214
+ revoke(key) {
215
+ for (const [id, entry] of this.connections)
216
+ if (entry.key === key)
217
+ this.disconnect(id);
218
+ }
219
+ closeAll() {
220
+ this.generation++;
221
+ for (const id of this.connections.keys())
222
+ this.disconnect(id);
223
+ this.events = [];
224
+ }
225
+ drain() {
226
+ const events = this.events;
227
+ this.events = [];
228
+ return events;
229
+ }
230
+ }
package/package.json CHANGED
@@ -1,67 +1,71 @@
1
- {
2
- "name": "@shiqianjiang/ceru-plugin-cli",
3
- "version": "0.1.1",
4
- "description": "TypeScript scaffolding, single-file build, watch, validation, signing and issuance for Ceru plugins",
5
- "type": "module",
6
- "main": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "default": "./dist/index.js"
13
- }
14
- },
15
- "bin": {
16
- "ceru-plugin": "./dist/bin.js"
17
- },
18
- "files": [
19
- "dist",
20
- "assets",
21
- "schemas",
22
- "templates",
23
- "README.md",
24
- "LICENSE",
25
- "ASSET_LICENSE",
26
- "NOTICE"
27
- ],
28
- "license": "MIT AND AGPL-3.0-only",
29
- "author": "澜音团队",
30
- "engines": {
31
- "node": ">=22.12.0"
32
- },
33
- "dependencies": {
34
- "@shiqianjiang/ceru-plugin-issuer": "0.1.0",
35
- "@babel/core": "^7.29.7",
36
- "@vue/babel-plugin-jsx": "^2.0.1",
37
- "@vue/compiler-sfc": "3.5.43",
38
- "esbuild": "^0.28.2",
39
- "lodash-es": "^4.18.1",
40
- "parse5": "^8.0.1",
41
- "semver": "^7.7.0",
42
- "vue": "3.5.43",
43
- "vue-tsc": "^3.3.11",
44
- "react": "19.3.0",
45
- "react-dom": "19.3.0",
46
- "typescript": "~5.9.3"
47
- },
48
- "publishConfig": {
49
- "access": "public",
50
- "registry": "https://registry.npmjs.org/"
51
- },
52
- "repository": {
53
- "type": "git",
54
- "url": "git+https://github.com/CeruMusic/CeruMusic-Plugin-Cli.git",
55
- "directory": "packages/cli"
56
- },
57
- "bugs": {
58
- "url": "https://github.com/CeruMusic/CeruMusic-Plugin-Cli/issues"
59
- },
60
- "homepage": "https://github.com/CeruMusic/CeruMusic-Plugin-Cli#readme",
61
- "keywords": [
62
- "ceru-music",
63
- "plugin",
64
- "typescript",
65
- "electron"
66
- ]
67
- }
1
+ {
2
+ "name": "@shiqianjiang/ceru-plugin-cli",
3
+ "version": "0.2.0",
4
+ "description": "TypeScript scaffolding, single-file build, watch, validation, signing and issuance for Ceru plugins",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "bin": {
16
+ "ceru-plugin": "./dist/bin.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "assets",
21
+ "schemas",
22
+ "templates",
23
+ "README.md",
24
+ "LICENSE",
25
+ "ASSET_LICENSE",
26
+ "NOTICE"
27
+ ],
28
+ "license": "MIT AND AGPL-3.0-only",
29
+ "author": "澜音团队",
30
+ "engines": {
31
+ "node": ">=22.12.0"
32
+ },
33
+ "dependencies": {
34
+ "@babel/core": "^7.29.7",
35
+ "@shiqianjiang/ceru-plugin-issuer": "0.2.0",
36
+ "@shiqianjiang/ceru-plugin-sdk": "0.2.0",
37
+ "@vue/babel-plugin-jsx": "^2.0.1",
38
+ "@vue/compiler-sfc": "3.5.43",
39
+ "axios": "^1.20.0",
40
+ "esbuild": "^0.28.2",
41
+ "lodash-es": "^4.18.1",
42
+ "parse5": "^8.0.1",
43
+ "react": "19.3.0",
44
+ "react-dom": "19.3.0",
45
+ "semver": "^7.7.0",
46
+ "socket.io-client": "^4.8.3",
47
+ "typescript": "~5.9.3",
48
+ "vue": "3.5.43",
49
+ "vue-tsc": "^3.3.11",
50
+ "ws": "^8.21.3"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public",
54
+ "registry": "https://registry.npmjs.org/"
55
+ },
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/CeruMusic/CeruMusic-Plugin-Cli.git",
59
+ "directory": "packages/cli"
60
+ },
61
+ "bugs": {
62
+ "url": "https://github.com/CeruMusic/CeruMusic-Plugin-Cli/issues"
63
+ },
64
+ "homepage": "https://github.com/CeruMusic/CeruMusic-Plugin-Cli#readme",
65
+ "keywords": [
66
+ "ceru-music",
67
+ "plugin",
68
+ "typescript",
69
+ "electron"
70
+ ]
71
+ }