@zseven-w/qoder-openpencil 0.0.0-stage → 0.1.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 (63) hide show
  1. package/INSTALL.md +77 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +10 -0
  4. package/README.md +46 -2
  5. package/README.zh.md +38 -0
  6. package/THIRD_PARTY_NOTICES.md +69 -0
  7. package/bin/qoder-openpencil.mjs +90 -0
  8. package/package.json +71 -4
  9. package/platforms.json +65 -0
  10. package/plugins/openpencil/.mcp.json +10 -0
  11. package/plugins/openpencil/.qoder-plugin/plugin.json +19 -0
  12. package/plugins/openpencil/CONNECTORS.md +9 -0
  13. package/plugins/openpencil/LICENSE +21 -0
  14. package/plugins/openpencil/NOTICE +10 -0
  15. package/plugins/openpencil/assets/icon.png +0 -0
  16. package/plugins/openpencil/assets/logo.png +0 -0
  17. package/plugins/openpencil/mcp.json +11 -0
  18. package/plugins/openpencil/plugin.json +19 -0
  19. package/plugins/openpencil/scripts/browser-launch.mjs +37 -0
  20. package/plugins/openpencil/scripts/canvas-codegen.mjs +141 -0
  21. package/plugins/openpencil/scripts/canvas-controller.mjs +293 -0
  22. package/plugins/openpencil/scripts/canvas-images.mjs +93 -0
  23. package/plugins/openpencil/scripts/canvas-panel.mjs +82 -0
  24. package/plugins/openpencil/scripts/canvas-selection.mjs +61 -0
  25. package/plugins/openpencil/scripts/document-format.mjs +48 -0
  26. package/plugins/openpencil/scripts/editor-runtime.mjs +453 -0
  27. package/plugins/openpencil/scripts/editor-session.mjs +230 -0
  28. package/plugins/openpencil/scripts/launch-mcp +22 -0
  29. package/plugins/openpencil/scripts/launch-mcp.cmd +21 -0
  30. package/plugins/openpencil/scripts/mcp-bridge.mjs +70 -0
  31. package/plugins/openpencil/scripts/runtime-install.mjs +128 -0
  32. package/plugins/openpencil/scripts/transport.mjs +138 -0
  33. package/plugins/openpencil/skills/openpencil-design/SKILL.md +125 -0
  34. package/plugins/openpencil/skills/openpencil-design/references/codegen.md +34 -0
  35. package/plugins/openpencil/skills/openpencil-design/references/images.md +54 -0
  36. package/plugins/openpencil/skills/openpencil-design/references/node-schema.md +208 -0
  37. package/plugins/openpencil/skills/openpencil-setup/SKILL.md +59 -0
  38. package/plugins/openpencil/ui/app.html +226 -0
  39. package/plugins/openpencil/ui/codegen.js +80 -0
  40. package/plugins/openpencil/ui/panel.css +311 -0
  41. package/plugins/openpencil/ui/panel.html +11 -0
  42. package/plugins/openpencil/ui/panel.js +219 -0
  43. package/plugins/openpencil/ui/selection.js +19 -0
  44. package/scripts/build-editor-runtime.mjs +35 -0
  45. package/scripts/canvas.mjs +75 -0
  46. package/scripts/check-package.mjs +81 -0
  47. package/scripts/check-release-version.mjs +53 -0
  48. package/scripts/collab-bootstrap-config.mjs +66 -0
  49. package/scripts/configure-runtime.mjs +15 -0
  50. package/scripts/host-config.mjs +352 -0
  51. package/scripts/managed-handshake.mjs +23 -0
  52. package/scripts/node-registration.mjs +17 -0
  53. package/scripts/pack-package.mjs +41 -0
  54. package/scripts/pack-plugin.mjs +166 -0
  55. package/scripts/platforms.mjs +84 -0
  56. package/scripts/plugin-host-check.mjs +174 -0
  57. package/scripts/publish-release.mjs +294 -0
  58. package/scripts/registry-convergence.mjs +40 -0
  59. package/scripts/setup.mjs +147 -0
  60. package/scripts/stage-editor-runtime.mjs +189 -0
  61. package/scripts/sync-platform-versions.mjs +63 -0
  62. package/scripts/verify-platform-packages.mjs +270 -0
  63. package/scripts/verify-selective-install.mjs +219 -0
@@ -0,0 +1,48 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+
3
+ // Match the Rust schema's structural image visitor. Never rewrite free-form
4
+ // user state, text, action parameters or variables that resemble image refs.
5
+ export function liveDocument(disk) {
6
+ const copy = structuredClone(disk);
7
+ const table = copy.images || {};
8
+ delete copy.images;
9
+ delete copy.imageThumbs;
10
+ delete copy.editorMeta;
11
+ const resolve = value => typeof value === 'string' && value.startsWith('op-image:')
12
+ && Object.hasOwn(table, value.slice(9)) ? table[value.slice(9)] : value;
13
+ const fills = list => {
14
+ if (Array.isArray(list)) for (const fill of list) if (fill?.type === 'image') fill.url = resolve(fill.url);
15
+ };
16
+ const style = node => { fills(node.fill); fills(node.stroke?.fill); };
17
+ const stack = [...(copy.children || []), ...(copy.pages || [])];
18
+ while (stack.length) {
19
+ const node = stack.pop();
20
+ if (!node || typeof node !== 'object') continue;
21
+ if (node.type === 'image') node.src = resolve(node.src);
22
+ style(node);
23
+ for (const override of Object.values(node.states || {})) if (override && typeof override === 'object') style(override);
24
+ if (Array.isArray(node.children)) stack.push(...node.children);
25
+ }
26
+ return copy;
27
+ }
28
+
29
+ export function snapshotMatches(disk, live) {
30
+ const meta = disk.editorMeta;
31
+ return isDeepStrictEqual(liveDocument(disk), liveDocument(live.document))
32
+ && (!meta || (
33
+ meta.activePageIndex === live.activePageIndex
34
+ && meta.preserveAuthoredGeometry === live.preserveAuthoredGeometry
35
+ && (meta.scenario ?? null) === (live.scenario ?? null)
36
+ ));
37
+ }
38
+
39
+ export function diskDocument(live) {
40
+ return {
41
+ ...live.document,
42
+ editorMeta: {
43
+ activePageIndex: live.activePageIndex,
44
+ preserveAuthoredGeometry: live.preserveAuthoredGeometry,
45
+ ...(live.scenario != null ? { scenario: live.scenario } : {}),
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Atomic OpenPencil editor runtime resolution for Qoder.
3
+ *
4
+ * A runtime is always selected as one complete package root. The daemon and
5
+ * both web asset directories are never assembled from unrelated installs.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import { chmodSync, existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
9
+ import { chmod, lstat, readFile, realpath } from 'node:fs/promises';
10
+ import { createRequire } from 'node:module';
11
+ import { homedir } from 'node:os';
12
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ export const EDITOR_RUNTIME_SCHEMA_VERSION = 1;
16
+
17
+ const requireFromPlugin = createRequire(import.meta.url);
18
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/;
19
+ const REVISION_PATTERN = /^[a-f0-9]{40,64}$/;
20
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
21
+ const SAFE_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
22
+
23
+ export const stateRoot = () => process.env.OPENPENCIL_QODER_STATE_DIR || join(homedir(), '.qoder-openpencil');
24
+ export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
25
+
26
+ export class EditorRuntimeUnavailableError extends Error {
27
+ constructor(code, message, diagnostics = [], options) {
28
+ super(message, options);
29
+ this.name = 'EditorRuntimeUnavailableError';
30
+ this.code = code;
31
+ this.diagnostics = diagnostics;
32
+ }
33
+ }
34
+
35
+ export function assertSupportedLibc(platform, glibc) {
36
+ if (!platform.startsWith('linux-')) return;
37
+ const minor = platform === 'linux-arm64' ? 39 : 35;
38
+ const [major, current] = String(glibc || '').split('.').map(Number);
39
+ if (!major || major < 2 || (major === 2 && current < minor)) {
40
+ throw new Error(`Published ${platform} runtimes require glibc 2.${minor}+; musl/Alpine and older systems need a custom runtime.`);
41
+ }
42
+ }
43
+
44
+ export function editorRuntimePlatformKey(platform = process.platform, arch = process.arch) {
45
+ return `${platform}-${arch}`;
46
+ }
47
+
48
+ export function editorRuntimeRequiredFiles(binaryName) {
49
+ return Object.freeze([
50
+ `bin/${binaryName}`,
51
+ 'bin/web-bundle/op_host_web.js',
52
+ 'bin/web-bundle/op_host_web_bg.wasm',
53
+ 'bin/web-bundle/canvaskit/canvaskit.js',
54
+ 'bin/web-bundle/canvaskit/canvaskit.wasm',
55
+ ]);
56
+ }
57
+
58
+ export function defaultPackageRoot() {
59
+ return resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
60
+ }
61
+
62
+ export function hasPackageCatalog(projectRoot = defaultPackageRoot()) {
63
+ const path = join(resolve(projectRoot), 'platforms.json');
64
+ try {
65
+ return existsSync(path) && statSync(path).isFile();
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ function recordFrom(value) {
72
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
73
+ }
74
+
75
+ function nonEmptyString(value) {
76
+ return typeof value === 'string' && value.trim() === value && value.length > 0;
77
+ }
78
+
79
+ function catalogError(message) {
80
+ throw new EditorRuntimeUnavailableError('invalid-catalog', `Invalid OpenPencil runtime catalog: ${message}`);
81
+ }
82
+
83
+ /** Parse and validate platforms.json without performing any I/O. */
84
+ export function parseEditorRuntimeCatalog(value) {
85
+ const catalog = recordFrom(value);
86
+ if (catalog === undefined) catalogError('root must be an object');
87
+ if (catalog.schemaVersion !== EDITOR_RUNTIME_SCHEMA_VERSION) {
88
+ catalogError(`schemaVersion must be ${EDITOR_RUNTIME_SCHEMA_VERSION}`);
89
+ }
90
+ const openPencil = recordFrom(catalog.openPencil);
91
+ if (openPencil === undefined) catalogError('openPencil must be an object');
92
+ if (!nonEmptyString(openPencil.version) || !VERSION_PATTERN.test(openPencil.version)) {
93
+ catalogError('openPencil.version must be a semantic version');
94
+ }
95
+ if (!nonEmptyString(openPencil.revision) || !REVISION_PATTERN.test(openPencil.revision)) {
96
+ catalogError('openPencil.revision must be a full hexadecimal Git revision');
97
+ }
98
+ if (!Array.isArray(catalog.platforms) || catalog.platforms.length === 0) {
99
+ catalogError('platforms must be a non-empty array');
100
+ }
101
+ const platforms = [];
102
+ const ids = new Set();
103
+ const selectors = new Set();
104
+ const packageNames = new Set();
105
+ for (const [index, rawPlatform] of catalog.platforms.entries()) {
106
+ const entry = recordFrom(rawPlatform);
107
+ if (entry === undefined) catalogError(`platforms[${index}] must be an object`);
108
+ for (const field of ['id', 'os', 'cpu', 'rustTarget', 'runner', 'packageName', 'binaryName']) {
109
+ if (!nonEmptyString(entry[field])) catalogError(`platforms[${index}].${field} must be a non-empty string`);
110
+ }
111
+ if (!SAFE_ID_PATTERN.test(entry.id)) catalogError(`platforms[${index}].id is invalid`);
112
+ if (!SAFE_ID_PATTERN.test(entry.os)) catalogError(`platforms[${index}].os is invalid`);
113
+ if (!SAFE_ID_PATTERN.test(entry.cpu)) catalogError(`platforms[${index}].cpu is invalid`);
114
+ if (entry.libc !== undefined && !nonEmptyString(entry.libc)) {
115
+ catalogError(`platforms[${index}].libc must be a non-empty string when present`);
116
+ }
117
+ const selector = `${entry.os}-${entry.cpu}`;
118
+ if (entry.id !== selector) catalogError(`platforms[${index}].id must equal ${selector}`);
119
+ const expectedPackageName = `@zseven-w/qoder-openpencil-${entry.id}`;
120
+ if (entry.packageName !== expectedPackageName) {
121
+ catalogError(`platforms[${index}].packageName must equal ${expectedPackageName}`);
122
+ }
123
+ const expectedBinaryName = entry.os === 'win32' ? 'op-host-web-server.exe' : 'op-host-web-server';
124
+ if (entry.binaryName !== expectedBinaryName) {
125
+ catalogError(`platforms[${index}].binaryName must equal ${expectedBinaryName}`);
126
+ }
127
+ if (ids.has(entry.id)) catalogError(`duplicate platform id ${entry.id}`);
128
+ if (selectors.has(selector)) catalogError(`duplicate platform selector ${selector}`);
129
+ if (packageNames.has(entry.packageName)) catalogError(`duplicate packageName ${entry.packageName}`);
130
+ ids.add(entry.id);
131
+ selectors.add(selector);
132
+ packageNames.add(entry.packageName);
133
+ platforms.push(Object.freeze({ ...entry }));
134
+ }
135
+ return Object.freeze({
136
+ schemaVersion: EDITOR_RUNTIME_SCHEMA_VERSION,
137
+ openPencil: Object.freeze({ version: openPencil.version, revision: openPencil.revision }),
138
+ platforms: Object.freeze(platforms),
139
+ });
140
+ }
141
+
142
+ function safeManifestPath(path) {
143
+ if (!nonEmptyString(path) || isAbsolute(path) || path.includes('\\')) return false;
144
+ const segments = path.split('/');
145
+ return segments.every(segment => segment !== '' && segment !== '.' && segment !== '..');
146
+ }
147
+
148
+ /** Parse one openpencil-runtime.json and bind it to its expected release. */
149
+ export function parseEditorRuntimeManifest(value, expected) {
150
+ const fail = message => {
151
+ throw new EditorRuntimeUnavailableError('invalid-runtime', `Invalid OpenPencil runtime manifest: ${message}`);
152
+ };
153
+ const manifest = recordFrom(value);
154
+ if (manifest === undefined) fail('root must be an object');
155
+ if (manifest.schemaVersion !== EDITOR_RUNTIME_SCHEMA_VERSION) {
156
+ fail(`schemaVersion must be ${EDITOR_RUNTIME_SCHEMA_VERSION}`);
157
+ }
158
+ if (manifest.platform !== expected.platform) fail(`platform must equal ${expected.platform}`);
159
+ if (expected.packageName !== undefined && manifest.packageName !== expected.packageName) {
160
+ fail(`packageName must equal ${expected.packageName}`);
161
+ }
162
+ if (manifest.openPencilVersion !== expected.openPencilVersion) {
163
+ fail(`openPencilVersion must equal ${expected.openPencilVersion}`);
164
+ }
165
+ if (manifest.openPencilRevision !== expected.openPencilRevision) {
166
+ fail(`openPencilRevision must equal ${expected.openPencilRevision}`);
167
+ }
168
+ const files = recordFrom(manifest.files);
169
+ if (files === undefined) fail('files must be an object');
170
+ for (const [path, digest] of Object.entries(files)) {
171
+ if (!safeManifestPath(path)) fail(`files contains unsafe path ${JSON.stringify(path)}`);
172
+ if (typeof digest !== 'string' || !SHA256_PATTERN.test(digest)) {
173
+ fail(`files[${JSON.stringify(path)}] must be a lowercase SHA-256 digest`);
174
+ }
175
+ }
176
+ return Object.freeze({
177
+ schemaVersion: EDITOR_RUNTIME_SCHEMA_VERSION,
178
+ platform: manifest.platform,
179
+ packageName: manifest.packageName,
180
+ openPencilVersion: manifest.openPencilVersion,
181
+ openPencilRevision: manifest.openPencilRevision,
182
+ files: Object.freeze({ ...files }),
183
+ });
184
+ }
185
+
186
+ function readJsonSync(path, io, kind) {
187
+ let bytes;
188
+ try {
189
+ bytes = io.readFile(path);
190
+ } catch (error) {
191
+ throw new EditorRuntimeUnavailableError(
192
+ kind === 'catalog' ? 'catalog-unavailable' : 'invalid-runtime',
193
+ `Unable to read OpenPencil ${kind} at ${path}`,
194
+ [error instanceof Error ? error.message : String(error)],
195
+ { cause: error },
196
+ );
197
+ }
198
+ try {
199
+ return JSON.parse(bytes.toString('utf8'));
200
+ } catch (error) {
201
+ throw new EditorRuntimeUnavailableError(
202
+ kind === 'catalog' ? 'invalid-catalog' : 'invalid-runtime',
203
+ `OpenPencil ${kind} at ${path} is not valid JSON`,
204
+ [error instanceof Error ? error.message : String(error)],
205
+ { cause: error },
206
+ );
207
+ }
208
+ }
209
+
210
+ function isRegularFileSync(path, io) {
211
+ try {
212
+ const info = io.lstat(path);
213
+ return info.isFile() && (!info.isSymbolicLink || !info.isSymbolicLink());
214
+ } catch {
215
+ return false;
216
+ }
217
+ }
218
+
219
+ function isDirectorySync(path, io) {
220
+ try {
221
+ return io.stat(path).isDirectory();
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+
227
+ function validateCatalogRuntimeRoot(rawRoot, source, expected, io) {
228
+ let root;
229
+ try {
230
+ root = io.realpath(rawRoot);
231
+ } catch (error) {
232
+ throw new EditorRuntimeUnavailableError(
233
+ 'invalid-runtime',
234
+ `OpenPencil ${source} runtime root does not exist: ${rawRoot}`,
235
+ [error instanceof Error ? error.message : String(error)],
236
+ { cause: error },
237
+ );
238
+ }
239
+ const manifestPath = join(root, 'openpencil-runtime.json');
240
+ if (!isRegularFileSync(manifestPath, io)) {
241
+ throw new EditorRuntimeUnavailableError('invalid-runtime', `OpenPencil ${source} runtime is missing ${manifestPath}`);
242
+ }
243
+ let manifest;
244
+ try {
245
+ manifest = parseEditorRuntimeManifest(readJsonSync(manifestPath, io, 'runtime manifest'), {
246
+ platform: expected.platform.id,
247
+ packageName: expected.platform.packageName,
248
+ openPencilVersion: expected.version,
249
+ openPencilRevision: expected.revision,
250
+ });
251
+ } catch (error) {
252
+ if (error instanceof EditorRuntimeUnavailableError) {
253
+ throw new EditorRuntimeUnavailableError('invalid-runtime', `${error.message} (${manifestPath})`, error.diagnostics, { cause: error });
254
+ }
255
+ throw error;
256
+ }
257
+ const webBundleDir = join(root, 'bin', 'web-bundle');
258
+ const canvasKitDir = join(webBundleDir, 'canvaskit');
259
+ if (!isDirectorySync(webBundleDir, io) || !isDirectorySync(canvasKitDir, io)) {
260
+ throw new EditorRuntimeUnavailableError(
261
+ 'invalid-runtime',
262
+ `OpenPencil runtime under ${root} must contain bin/web-bundle with its canvaskit subdirectory`,
263
+ );
264
+ }
265
+ for (const relativePath of editorRuntimeRequiredFiles(expected.platform.binaryName)) {
266
+ if (manifest.files[relativePath] === undefined) {
267
+ throw new EditorRuntimeUnavailableError(
268
+ 'invalid-runtime',
269
+ `OpenPencil runtime manifest ${manifestPath} is missing SHA-256 for ${relativePath}`,
270
+ );
271
+ }
272
+ }
273
+ for (const [relativePath, expectedDigest] of Object.entries(manifest.files)) {
274
+ const absolutePath = join(root, ...relativePath.split('/'));
275
+ if (!isRegularFileSync(absolutePath, io)) {
276
+ throw new EditorRuntimeUnavailableError('invalid-runtime', `OpenPencil runtime file is missing or not regular: ${absolutePath}`);
277
+ }
278
+ const resolvedPath = io.realpath(absolutePath);
279
+ if (relative(root, resolvedPath).startsWith('..')) {
280
+ throw new EditorRuntimeUnavailableError('invalid-runtime', `OpenPencil runtime file escapes package root: ${relativePath}`);
281
+ }
282
+ const actualDigest = sha256(io.readFile(absolutePath));
283
+ if (actualDigest !== expectedDigest) {
284
+ throw new EditorRuntimeUnavailableError(
285
+ 'invalid-runtime',
286
+ `OpenPencil runtime SHA-256 mismatch for ${absolutePath}`,
287
+ [`expected ${expectedDigest}`, `actual ${actualDigest}`],
288
+ );
289
+ }
290
+ }
291
+ const binary = join(root, 'bin', expected.platform.binaryName);
292
+ if (expected.platform.os !== 'win32') {
293
+ try { io.chmod(binary, 0o755); } catch { /* Immutable stores remain usable when already +x. */ }
294
+ }
295
+ return Object.freeze({
296
+ binary,
297
+ webBundleDir,
298
+ canvasKitDir,
299
+ openPencilVersion: expected.version,
300
+ revision: expected.revision,
301
+ source,
302
+ });
303
+ }
304
+
305
+ function runtimeIo(options) {
306
+ return {
307
+ readFile: options.readFile ?? (path => readFileSync(path)),
308
+ stat: options.stat ?? (path => statSync(path)),
309
+ lstat: options.lstat ?? options.stat ?? (path => lstatSync(path)),
310
+ realpath: options.realpath ?? (options.stat ? (path => resolve(path)) : (path => realpathSync.native(path))),
311
+ chmod: options.chmod ?? ((path, mode) => chmodSync(path, mode)),
312
+ };
313
+ }
314
+
315
+ /** Resolve and fully verify one atomic editor runtime from npm optionalDependencies or staged npm/<platform>. */
316
+ export function resolveEditorRuntime(options = {}) {
317
+ const platformName = options.platform ?? process.platform;
318
+ const architecture = options.arch ?? process.arch;
319
+ const key = editorRuntimePlatformKey(platformName, architecture);
320
+ const env = options.env ?? process.env;
321
+ const projectRoot = options.projectRoot === undefined ? defaultPackageRoot() : resolve(options.projectRoot);
322
+ const io = runtimeIo(options);
323
+
324
+ const rawCatalog = options.catalog !== undefined
325
+ ? options.catalog
326
+ : readJsonSync(join(projectRoot, 'platforms.json'), io, 'catalog');
327
+ const catalog = parseEditorRuntimeCatalog(rawCatalog);
328
+ const platform = catalog.platforms.find(entry => entry.os === platformName && entry.cpu === architecture);
329
+ if (platform === undefined) {
330
+ throw new EditorRuntimeUnavailableError(
331
+ 'unsupported-platform',
332
+ `No OpenPencil editor runtime is published for ${key}`,
333
+ [`supported: ${catalog.platforms.map(entry => entry.id).join(', ')}`],
334
+ );
335
+ }
336
+ const expected = {
337
+ platform,
338
+ version: catalog.openPencil.version,
339
+ revision: catalog.openPencil.revision,
340
+ };
341
+
342
+ const explicitOverride = env.OPENPENCIL_EDITOR_RUNTIME_DIR?.trim();
343
+ if (explicitOverride) {
344
+ if (!isAbsolute(explicitOverride)) {
345
+ throw new EditorRuntimeUnavailableError(
346
+ 'invalid-override',
347
+ `OPENPENCIL_EDITOR_RUNTIME_DIR must be an absolute path: ${explicitOverride}`,
348
+ );
349
+ }
350
+ return validateCatalogRuntimeRoot(explicitOverride, 'override', expected, io);
351
+ }
352
+
353
+ const resolvePackageJson = options.resolvePackageJson ?? (specifier => requireFromPlugin.resolve(specifier));
354
+ let packageJson;
355
+ let packageResolutionDiagnostic;
356
+ try {
357
+ packageJson = resolvePackageJson(`${platform.packageName}/package.json`);
358
+ } catch (error) {
359
+ packageResolutionDiagnostic = error instanceof Error ? error.message : String(error);
360
+ }
361
+ const developmentRoot = join(projectRoot, 'npm', platform.id);
362
+ if (packageJson !== undefined && resolve(dirname(packageJson)) !== resolve(developmentRoot)) {
363
+ return validateCatalogRuntimeRoot(dirname(packageJson), 'optional-package', expected, io);
364
+ }
365
+
366
+ const developmentManifest = join(developmentRoot, 'openpencil-runtime.json');
367
+ if (isRegularFileSync(developmentManifest, io)) {
368
+ return validateCatalogRuntimeRoot(developmentRoot, 'development-package', expected, io);
369
+ }
370
+
371
+ throw new EditorRuntimeUnavailableError(
372
+ 'runtime-not-found',
373
+ `OpenPencil editor runtime ${platform.id} is unavailable`,
374
+ [
375
+ `optional package: ${platform.packageName}`,
376
+ `development runtime: ${developmentRoot}`,
377
+ ...(packageResolutionDiagnostic === undefined ? [] : [`package resolution: ${packageResolutionDiagnostic}`]),
378
+ ],
379
+ );
380
+ }
381
+
382
+ /** Optional form: throws on integrity/config errors, returns undefined only when absent or unsupported. */
383
+ export function tryResolveEditorRuntime(options = {}) {
384
+ try {
385
+ return resolveEditorRuntime(options);
386
+ } catch (error) {
387
+ if (error instanceof EditorRuntimeUnavailableError && (error.code === 'runtime-not-found' || error.code === 'unsupported-platform')) {
388
+ return undefined;
389
+ }
390
+ throw error;
391
+ }
392
+ }
393
+
394
+ /** Async validator for an explicit, custom, or configured runtime directory. */
395
+ export async function resolveRuntime(root, expected = {}) {
396
+ if (!root) {
397
+ root = process.env.OPENPENCIL_EDITOR_RUNTIME_DIR;
398
+ if (!root) {
399
+ try { root = JSON.parse(await readFile(join(stateRoot(), 'runtime.json'), 'utf8')).root; }
400
+ catch { /* Report one actionable error for missing or malformed configuration. */ }
401
+ }
402
+ }
403
+ if (typeof root !== 'string' || !isAbsolute(root)) {
404
+ throw new Error('Configure a complete Rust editor runtime with qoder-openpencil setup or qoder-openpencil configure-runtime /absolute/runtime/root.');
405
+ }
406
+ root = await realpath(root);
407
+ const manifest = JSON.parse(await readFile(join(root, 'openpencil-runtime.json'), 'utf8'));
408
+ const currentPlatform = `${process.platform}-${process.arch}`;
409
+ if (
410
+ manifest.schemaVersion !== EDITOR_RUNTIME_SCHEMA_VERSION
411
+ || manifest.platform !== currentPlatform
412
+ || !VERSION_PATTERN.test(manifest.openPencilVersion || '')
413
+ || !recordFrom(manifest.files)
414
+ ) {
415
+ throw new Error('Editor runtime manifest or platform is incompatible.');
416
+ }
417
+ if (expected.packageName !== undefined && manifest.packageName !== expected.packageName) {
418
+ throw new Error('Editor runtime package does not match the configured release. Rerun qoder-openpencil setup and reconnect the plugin.');
419
+ }
420
+ if (expected.openPencilVersion !== undefined && manifest.openPencilVersion !== expected.openPencilVersion) {
421
+ throw new Error('Editor runtime version does not match the configured release. Rerun qoder-openpencil setup and reconnect the plugin.');
422
+ }
423
+ if (expected.openPencilRevision !== undefined && manifest.openPencilRevision !== expected.openPencilRevision) {
424
+ throw new Error('Editor runtime revision does not match the configured release. Rerun qoder-openpencil setup and reconnect the plugin.');
425
+ }
426
+ const binaryName = process.platform === 'win32' ? 'op-host-web-server.exe' : 'op-host-web-server';
427
+ const required = editorRuntimeRequiredFiles(binaryName);
428
+ // Never mix a daemon and web bundle from different releases or trust a partial package.
429
+ for (const name of required) if (!manifest.files[name]) throw new Error(`Runtime is incomplete: ${name}`);
430
+ for (const [name, hash] of Object.entries(manifest.files)) {
431
+ const path = resolve(root, name);
432
+ if (!safeManifestPath(name) || relative(root, path).startsWith('..') || !SHA256_PATTERN.test(hash)) {
433
+ throw new Error('Invalid editor runtime file manifest.');
434
+ }
435
+ const stat = await lstat(path);
436
+ if (relative(root, await realpath(path)).startsWith('..') || !stat.isFile() || stat.isSymbolicLink() || sha256(await readFile(path)) !== hash) {
437
+ throw new Error(`Editor runtime integrity check failed: ${name}`);
438
+ }
439
+ }
440
+ const binary = join(root, 'bin', binaryName);
441
+ if (process.platform !== 'win32') {
442
+ try { await chmod(binary, 0o755); } catch { /* Immutable package stores may already be +x. */ }
443
+ }
444
+ return {
445
+ root,
446
+ version: manifest.openPencilVersion,
447
+ revision: manifest.openPencilRevision,
448
+ packageName: manifest.packageName,
449
+ binary,
450
+ webBundle: join(root, 'bin/web-bundle'),
451
+ canvasKit: join(root, 'bin/web-bundle/canvaskit'),
452
+ };
453
+ }