@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,352 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { chmod, copyFile, lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const SERVER_NAME = 'openpencil';
9
+ export const PLUGIN_NAME = 'openpencil';
10
+ export const PLUGIN_ID = `${PLUGIN_NAME}@local`;
11
+ export const SKILL_NAMES = Object.freeze(['openpencil-design', 'openpencil-setup']);
12
+ const OWNERSHIP_MARKER = '.openpencil-qoder-managed.json';
13
+ const defaultPluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../plugins/openpencil');
14
+
15
+ /**
16
+ * Resolve Qoder's configuration directory following Qoder Desktop's documented order:
17
+ * 1. Explicit configDir argument
18
+ * 2. QODER_CONFIG_DIR / QODERCN_CONFIG_DIR
19
+ * 3. QODER_CLI_HOME + QODER_CONFIG_DIR_NAME (or QODERCN equivalents)
20
+ * 4. Existing ~/.qoder, then ~/.qoder-cn, defaulting to ~/.qoder
21
+ */
22
+ export function resolveQoderConfigDir({ configDir, env = process.env, home = homedir() } = {}) {
23
+ if (configDir) return resolve(configDir);
24
+ const direct = env.QODER_CONFIG_DIR?.trim() || env.QODERCN_CONFIG_DIR?.trim();
25
+ if (direct) return resolve(direct);
26
+ if (env.QODER_CLI_HOME?.trim()) {
27
+ return join(resolve(env.QODER_CLI_HOME.trim()), env.QODER_CONFIG_DIR_NAME?.trim() || '.qoder');
28
+ }
29
+ if (env.QODERCN_CLI_HOME?.trim()) {
30
+ return join(resolve(env.QODERCN_CLI_HOME.trim()), env.QODERCN_CONFIG_DIR_NAME?.trim() || '.qoder-cn');
31
+ }
32
+ for (const candidate of ['.qoder', '.qoder-cn']) {
33
+ const dir = join(home, candidate);
34
+ if (existsSync(dir)) return dir;
35
+ }
36
+ return join(home, '.qoder');
37
+ }
38
+
39
+ export function launcherPathForPlugin(pluginRoot = defaultPluginRoot, platform = process.platform) {
40
+ return join(resolve(pluginRoot), 'scripts', platform === 'win32' ? 'launch-mcp.cmd' : 'launch-mcp');
41
+ }
42
+
43
+ export function buildQoderMcpEntry({ pluginRoot = defaultPluginRoot, platform = process.platform, env } = {}) {
44
+ const root = resolve(pluginRoot);
45
+ const entry = {
46
+ type: 'stdio',
47
+ command: launcherPathForPlugin(root, platform),
48
+ args: [],
49
+ cwd: root,
50
+ };
51
+ if (env && Object.keys(env).length > 0) entry.env = env;
52
+ return entry;
53
+ }
54
+
55
+ export function renderQoderConnectorConfig(options = {}) {
56
+ return {
57
+ mcpServers: {
58
+ [SERVER_NAME]: buildQoderMcpEntry(options),
59
+ },
60
+ };
61
+ }
62
+
63
+ async function readJsonObject(path) {
64
+ let raw;
65
+ try {
66
+ raw = await readFile(path, 'utf8');
67
+ } catch (error) {
68
+ if (error.code === 'ENOENT') return {};
69
+ throw error;
70
+ }
71
+ if (!raw.trim()) return {};
72
+ const parsed = JSON.parse(raw);
73
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
74
+ throw new Error(`Expected a JSON object in ${path}.`);
75
+ }
76
+ return parsed;
77
+ }
78
+
79
+ async function writeJsonAtomic(path, value) {
80
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
81
+ const temp = join(dirname(path), `.qoder-${randomUUID()}.tmp`);
82
+ try {
83
+ await writeFile(temp, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
84
+ await rename(temp, path);
85
+ } finally {
86
+ await rm(temp, { force: true });
87
+ }
88
+ }
89
+
90
+ async function copyTree(sourceDir, destinationDir) {
91
+ await mkdir(destinationDir, { recursive: true, mode: 0o755 });
92
+ const entries = await readdir(sourceDir, { withFileTypes: true });
93
+ entries.sort((left, right) => left.name.localeCompare(right.name, 'en'));
94
+ for (const entry of entries) {
95
+ if (entry.name === '.DS_Store' || entry.name === 'Thumbs.db') continue;
96
+ const src = join(sourceDir, entry.name);
97
+ const dst = join(destinationDir, entry.name);
98
+ const info = await lstat(src);
99
+ if (info.isSymbolicLink()) throw new Error(`Plugin bundle must not contain symlinks: ${src}`);
100
+ if (info.isDirectory()) {
101
+ await copyTree(src, dst);
102
+ } else if (info.isFile()) {
103
+ await copyFile(src, dst);
104
+ if (process.platform !== 'win32' && (info.mode & 0o111) !== 0) {
105
+ await chmod(dst, info.mode & 0o777);
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Install the plugin into Qoder's canonical versioned local cache, register
113
+ * openpencil@local in plugins/installed_plugins_v2.json, and enable it in
114
+ * settings.json without clobbering unrelated plugins or settings.
115
+ */
116
+ export async function installQoderPlugin({
117
+ configDir,
118
+ pluginRoot = defaultPluginRoot,
119
+ env = process.env,
120
+ home = homedir(),
121
+ version = '0.1.0',
122
+ } = {}) {
123
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
124
+ const installPath = join(rootDir, 'plugins', 'cache', 'local', PLUGIN_NAME, version);
125
+ const pluginsRegistryPath = join(rootDir, 'plugins', 'installed_plugins_v2.json');
126
+ const settingsPath = join(rootDir, 'settings.json');
127
+
128
+ if (existsSync(installPath)) {
129
+ const markerPath = join(installPath, OWNERSHIP_MARKER);
130
+ if (!existsSync(markerPath)) {
131
+ throw new Error(`Refusing to overwrite existing unmanaged plugin directory: ${installPath}`);
132
+ }
133
+ await rm(installPath, { recursive: true, force: true });
134
+ }
135
+ await copyTree(resolve(pluginRoot), installPath);
136
+ if (process.platform !== 'win32') {
137
+ await chmod(join(installPath, 'scripts', 'launch-mcp'), 0o755);
138
+ }
139
+ await writeFile(
140
+ join(installPath, OWNERSHIP_MARKER),
141
+ JSON.stringify({ managedBy: '@zseven-w/qoder-openpencil', pluginId: PLUGIN_ID, version }, null, 2) + '\n',
142
+ { mode: 0o644 },
143
+ );
144
+
145
+ const registry = await readJsonObject(pluginsRegistryPath);
146
+ const existingPlugins = registry.plugins && typeof registry.plugins === 'object' && !Array.isArray(registry.plugins)
147
+ ? { ...registry.plugins }
148
+ : {};
149
+ const updatedRegistry = {
150
+ ...registry,
151
+ version: 2,
152
+ plugins: {
153
+ ...existingPlugins,
154
+ [PLUGIN_ID]: [{ scope: 'user', installPath, version }],
155
+ },
156
+ };
157
+ await writeJsonAtomic(pluginsRegistryPath, updatedRegistry);
158
+
159
+ const settings = await readJsonObject(settingsPath);
160
+ const existingEnabled = settings.enabledPlugins && typeof settings.enabledPlugins === 'object' && !Array.isArray(settings.enabledPlugins)
161
+ ? { ...settings.enabledPlugins }
162
+ : {};
163
+ const updatedSettings = {
164
+ ...settings,
165
+ enabledPlugins: {
166
+ ...existingEnabled,
167
+ [PLUGIN_ID]: true,
168
+ },
169
+ };
170
+ await writeJsonAtomic(settingsPath, updatedSettings);
171
+
172
+ return {
173
+ configDir: rootDir,
174
+ pluginId: PLUGIN_ID,
175
+ installPath,
176
+ pluginsRegistryPath,
177
+ settingsPath,
178
+ version,
179
+ };
180
+ }
181
+
182
+ export async function uninstallQoderPlugin({ configDir, env = process.env, home = homedir() } = {}) {
183
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
184
+ const pluginsRegistryPath = join(rootDir, 'plugins', 'installed_plugins_v2.json');
185
+ const settingsPath = join(rootDir, 'settings.json');
186
+ const removedPaths = [];
187
+ let registryRemoved = false;
188
+ let settingRemoved = false;
189
+
190
+ if (existsSync(pluginsRegistryPath)) {
191
+ const registry = await readJsonObject(pluginsRegistryPath);
192
+ if (registry.plugins && typeof registry.plugins === 'object' && Object.hasOwn(registry.plugins, PLUGIN_ID)) {
193
+ const records = Array.isArray(registry.plugins[PLUGIN_ID]) ? registry.plugins[PLUGIN_ID] : [];
194
+ for (const record of records) {
195
+ if (typeof record?.installPath === 'string' && existsSync(join(record.installPath, OWNERSHIP_MARKER))) {
196
+ const info = await lstat(record.installPath);
197
+ if (info.isDirectory() && !info.isSymbolicLink()) {
198
+ await rm(record.installPath, { recursive: true, force: true });
199
+ removedPaths.push(record.installPath);
200
+ }
201
+ }
202
+ }
203
+ const nextPlugins = { ...registry.plugins };
204
+ delete nextPlugins[PLUGIN_ID];
205
+ await writeJsonAtomic(pluginsRegistryPath, { ...registry, version: registry.version ?? 2, plugins: nextPlugins });
206
+ registryRemoved = true;
207
+ }
208
+ }
209
+
210
+ if (existsSync(settingsPath)) {
211
+ const settings = await readJsonObject(settingsPath);
212
+ if (settings.enabledPlugins && typeof settings.enabledPlugins === 'object' && Object.hasOwn(settings.enabledPlugins, PLUGIN_ID)) {
213
+ const nextEnabled = { ...settings.enabledPlugins };
214
+ delete nextEnabled[PLUGIN_ID];
215
+ await writeJsonAtomic(settingsPath, { ...settings, enabledPlugins: nextEnabled });
216
+ settingRemoved = true;
217
+ }
218
+ }
219
+
220
+ return { configDir: rootDir, pluginId: PLUGIN_ID, registryRemoved, settingRemoved, removedPaths };
221
+ }
222
+
223
+ /** Optional global settings.json mcpServers registration for Qoder IDE / CLI mode. */
224
+ export async function installQoderMcpSettings({
225
+ configDir,
226
+ pluginRoot = defaultPluginRoot,
227
+ platform = process.platform,
228
+ env = process.env,
229
+ home = homedir(),
230
+ serverEnv,
231
+ } = {}) {
232
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
233
+ const settingsPath = join(rootDir, 'settings.json');
234
+ const current = await readJsonObject(settingsPath);
235
+ const existingServers = current.mcpServers && typeof current.mcpServers === 'object' && !Array.isArray(current.mcpServers)
236
+ ? { ...current.mcpServers }
237
+ : {};
238
+ const entry = buildQoderMcpEntry({ pluginRoot, platform, env: serverEnv });
239
+ const updated = {
240
+ ...current,
241
+ mcpServers: {
242
+ ...existingServers,
243
+ [SERVER_NAME]: entry,
244
+ },
245
+ };
246
+ await writeJsonAtomic(settingsPath, updated);
247
+ return { configDir: rootDir, settingsPath, serverName: SERVER_NAME, entry };
248
+ }
249
+
250
+ export async function uninstallQoderMcpSettings({ configDir, env = process.env, home = homedir() } = {}) {
251
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
252
+ const settingsPath = join(rootDir, 'settings.json');
253
+ if (!existsSync(settingsPath)) return { configDir: rootDir, settingsPath, removed: false };
254
+ const current = await readJsonObject(settingsPath);
255
+ if (!current.mcpServers || typeof current.mcpServers !== 'object' || !Object.hasOwn(current.mcpServers, SERVER_NAME)) {
256
+ return { configDir: rootDir, settingsPath, removed: false };
257
+ }
258
+ const nextServers = { ...current.mcpServers };
259
+ delete nextServers[SERVER_NAME];
260
+ await writeJsonAtomic(settingsPath, { ...current, mcpServers: nextServers });
261
+ return { configDir: rootDir, settingsPath, removed: true };
262
+ }
263
+
264
+ export async function installQoderSkills({
265
+ configDir,
266
+ pluginRoot = defaultPluginRoot,
267
+ env = process.env,
268
+ home = homedir(),
269
+ version = '0.1.0',
270
+ } = {}) {
271
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
272
+ const skillsDir = join(rootDir, 'skills');
273
+ await mkdir(skillsDir, { recursive: true, mode: 0o755 });
274
+ const installed = [];
275
+ for (const skillName of SKILL_NAMES) {
276
+ const source = join(resolve(pluginRoot), 'skills', skillName);
277
+ const target = join(skillsDir, skillName);
278
+ if (existsSync(target)) {
279
+ const markerPath = join(target, OWNERSHIP_MARKER);
280
+ if (!existsSync(markerPath)) {
281
+ throw new Error(`Refusing to overwrite existing unmanaged skill directory: ${target}`);
282
+ }
283
+ await rm(target, { recursive: true, force: true });
284
+ }
285
+ await copyTree(source, target);
286
+ await writeFile(
287
+ join(target, OWNERSHIP_MARKER),
288
+ JSON.stringify({ managedBy: '@zseven-w/qoder-openpencil', skill: skillName, version }, null, 2) + '\n',
289
+ { mode: 0o644 },
290
+ );
291
+ installed.push({ name: skillName, path: target });
292
+ }
293
+ return { configDir: rootDir, skillsDir, installed };
294
+ }
295
+
296
+ export async function uninstallQoderSkills({ configDir, env = process.env, home = homedir() } = {}) {
297
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
298
+ const skillsDir = join(rootDir, 'skills');
299
+ const removed = [];
300
+ for (const skillName of SKILL_NAMES) {
301
+ const target = join(skillsDir, skillName);
302
+ const markerPath = join(target, OWNERSHIP_MARKER);
303
+ if (!existsSync(target) || !existsSync(markerPath)) continue;
304
+ const info = await lstat(target);
305
+ if (!info.isDirectory() || info.isSymbolicLink()) continue;
306
+ await rm(target, { recursive: true, force: true });
307
+ removed.push(skillName);
308
+ }
309
+ return { configDir: rootDir, skillsDir, removed };
310
+ }
311
+
312
+ export async function inspectQoderRegistration({ configDir, env = process.env, home = homedir() } = {}) {
313
+ const rootDir = resolveQoderConfigDir({ configDir, env, home });
314
+ const pluginsRegistryPath = join(rootDir, 'plugins', 'installed_plugins_v2.json');
315
+ const settingsPath = join(rootDir, 'settings.json');
316
+ const skillsDir = join(rootDir, 'skills');
317
+
318
+ let pluginRecord = null;
319
+ if (existsSync(pluginsRegistryPath)) {
320
+ const registry = await readJsonObject(pluginsRegistryPath);
321
+ const records = registry.plugins?.[PLUGIN_ID];
322
+ if (Array.isArray(records) && records.length > 0) pluginRecord = records[0];
323
+ }
324
+
325
+ let pluginEnabled = false;
326
+ let mcpEntry = null;
327
+ if (existsSync(settingsPath)) {
328
+ const settings = await readJsonObject(settingsPath);
329
+ pluginEnabled = settings.enabledPlugins?.[PLUGIN_ID] === true;
330
+ if (settings.mcpServers && typeof settings.mcpServers === 'object' && Object.hasOwn(settings.mcpServers, SERVER_NAME)) {
331
+ mcpEntry = settings.mcpServers[SERVER_NAME];
332
+ }
333
+ }
334
+
335
+ const skills = SKILL_NAMES.map(name => ({
336
+ name,
337
+ installed: existsSync(join(skillsDir, name, 'SKILL.md')),
338
+ managed: existsSync(join(skillsDir, name, OWNERSHIP_MARKER)),
339
+ }));
340
+
341
+ return {
342
+ configDir: rootDir,
343
+ pluginsRegistryPath,
344
+ settingsPath,
345
+ pluginRegistered: pluginRecord !== null,
346
+ pluginEnabled,
347
+ pluginRecord,
348
+ mcpSettingsRegistered: mcpEntry !== null,
349
+ mcpEntry,
350
+ skills,
351
+ };
352
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Parse a managed editor daemon handshake without ever echoing the raw line.
3
+ * The line contains a short-lived bearer token and must be treated as secret.
4
+ */
5
+ export function parseManagedHandshake(line, platformId) {
6
+ let handshake;
7
+ try {
8
+ handshake = JSON.parse(line);
9
+ } catch {
10
+ throw new Error(`${platformId}: invalid managed handshake JSON`);
11
+ }
12
+ if (
13
+ handshake === null
14
+ || typeof handshake !== 'object'
15
+ || Array.isArray(handshake)
16
+ || handshake.ok !== true
17
+ || !Number.isInteger(handshake.port)
18
+ || typeof handshake.token !== 'string'
19
+ ) {
20
+ throw new Error(`${platformId}: incomplete managed handshake`);
21
+ }
22
+ return handshake;
23
+ }
@@ -0,0 +1,17 @@
1
+ import { mkdir, writeFile, rename, rm } from 'node:fs/promises';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { stateRoot } from '../plugins/openpencil/scripts/editor-runtime.mjs';
5
+
6
+ // A fixed private location remains discoverable when GUI hosts strip terminal PATH.
7
+ export async function registerNode(state = stateRoot(), binary = process.execPath) {
8
+ if (!isAbsolute(binary) || /[\r\n\0]/.test(binary)) throw new Error('Invalid Node executable path.');
9
+ await mkdir(state, { recursive: true, mode: 0o700 });
10
+ const temporary = join(state, `.node-${randomUUID()}`);
11
+ try {
12
+ await writeFile(temporary, `${binary}\n`, { flag: 'wx', mode: 0o600 });
13
+ await rename(temporary, join(state, 'node-path'));
14
+ } finally {
15
+ await rm(temporary, { force: true });
16
+ }
17
+ }
@@ -0,0 +1,41 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { isAbsolute, join, resolve } from 'node:path';
6
+ import { argumentValue, projectRoot } from './platforms.mjs';
7
+
8
+ const packagePath = argumentValue('--package') ?? '.';
9
+ const requestedDestination = argumentValue('--destination') ?? 'artifacts';
10
+ const destination = isAbsolute(requestedDestination)
11
+ ? requestedDestination
12
+ : resolve(projectRoot, requestedDestination);
13
+ await mkdir(destination, { recursive: true });
14
+
15
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
16
+ const result = spawnSync(npm, [
17
+ 'pack',
18
+ '--json',
19
+ '--ignore-scripts',
20
+ '--pack-destination',
21
+ destination,
22
+ packagePath,
23
+ ], {
24
+ cwd: projectRoot,
25
+ encoding: 'utf8',
26
+ env: { ...process.env, npm_config_cache: join(tmpdir(), 'qoder-openpencil-npm-cache') },
27
+ shell: process.platform === 'win32',
28
+ });
29
+ if (result.status !== 0) throw new Error(result.stderr || result.stdout || `npm pack exited ${result.status}`);
30
+ const reports = JSON.parse(result.stdout);
31
+ if (!Array.isArray(reports) || reports.length !== 1) throw new Error('npm pack returned an unexpected report');
32
+ const report = reports[0];
33
+ const tarballPath = join(destination, report.filename);
34
+ const bytes = await readFile(tarballPath);
35
+ const integrity = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
36
+ const shasum = createHash('sha1').update(bytes).digest('hex');
37
+ if (report.integrity !== integrity || report.shasum !== shasum) {
38
+ throw new Error(`${report.name}@${report.version}: npm report integrity does not match ${tarballPath}`);
39
+ }
40
+ await writeFile(join(destination, report.filename + '.json'), JSON.stringify(report, null, 2) + '\n');
41
+ process.stdout.write(`${report.name}@${report.version} -> ${tarballPath}\n`);
@@ -0,0 +1,166 @@
1
+ import { deflateRawSync } from 'node:zlib';
2
+ import { lstat, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, relative, resolve, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
7
+ const defaultPluginRoot = join(packageRoot, 'plugins', 'openpencil');
8
+ const MAX_PLUGIN_ZIP_TOTAL_SIZE = 256 * 1024 * 1024;
9
+ const CRC_TABLE = (() => {
10
+ const table = new Uint32Array(256);
11
+ for (let i = 0; i < 256; i++) {
12
+ let c = i;
13
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
14
+ table[i] = c >>> 0;
15
+ }
16
+ return table;
17
+ })();
18
+
19
+ function crc32(buffer) {
20
+ let crc = 0xffffffff;
21
+ for (let i = 0; i < buffer.length; i++) {
22
+ crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8);
23
+ }
24
+ return (crc ^ 0xffffffff) >>> 0;
25
+ }
26
+
27
+ async function collectFiles(root) {
28
+ const output = [];
29
+ async function walk(dir) {
30
+ const entries = await readdir(dir, { withFileTypes: true });
31
+ entries.sort((left, right) => left.name.localeCompare(right.name, 'en'));
32
+ for (const entry of entries) {
33
+ if (entry.name === '.DS_Store' || entry.name === 'Thumbs.db' || entry.name === '__MACOSX') continue;
34
+ const abs = join(dir, entry.name);
35
+ const info = await lstat(abs);
36
+ if (info.isSymbolicLink()) throw new Error(`Plugin archive must not contain symbolic links: ${abs}`);
37
+ if (info.isDirectory()) await walk(abs);
38
+ else if (info.isFile()) output.push({ abs, rel: relative(root, abs).split(sep).join('/'), mode: info.mode });
39
+ }
40
+ }
41
+ await walk(root);
42
+ return output;
43
+ }
44
+
45
+ /**
46
+ * Build a standard ZIP 2.0 archive directly from plugins/openpencil/ with zero
47
+ * external dependencies, placing .qoder-plugin/plugin.json and .mcp.json directly
48
+ * at the ZIP root per Qoder's local plugin archive specification and preserving
49
+ * POSIX 0755 executable bits on scripts/launch-mcp.
50
+ */
51
+ export async function packQoderPlugin({
52
+ pluginRoot = defaultPluginRoot,
53
+ outputPath = join(packageRoot, 'dist', 'openpencil-qoder-plugin.zip'),
54
+ rootPrefix = '',
55
+ } = {}) {
56
+ const absPluginRoot = resolve(pluginRoot);
57
+ const absOutputPath = resolve(outputPath);
58
+ const files = await collectFiles(absPluginRoot);
59
+ const manifestEntry = files.find(file => file.rel === '.qoder-plugin/plugin.json');
60
+ if (!manifestEntry) {
61
+ throw new Error('Plugin root is missing .qoder-plugin/plugin.json.');
62
+ }
63
+ const manifest = JSON.parse(await readFile(manifestEntry.abs, 'utf8'));
64
+ if (typeof manifest.name !== 'string' || !manifest.name.trim()) {
65
+ throw new Error('.qoder-plugin/plugin.json must contain a non-empty name field.');
66
+ }
67
+
68
+ const localChunks = [];
69
+ const centralChunks = [];
70
+ let offset = 0;
71
+ let totalUncompressed = 0;
72
+
73
+ for (const file of files) {
74
+ const data = await readFile(file.abs);
75
+ totalUncompressed += data.length;
76
+ if (totalUncompressed > MAX_PLUGIN_ZIP_TOTAL_SIZE) {
77
+ throw new Error('Plugin archive exceeds the 256 MiB total size limit.');
78
+ }
79
+ const zipName = rootPrefix ? `${rootPrefix}/${file.rel}` : file.rel;
80
+ const nameBytes = Buffer.from(zipName, 'utf8');
81
+ const compressed = deflateRawSync(data, { level: 9 });
82
+ const useDeflate = compressed.length < data.length;
83
+ const payload = useDeflate ? compressed : data;
84
+ const method = useDeflate ? 8 : 0;
85
+ const checksum = crc32(data);
86
+ const posixMode = file.rel === 'scripts/launch-mcp' ? 0o100755 : (0o100000 | (file.mode & 0o777 || 0o644));
87
+
88
+ const localHeader = Buffer.alloc(30);
89
+ localHeader.writeUInt32LE(0x04034b50, 0);
90
+ localHeader.writeUInt16LE(20, 4);
91
+ localHeader.writeUInt16LE(0x0800, 6);
92
+ localHeader.writeUInt16LE(method, 8);
93
+ localHeader.writeUInt16LE(0, 10);
94
+ localHeader.writeUInt16LE(0x5421, 12);
95
+ localHeader.writeUInt32LE(checksum, 14);
96
+ localHeader.writeUInt32LE(payload.length, 18);
97
+ localHeader.writeUInt32LE(data.length, 22);
98
+ localHeader.writeUInt16LE(nameBytes.length, 26);
99
+ localHeader.writeUInt16LE(0, 28);
100
+ localChunks.push(localHeader, nameBytes, payload);
101
+
102
+ const centralHeader = Buffer.alloc(46);
103
+ centralHeader.writeUInt32LE(0x02014b50, 0);
104
+ centralHeader.writeUInt16LE((3 << 8) | 20, 4);
105
+ centralHeader.writeUInt16LE(20, 6);
106
+ centralHeader.writeUInt16LE(0x0800, 8);
107
+ centralHeader.writeUInt16LE(method, 10);
108
+ centralHeader.writeUInt16LE(0, 12);
109
+ centralHeader.writeUInt16LE(0x5421, 14);
110
+ centralHeader.writeUInt32LE(checksum, 16);
111
+ centralHeader.writeUInt32LE(payload.length, 20);
112
+ centralHeader.writeUInt32LE(data.length, 24);
113
+ centralHeader.writeUInt16LE(nameBytes.length, 28);
114
+ centralHeader.writeUInt16LE(0, 30);
115
+ centralHeader.writeUInt16LE(0, 32);
116
+ centralHeader.writeUInt16LE(0, 34);
117
+ centralHeader.writeUInt16LE(0, 36);
118
+ centralHeader.writeUInt32LE((posixMode << 16) >>> 0, 38);
119
+ centralHeader.writeUInt32LE(offset, 42);
120
+ centralChunks.push(centralHeader, nameBytes);
121
+
122
+ offset += localHeader.length + nameBytes.length + payload.length;
123
+ }
124
+
125
+ const centralBuffer = Buffer.concat(centralChunks);
126
+ const eocd = Buffer.alloc(22);
127
+ eocd.writeUInt32LE(0x06054b50, 0);
128
+ eocd.writeUInt16LE(0, 4);
129
+ eocd.writeUInt16LE(0, 6);
130
+ eocd.writeUInt16LE(files.length, 8);
131
+ eocd.writeUInt16LE(files.length, 10);
132
+ eocd.writeUInt32LE(centralBuffer.length, 12);
133
+ eocd.writeUInt32LE(offset, 16);
134
+ eocd.writeUInt16LE(0, 20);
135
+
136
+ const archive = Buffer.concat([...localChunks, centralBuffer, eocd]);
137
+ await mkdir(dirname(absOutputPath), { recursive: true });
138
+ await writeFile(absOutputPath, archive);
139
+ return {
140
+ ok: true,
141
+ outputPath: absOutputPath,
142
+ pluginName: manifest.name,
143
+ version: manifest.version,
144
+ fileCount: files.length,
145
+ bytes: archive.length,
146
+ };
147
+ }
148
+
149
+ export async function runPackPlugin(args = process.argv.slice(2)) {
150
+ let outputPath;
151
+ for (let i = 0; i < args.length; i++) {
152
+ if ((args[i] === '--output' || args[i] === '-o') && args[i + 1]) outputPath = args[++i];
153
+ else throw new Error('Usage: qoder-openpencil pack-plugin [--output /path/to/openpencil-qoder-plugin.zip]');
154
+ }
155
+ try {
156
+ const result = await packQoderPlugin(outputPath ? { outputPath } : {});
157
+ console.log(JSON.stringify(result, null, 2));
158
+ } catch (error) {
159
+ console.error(`Failed to pack Qoder plugin ZIP: ${error.message}`);
160
+ process.exitCode = 1;
161
+ }
162
+ }
163
+
164
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
165
+ await runPackPlugin(process.argv.slice(2));
166
+ }
@@ -0,0 +1,84 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
6
+ export const openPencilRoot = resolve(
7
+ process.env.OPENPENCIL_SOURCE_ROOT?.trim()
8
+ || process.env.OPENPENCIL_ROOT?.trim()
9
+ || resolve(projectRoot, '..', '..'),
10
+ );
11
+
12
+ const config = JSON.parse(await readFile(join(projectRoot, 'platforms.json'), 'utf8'));
13
+ if (config.schemaVersion !== 1) throw new Error('platforms.json: unsupported schemaVersion');
14
+ if (!config.openPencil || typeof config.openPencil !== 'object') {
15
+ throw new Error('platforms.json: openPencil metadata is required');
16
+ }
17
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(config.openPencil.version ?? '')) {
18
+ throw new Error('platforms.json: invalid OpenPencil version');
19
+ }
20
+ if (!/^[0-9a-f]{40}$/u.test(config.openPencil.revision ?? '')) {
21
+ throw new Error('platforms.json: OpenPencil revision must be a full lowercase commit SHA');
22
+ }
23
+ if (!Array.isArray(config.platforms) || config.platforms.length !== 6) {
24
+ throw new Error('platforms.json: exactly six platforms are required');
25
+ }
26
+
27
+ export const openPencil = Object.freeze({ ...config.openPencil });
28
+ export const platforms = Object.freeze(config.platforms.map(platform => Object.freeze({ ...platform })));
29
+
30
+ const expectedIds = [
31
+ 'darwin-arm64',
32
+ 'darwin-x64',
33
+ 'linux-arm64',
34
+ 'linux-x64',
35
+ 'win32-arm64',
36
+ 'win32-x64',
37
+ ];
38
+ if (platforms.some((platform, index) => platform.id !== expectedIds[index])) {
39
+ throw new Error(`platforms.json: expected platform order ${expectedIds.join(', ')}`);
40
+ }
41
+ if (new Set(platforms.map(platform => platform.packageName)).size !== platforms.length) {
42
+ throw new Error('platforms.json: platform package names must be unique');
43
+ }
44
+
45
+ export const runtimeManifestName = 'openpencil-runtime.json';
46
+
47
+ export function platformById(id) {
48
+ const platform = platforms.find(candidate => candidate.id === id);
49
+ if (platform === undefined) {
50
+ throw new Error(`unsupported platform ${JSON.stringify(id)}; expected one of ${expectedIds.join(', ')}`);
51
+ }
52
+ return platform;
53
+ }
54
+
55
+ export function platformPackageRoot(platform) {
56
+ return join(projectRoot, 'npm', platform.id);
57
+ }
58
+
59
+ export function runtimeKeyPaths(platform) {
60
+ return [
61
+ `bin/${platform.binaryName}`,
62
+ 'bin/web-bundle/op_host_web.js',
63
+ 'bin/web-bundle/op_host_web_bg.wasm',
64
+ 'bin/web-bundle/assets/iconify-catalog-core.json',
65
+ 'bin/web-bundle/canvaskit/canvaskit.js',
66
+ 'bin/web-bundle/canvaskit/canvaskit.wasm',
67
+ ];
68
+ }
69
+
70
+ export function argumentValue(name) {
71
+ const exactIndex = process.argv.indexOf(name);
72
+ if (exactIndex !== -1) {
73
+ const value = process.argv[exactIndex + 1];
74
+ if (value === undefined || value.startsWith('--')) throw new Error(`${name} requires a value`);
75
+ return value;
76
+ }
77
+ const prefix = name + '=';
78
+ const joined = process.argv.find(argument => argument.startsWith(prefix));
79
+ return joined?.slice(prefix.length);
80
+ }
81
+
82
+ export function hasFlag(name) {
83
+ return process.argv.includes(name);
84
+ }