@verentis/cli 0.2.26 → 0.2.28

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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm } from 'fs/promises';
3
+ import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
4
4
  import { tmpdir, homedir } from 'os';
5
5
  import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
@@ -8,10 +8,11 @@ import { promisify, TextDecoder as TextDecoder$1 } from 'util';
8
8
  import * as tar from 'tar';
9
9
  import { extract } from 'tar';
10
10
  import { generateKeyPairSync, createHash, randomUUID, randomBytes, createCipheriv, createPublicKey, verify, diffieHellman, hkdfSync, sign, createPrivateKey } from 'crypto';
11
- import { parse, stringify, parseDocument } from 'yaml';
11
+ import { parse, parseDocument, isScalar, stringify, Document, YAMLMap, Scalar } from 'yaml';
12
12
  import { createWriteStream, readFileSync, createReadStream } from 'fs';
13
13
  import { Readable } from 'stream';
14
14
  import { pipeline } from 'stream/promises';
15
+ import { createRequire } from 'module';
15
16
  import { fileURLToPath } from 'url';
16
17
 
17
18
  function insecureFetchOptions(insecure) {
@@ -139,7 +140,7 @@ async function refreshIdentityToken(apiUrl, refreshToken, insecure) {
139
140
  `Session could not be renewed${payload?.error ? ` (${payload.error})` : ` (${res.status})`}. Run \`verentis login\` again.`
140
141
  );
141
142
  }
142
- var sleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
143
+ var sleep = (ms) => new Promise((resolve15) => setTimeout(resolve15, ms));
143
144
 
144
145
  // src/auth/githubActions.ts
145
146
  var JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
@@ -1076,6 +1077,14 @@ async function loadManifest(path) {
1076
1077
  if (collaborationErrors.length > 0) {
1077
1078
  throw new Error(`Invalid manifest at ${path}: ${collaborationErrors.join(" ")}`);
1078
1079
  }
1080
+ const messageErrors = validateMessageChannelsSection(kind, manifest.spec);
1081
+ if (messageErrors.length > 0) {
1082
+ throw new Error(`Invalid manifest at ${path}: ${messageErrors.join(" ")}`);
1083
+ }
1084
+ const actorErrors = validateActorSection(kind, manifest.spec);
1085
+ if (actorErrors.length > 0) {
1086
+ throw new Error(`Invalid manifest at ${path}: ${actorErrors.join(" ")}`);
1087
+ }
1079
1088
  const operationErrors = validateWopiOperationsSection(manifest.spec);
1080
1089
  if (operationErrors.length > 0) {
1081
1090
  throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
@@ -1142,6 +1151,110 @@ function validateHostedBackendDeclaration(kind, spec) {
1142
1151
  }
1143
1152
  return [];
1144
1153
  }
1154
+ var MESSAGE_CHANNEL_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
1155
+ var MAX_MESSAGE_CHANNELS = 32;
1156
+ function validateMessageChannelsSection(kind, spec) {
1157
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "messages")) return [];
1158
+ if (kind !== "Application") return ["spec.messages is only supported for Application manifests."];
1159
+ const messages = spec.messages;
1160
+ if (!Array.isArray(messages)) return ["spec.messages must be a list of { channel, description, schema? }."];
1161
+ if (messages.length > MAX_MESSAGE_CHANNELS) return [`spec.messages declares more than ${MAX_MESSAGE_CHANNELS} channels.`];
1162
+ const errors = [];
1163
+ const seen = /* @__PURE__ */ new Set();
1164
+ messages.forEach((value, index) => {
1165
+ const path = `spec.messages[${index}]`;
1166
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1167
+ errors.push(`${path} must be an object with channel and description.`);
1168
+ return;
1169
+ }
1170
+ const { channel, description, schema } = value;
1171
+ if (typeof channel !== "string" || !MESSAGE_CHANNEL_PATTERN.test(channel)) {
1172
+ errors.push(`${path}.channel must match ${MESSAGE_CHANNEL_PATTERN.source}.`);
1173
+ } else if (seen.has(channel)) {
1174
+ errors.push(`${path}.channel '${channel}' is declared more than once.`);
1175
+ } else {
1176
+ seen.add(channel);
1177
+ }
1178
+ if (typeof description !== "string" || description.trim().length === 0) {
1179
+ errors.push(`${path}.description is required so agents know when to use the channel.`);
1180
+ }
1181
+ if (schema !== void 0 && (!schema || typeof schema !== "object" || Array.isArray(schema))) {
1182
+ errors.push(`${path}.schema must be a JSON Schema object.`);
1183
+ }
1184
+ });
1185
+ return errors;
1186
+ }
1187
+ var ACTOR_SURFACE_KINDS = ["app-backend", "mcp", "native-collaboration", "document", "raw-file"];
1188
+ var ACTOR_FILE_KINDS = /* @__PURE__ */ new Set(["native-collaboration", "document", "raw-file"]);
1189
+ var MAX_ACTOR_SURFACES = 16;
1190
+ function validateActorSection(kind, spec) {
1191
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "actor")) return [];
1192
+ if (kind !== "Application") return ["spec.actor is only supported for Application manifests."];
1193
+ const applicationSpec = spec;
1194
+ const actor = applicationSpec.actor;
1195
+ if (!actor || typeof actor !== "object" || Array.isArray(actor)) {
1196
+ return ["spec.actor must be an object with live-channel and/or surfaces."];
1197
+ }
1198
+ const { "live-channel": liveChannel, surfaces } = actor;
1199
+ const errors = [];
1200
+ if (liveChannel !== void 0) {
1201
+ const declared = Array.isArray(applicationSpec.messages) && applicationSpec.messages.some((m) => m && typeof m === "object" && m.channel === liveChannel);
1202
+ if (typeof liveChannel !== "string" || !declared) {
1203
+ errors.push("spec.actor.live-channel must name a channel declared in spec.messages.");
1204
+ }
1205
+ }
1206
+ if (surfaces === void 0) {
1207
+ if (liveChannel === void 0) errors.push("spec.actor must declare live-channel and/or surfaces.");
1208
+ return errors;
1209
+ }
1210
+ if (!Array.isArray(surfaces) || surfaces.length === 0) {
1211
+ errors.push("spec.actor.surfaces must be a non-empty list of { kind, ... }.");
1212
+ return errors;
1213
+ }
1214
+ if (surfaces.length > MAX_ACTOR_SURFACES) {
1215
+ errors.push(`spec.actor.surfaces declares more than ${MAX_ACTOR_SURFACES} surfaces.`);
1216
+ return errors;
1217
+ }
1218
+ surfaces.forEach((value, index) => {
1219
+ const path = `spec.actor.surfaces[${index}]`;
1220
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1221
+ errors.push(`${path} must be an object with a kind.`);
1222
+ return;
1223
+ }
1224
+ const surface = value;
1225
+ const surfaceKind = surface.kind;
1226
+ if (typeof surfaceKind !== "string" || !ACTOR_SURFACE_KINDS.includes(surfaceKind)) {
1227
+ errors.push(`${path}.kind must be one of ${ACTOR_SURFACE_KINDS.join(", ")}.`);
1228
+ return;
1229
+ }
1230
+ const mimeTypes = surface["mime-types"];
1231
+ const extensions = surface.extensions;
1232
+ for (const [name, list] of [["mime-types", mimeTypes], ["extensions", extensions]]) {
1233
+ if (list !== void 0 && (!Array.isArray(list) || list.some((item) => typeof item !== "string" || item.trim().length === 0))) {
1234
+ errors.push(`${path}.${name} must be a list of non-empty strings.`);
1235
+ }
1236
+ }
1237
+ const filters = (Array.isArray(mimeTypes) ? mimeTypes.length : 0) + (Array.isArray(extensions) ? extensions.length : 0);
1238
+ if (ACTOR_FILE_KINDS.has(surfaceKind)) {
1239
+ if (filters === 0) errors.push(`${path} (${surfaceKind}) must list mime-types and/or extensions.`);
1240
+ } else if (mimeTypes !== void 0 || extensions !== void 0) {
1241
+ errors.push(`${path} (${surfaceKind}) is not a file surface and cannot list mime-types or extensions.`);
1242
+ }
1243
+ if (surface.format !== void 0 && (surfaceKind !== "raw-file" || surface.format !== "text" && surface.format !== "json")) {
1244
+ errors.push(`${path}.format is only for raw-file surfaces and must be text or json.`);
1245
+ }
1246
+ if (surface.description !== void 0 && typeof surface.description !== "string") {
1247
+ errors.push(`${path}.description must be a string.`);
1248
+ }
1249
+ if (surfaceKind === "native-collaboration" && applicationSpec.collaboration?.mode !== "native-scene-v1") {
1250
+ errors.push(`${path} (native-collaboration) requires spec.collaboration.mode native-scene-v1.`);
1251
+ }
1252
+ if (surfaceKind === "document" && !Object.prototype.hasOwnProperty.call(applicationSpec, "wopi")) {
1253
+ errors.push(`${path} (document) requires spec.wopi.`);
1254
+ }
1255
+ });
1256
+ return errors;
1257
+ }
1145
1258
  function validateNativeCollaborationSection(kind, spec) {
1146
1259
  if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "collaboration")) return [];
1147
1260
  if (kind !== "Application") return ["spec.collaboration is only supported for Application manifests."];
@@ -1354,6 +1467,8 @@ function validateManifest(manifest) {
1354
1467
  for (const message of validateHostedBackendDeclaration(kind, spec)) error(message);
1355
1468
  for (const message of validateDependencies(spec)) error(message);
1356
1469
  for (const message of validateNativeCollaborationSection(kind, spec)) error(message);
1470
+ for (const message of validateMessageChannelsSection(kind, spec)) error(message);
1471
+ for (const message of validateActorSection(kind, spec)) error(message);
1357
1472
  if (kind === "ExecutionEngine") {
1358
1473
  const runtimes = spec.runtimes ?? {};
1359
1474
  if (Object.keys(runtimes).length === 0) {
@@ -2014,7 +2129,7 @@ async function followExecution(api, workspaceId, executionId, json) {
2014
2129
  if (exec.status !== "Completed") process.exitCode = 1;
2015
2130
  return;
2016
2131
  }
2017
- await new Promise((resolve13) => setTimeout(resolve13, 1e3));
2132
+ await new Promise((resolve15) => setTimeout(resolve15, 1e3));
2018
2133
  }
2019
2134
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2020
2135
  process.exitCode = 1;
@@ -2155,6 +2270,427 @@ async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
2155
2270
  }
2156
2271
  return count;
2157
2272
  }
2273
+ var MAX_ICON_BYTES = 32 * 1024;
2274
+ var MAX_TOTAL_ICON_BYTES = 256 * 1024;
2275
+ var LEGACY_ICON_PATTERN = /^[a-z0-9-]+(:[a-z0-9-]+)?$/;
2276
+ var SVG_START = /^(?:<\?xml[\s\S]*?\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg\b/i;
2277
+ var SVG_END_CLOSING = /<\/svg>\s*$/i;
2278
+ var SVG_END_SELF_CLOSING = /<svg\b[\s\S]*\/>\s*$/i;
2279
+ var SVG_REJECTIONS = [
2280
+ [/&#/i, "numeric character references (&#) are not allowed"],
2281
+ [/<!DOCTYPE|<!ENTITY/i, "<!DOCTYPE>/<!ENTITY> declarations are not allowed"],
2282
+ [/<(?:script|foreignObject|iframe|object|embed|audio|video)\b/i, "script, foreignObject, iframe, object, embed, audio and video elements are not allowed"],
2283
+ [/\son[a-z]+\s*=/i, "event handler (on*=) attributes are not allowed"],
2284
+ [/(?:javascript|vbscript)\s*:/i, "javascript:/vbscript: URLs are not allowed"],
2285
+ [/data\s*:\s*text\/html/i, "data:text/html URLs are not allowed"],
2286
+ [/(?:xlink:href|href)\s*=\s*["']?\s*(?:https?:|ftp:|\/\/)/i, "external href/xlink:href references are not allowed"],
2287
+ [/url\(\s*["']?\s*(?:https?:|\/\/)/i, "external url(...) references are not allowed"]
2288
+ ];
2289
+ function validateSvgIcon(text) {
2290
+ if (Buffer.byteLength(text, "utf8") > MAX_ICON_BYTES) return `SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit`;
2291
+ const markup = canonicalizeSvg(text);
2292
+ if (!SVG_START.test(markup)) return "SVG must have an <svg> root element (only an <?xml ?> declaration and comments may precede it)";
2293
+ if (!SVG_END_CLOSING.test(markup) && !SVG_END_SELF_CLOSING.test(markup)) return "SVG must end with </svg>";
2294
+ for (const [pattern, reason] of SVG_REJECTIONS) {
2295
+ if (pattern.test(markup)) return reason;
2296
+ }
2297
+ return null;
2298
+ }
2299
+ function canonicalizeSvg(text) {
2300
+ return text.replace(/^\uFEFF+/, "").trim();
2301
+ }
2302
+ function decodeUtf8(bytes) {
2303
+ try {
2304
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2305
+ } catch {
2306
+ return null;
2307
+ }
2308
+ }
2309
+ function classifyIconValue(value) {
2310
+ const trimmed = value.trim();
2311
+ if (trimmed.startsWith("<")) return "inline";
2312
+ if (trimmed.startsWith("#")) return "ref";
2313
+ if (/\.svg$/i.test(trimmed)) return "path";
2314
+ if (LEGACY_ICON_PATTERN.test(trimmed)) return "legacy";
2315
+ return "invalid";
2316
+ }
2317
+ function collectIconFields(manifest) {
2318
+ const fields = [];
2319
+ if (!isRecord(manifest)) return fields;
2320
+ const add = (path, value) => {
2321
+ if (value !== void 0) fields.push({ path, label: formatPath(path), value });
2322
+ };
2323
+ const bindings = (container, path) => {
2324
+ if (!Array.isArray(container)) return;
2325
+ container.forEach((item, index) => {
2326
+ if (isRecord(item)) add([...path, index, "icon"], item.icon);
2327
+ });
2328
+ };
2329
+ if (isRecord(manifest.metadata)) add(["metadata", "icon"], manifest.metadata.icon);
2330
+ const spec = manifest.spec;
2331
+ if (!isRecord(spec)) return fields;
2332
+ if (Array.isArray(spec["entry-points"])) {
2333
+ spec["entry-points"].forEach((entryPoint, index) => {
2334
+ if (!isRecord(entryPoint)) return;
2335
+ add(["spec", "entry-points", index, "icon"], entryPoint.icon);
2336
+ bindings(entryPoint["mime-types"], ["spec", "entry-points", index, "mime-types"]);
2337
+ });
2338
+ }
2339
+ bindings(spec["mime-types"], ["spec", "mime-types"]);
2340
+ bindings(spec["file-types"], ["spec", "file-types"]);
2341
+ return fields;
2342
+ }
2343
+ async function resolveManifestIcons(manifest, manifestDir) {
2344
+ const errors = [];
2345
+ const warnings = [];
2346
+ const fields = [];
2347
+ const root = resolve(manifestDir);
2348
+ const distinct = /* @__PURE__ */ new Set();
2349
+ const resolveSvg = async (label, value, allowLegacy) => {
2350
+ const kind = classifyIconValue(value);
2351
+ if (kind === "inline") return checkMarkup(label, value.trim(), "inline SVG");
2352
+ if (kind === "path") {
2353
+ const loaded = await readIconFile(root, value.trim());
2354
+ if ("error" in loaded) {
2355
+ errors.push(`${label}: ${loaded.error}`);
2356
+ return void 0;
2357
+ }
2358
+ return checkMarkup(label, loaded.text, value.trim());
2359
+ }
2360
+ if (kind === "legacy" && allowLegacy) return void 0;
2361
+ errors.push(allowLegacy ? `${label}: '${value}' is not a relative .svg path, "#key" reference, inline <svg> markup or Iconify id` : `${label}: '${value}' must be a relative .svg path or inline <svg> markup`);
2362
+ return void 0;
2363
+ };
2364
+ const checkMarkup = (label, text, source) => {
2365
+ const problem = validateSvgIcon(text);
2366
+ if (problem) {
2367
+ errors.push(`${label}: ${source}: ${problem}`);
2368
+ return void 0;
2369
+ }
2370
+ const markup = canonicalizeSvg(text);
2371
+ distinct.add(markup);
2372
+ return markup;
2373
+ };
2374
+ const map = /* @__PURE__ */ new Map();
2375
+ const iconsSection = isRecord(manifest) ? manifest.icons : void 0;
2376
+ if (iconsSection !== void 0) {
2377
+ if (!isRecord(iconsSection)) {
2378
+ errors.push("icons must be a map of key -> SVG file path or inline <svg> markup");
2379
+ } else {
2380
+ for (const [key, value] of Object.entries(iconsSection)) {
2381
+ const label = `icons.${key}`;
2382
+ if (typeof value !== "string" || value.trim().length === 0) {
2383
+ errors.push(`${label} must be a non-empty string`);
2384
+ map.set(key, void 0);
2385
+ continue;
2386
+ }
2387
+ map.set(key, await resolveSvg(label, value, false));
2388
+ }
2389
+ }
2390
+ }
2391
+ for (const field of collectIconFields(manifest)) {
2392
+ if (typeof field.value !== "string" || field.value.trim().length === 0) {
2393
+ errors.push(`${field.label} must be a non-empty string`);
2394
+ continue;
2395
+ }
2396
+ const value = field.value;
2397
+ const kind = classifyIconValue(value);
2398
+ if (kind === "legacy") {
2399
+ warnings.push(`${field.label}: '${value}' is a legacy Iconify icon; run \`verentis icons migrate\` to convert it to SVG`);
2400
+ fields.push({ ...field, value, legacy: true });
2401
+ continue;
2402
+ }
2403
+ if (kind === "ref") {
2404
+ const key = value.trim().slice(1);
2405
+ if (!map.has(key)) {
2406
+ errors.push(`${field.label}: ${value.trim()} does not match a key in the top-level icons map`);
2407
+ continue;
2408
+ }
2409
+ const markup2 = map.get(key);
2410
+ if (markup2 !== void 0) fields.push({ ...field, value, markup: markup2, legacy: false });
2411
+ continue;
2412
+ }
2413
+ const markup = await resolveSvg(field.label, value, true);
2414
+ if (markup !== void 0) fields.push({ ...field, value, markup, legacy: false });
2415
+ }
2416
+ let logoIcon;
2417
+ const metadata = isRecord(manifest) && isRecord(manifest.metadata) ? manifest.metadata : void 0;
2418
+ const marketplace2 = isRecord(manifest) && isRecord(manifest.marketplace) ? manifest.marketplace : void 0;
2419
+ if (metadata && metadata.icon === void 0 && typeof marketplace2?.logo === "string" && /\.svg$/i.test(marketplace2.logo.trim())) {
2420
+ const loaded = await readIconFile(root, marketplace2.logo.trim());
2421
+ const problem = "error" in loaded ? loaded.error : validateSvgIcon(loaded.text);
2422
+ if (problem || "error" in loaded) {
2423
+ warnings.push(`marketplace.logo cannot be used as the app icon (metadata.icon fallback): ${problem}`);
2424
+ } else {
2425
+ logoIcon = canonicalizeSvg(loaded.text);
2426
+ distinct.add(logoIcon);
2427
+ }
2428
+ }
2429
+ const total = [...distinct].reduce((sum, markup) => sum + Buffer.byteLength(markup, "utf8"), 0);
2430
+ if (total > MAX_TOTAL_ICON_BYTES) {
2431
+ errors.push(`icons: total distinct SVG markup is ${(total / 1024).toFixed(1)} KiB, exceeding the ${MAX_TOTAL_ICON_BYTES / 1024} KiB per-manifest limit`);
2432
+ }
2433
+ const needsInlining = logoIcon !== void 0 || iconsSection !== void 0 || fields.some((field) => !field.legacy);
2434
+ return { errors, warnings, fields, logoIcon, needsInlining };
2435
+ }
2436
+ async function readIconFile(root, source) {
2437
+ if (isAbsolute(source) || /^[a-z][a-z0-9+.-]*:/i.test(source) || source.includes("\\")) {
2438
+ return { error: `${source} must be a path relative to the manifest directory` };
2439
+ }
2440
+ const candidate = resolve(root, source);
2441
+ if (escapes(root, candidate)) return { error: `${source} escapes the package directory` };
2442
+ let actual;
2443
+ let realRoot;
2444
+ try {
2445
+ actual = await realpath(candidate);
2446
+ realRoot = await realpath(root);
2447
+ } catch {
2448
+ return { error: `${source} not found` };
2449
+ }
2450
+ if (escapes(realRoot, actual)) return { error: `${source} escapes the package directory` };
2451
+ let bytes;
2452
+ try {
2453
+ bytes = await readFile(actual);
2454
+ } catch {
2455
+ return { error: `${source} could not be read (is it a file?)` };
2456
+ }
2457
+ if (bytes.length > MAX_ICON_BYTES) return { error: `${source}: SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit` };
2458
+ const text = decodeUtf8(bytes);
2459
+ if (text === null) return { error: `${source} is not valid UTF-8` };
2460
+ return { text };
2461
+ }
2462
+ function escapes(root, candidate) {
2463
+ const fromRoot = relative(root, candidate);
2464
+ return fromRoot === "" || fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
2465
+ }
2466
+ function iconKey(markup) {
2467
+ return createHash("sha256").update(markup, "utf8").digest("hex").slice(0, 12);
2468
+ }
2469
+ function inlineIconsIntoDocument(document, resolution) {
2470
+ const icons = /* @__PURE__ */ new Map();
2471
+ const quoted = (text) => Object.assign(new Scalar(text), { type: Scalar.QUOTE_DOUBLE });
2472
+ for (const field of resolution.fields) {
2473
+ if (field.markup === void 0) continue;
2474
+ const key = iconKey(field.markup);
2475
+ icons.set(key, field.markup);
2476
+ document.setIn(field.path, quoted(`#${key}`));
2477
+ }
2478
+ if (resolution.logoIcon !== void 0) {
2479
+ const key = iconKey(resolution.logoIcon);
2480
+ icons.set(key, resolution.logoIcon);
2481
+ document.setIn(["metadata", "icon"], quoted(`#${key}`));
2482
+ }
2483
+ if (icons.size === 0) {
2484
+ if (document.has("icons")) document.delete("icons");
2485
+ return;
2486
+ }
2487
+ const node = new YAMLMap();
2488
+ for (const [key, markup] of [...icons.entries()].sort(([a], [b]) => a.localeCompare(b))) {
2489
+ node.set(key, Object.assign(new Scalar(markup), { type: Scalar.BLOCK_LITERAL }));
2490
+ }
2491
+ document.set("icons", node);
2492
+ }
2493
+ function formatPath(path) {
2494
+ return path.reduce((text, segment) => typeof segment === "number" ? `${text}[${segment}]` : text ? `${text}.${segment}` : segment, "");
2495
+ }
2496
+ function isRecord(value) {
2497
+ return !!value && typeof value === "object" && !Array.isArray(value);
2498
+ }
2499
+
2500
+ // src/vpkg/iconMigration.ts
2501
+ var DEFAULT_ICONIFY_API = "https://api.iconify.design";
2502
+ function createIconSetLoader(options = {}) {
2503
+ const apiBase = (options.apiBase ?? process.env.VERENTIS_ICONIFY_API ?? DEFAULT_ICONIFY_API).replace(/\/+$/, "");
2504
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2505
+ const loadLocal = options.loadLocal ?? loadLocalCollection;
2506
+ const local = /* @__PURE__ */ new Map();
2507
+ return async (prefix, name) => {
2508
+ let collection = local.get(prefix);
2509
+ if (!collection) {
2510
+ collection = loadLocal(prefix);
2511
+ local.set(prefix, collection);
2512
+ }
2513
+ const installed = await collection;
2514
+ if (installed) return installed;
2515
+ const url = `${apiBase}/${encodeURIComponent(prefix)}.json?icons=${encodeURIComponent(name)}`;
2516
+ let response;
2517
+ try {
2518
+ response = await fetchImpl(url);
2519
+ } catch (error) {
2520
+ return { error: `could not reach the Iconify API (${url}): ${error instanceof Error ? error.message : String(error)}` };
2521
+ }
2522
+ if (response.status === 404) return { error: `unknown Iconify icon set '${prefix}'` };
2523
+ if (!response.ok) return { error: `Iconify API request failed (${url}): HTTP ${response.status}` };
2524
+ let body;
2525
+ try {
2526
+ body = await response.json();
2527
+ } catch {
2528
+ return { error: `Iconify API returned an invalid response (${url})` };
2529
+ }
2530
+ if (body === 404 || !body || typeof body !== "object" || !("icons" in body)) {
2531
+ return { error: `unknown Iconify icon set '${prefix}'` };
2532
+ }
2533
+ return body;
2534
+ };
2535
+ }
2536
+ async function loadLocalCollection(prefix) {
2537
+ const specifier = `@iconify-json/${prefix}/icons.json`;
2538
+ for (const base of [join(process.cwd(), "noop.js"), import.meta.url]) {
2539
+ try {
2540
+ const path = createRequire(base).resolve(specifier);
2541
+ return JSON.parse(await readFile(path, "utf8"));
2542
+ } catch {
2543
+ }
2544
+ }
2545
+ return null;
2546
+ }
2547
+ async function findIconManifests(dir) {
2548
+ const entries = await readdir(dir);
2549
+ const matches = entries.filter((name) => /\.(app|engine)\.ya?ml$/.test(name) || name === "manifest.yaml").sort().map((name) => join(dir, name));
2550
+ const files2 = [];
2551
+ for (const path of matches) {
2552
+ if ((await stat(path)).isFile()) files2.push(path);
2553
+ }
2554
+ return files2;
2555
+ }
2556
+ async function migrateManifestIcons(manifestPath, options = {}) {
2557
+ const loader = options.loader ?? createIconSetLoader();
2558
+ const text = await readFile(manifestPath, "utf8");
2559
+ const document = parseDocument(text);
2560
+ if (document.errors.length > 0) {
2561
+ throw new Error(`Failed to parse ${manifestPath}: ${document.errors.map((error) => error.message).join(" ")}`);
2562
+ }
2563
+ const manifest = document.toJS();
2564
+ const targets = [];
2565
+ for (const field of collectIconFields(manifest)) {
2566
+ if (typeof field.value === "string" && classifyIconValue(field.value) === "legacy") {
2567
+ targets.push({ path: field.path, label: field.label, value: field.value });
2568
+ }
2569
+ }
2570
+ const icons = manifest && typeof manifest === "object" ? manifest.icons : void 0;
2571
+ if (icons && typeof icons === "object" && !Array.isArray(icons)) {
2572
+ for (const [key, value] of Object.entries(icons)) {
2573
+ if (typeof value === "string" && classifyIconValue(value) === "legacy") {
2574
+ targets.push({ path: ["icons", key], label: formatPath(["icons", key]), value });
2575
+ }
2576
+ }
2577
+ }
2578
+ const result = { manifestPath, changes: [], errors: [], written: [], updated: false };
2579
+ const iconDir = join(dirname(manifestPath), "icons");
2580
+ const splices = [];
2581
+ const pending = /* @__PURE__ */ new Map();
2582
+ for (const target of targets) {
2583
+ const id = target.value.trim();
2584
+ const [prefix, name] = id.includes(":") ? id.split(":") : ["lucide", id];
2585
+ const svg = await renderIconifySvg(prefix, name, loader);
2586
+ if (typeof svg !== "string") {
2587
+ result.errors.push(`${target.label}: ${svg.error}; left as '${target.value}'`);
2588
+ continue;
2589
+ }
2590
+ const node = document.getIn(target.path, true);
2591
+ if (!isScalar(node) || !node.range) {
2592
+ result.errors.push(`${target.label}: could not locate the value in the YAML source; left as '${target.value}'`);
2593
+ continue;
2594
+ }
2595
+ const fileName = `${prefix}-${name}.svg`;
2596
+ const replacementValue = `./icons/${fileName}`;
2597
+ const file = join(iconDir, fileName);
2598
+ pending.set(file, svg);
2599
+ splices.push({ start: node.range[0], end: node.range[1], replacement: formatScalar(replacementValue, node.type) });
2600
+ result.changes.push({ field: target.label, from: target.value, to: replacementValue, file });
2601
+ }
2602
+ if (options.dryRun || result.changes.length === 0) return result;
2603
+ for (const [file, svg] of pending) {
2604
+ if (await exists2(file)) continue;
2605
+ await mkdir(iconDir, { recursive: true });
2606
+ await writeFile(file, `${svg}
2607
+ `);
2608
+ result.written.push(file);
2609
+ }
2610
+ let updated = text;
2611
+ for (const splice of splices.sort((a, b) => b.start - a.start)) {
2612
+ updated = updated.slice(0, splice.start) + splice.replacement + updated.slice(splice.end);
2613
+ }
2614
+ await writeFile(manifestPath, updated);
2615
+ result.updated = true;
2616
+ return result;
2617
+ }
2618
+ async function renderIconifySvg(prefix, name, loader = createIconSetLoader()) {
2619
+ const id = `${prefix}:${name}`;
2620
+ if (!/^[a-z0-9-]+$/.test(prefix) || !/^[a-z0-9-]+$/.test(name)) return { error: `invalid Iconify id '${id}'` };
2621
+ const icons = await loader(prefix, name);
2622
+ if ("error" in icons && typeof icons.error === "string") return { error: `${icons.error} (for '${id}')` };
2623
+ const { getIconData, iconToSVG, iconToHTML } = await import('@iconify/utils');
2624
+ const data = getIconData(icons, name);
2625
+ if (!data) return { error: `unknown Iconify icon '${id}'` };
2626
+ const rendered = iconToSVG(data);
2627
+ const svg = iconToHTML(rendered.body, { viewBox: rendered.attributes.viewBox });
2628
+ const problem = validateSvgIcon(svg);
2629
+ if (problem) return { error: `Iconify icon '${id}' does not satisfy the SVG icon rules: ${problem}` };
2630
+ return svg;
2631
+ }
2632
+ function formatScalar(value, type) {
2633
+ if (type === "QUOTE_SINGLE") return `'${value}'`;
2634
+ if (type === "QUOTE_DOUBLE") return `"${value}"`;
2635
+ return value;
2636
+ }
2637
+ async function exists2(path) {
2638
+ try {
2639
+ await access(path);
2640
+ return true;
2641
+ } catch {
2642
+ return false;
2643
+ }
2644
+ }
2645
+
2646
+ // src/commands/icons.ts
2647
+ function registerIcons(program2) {
2648
+ const icons = program2.command("icons").description("Manage manifest icons");
2649
+ icons.command("migrate [dir]").description("Convert legacy Iconify icon ids in manifests to local SVG files (icons/<prefix>-<name>.svg)").option("--file <path>", "migrate this manifest (repeatable; default: *.app.yaml, *.engine.yaml and manifest.yaml in dir)", collect, []).option("--dry-run", "report the changes without writing files").option("--iconify-api <url>", `Iconify API base URL when @iconify-json/<prefix> is not installed (default: VERENTIS_ICONIFY_API or ${DEFAULT_ICONIFY_API})`).action(async (dir, options) => {
2650
+ const manifests = options.file.length > 0 ? options.file.map((file) => resolve(file)) : await findIconManifests(resolve(dir ?? "."));
2651
+ if (manifests.length === 0) {
2652
+ throw new Error(`No manifests found in ${resolve(dir ?? ".")} (expected *.app.yaml, *.engine.yaml or manifest.yaml; use --file).`);
2653
+ }
2654
+ const loader = createIconSetLoader({ apiBase: options.iconifyApi });
2655
+ let errorCount = 0;
2656
+ for (const manifestPath of manifests) {
2657
+ if (!(await stat(manifestPath).catch(() => null))?.isFile()) throw new Error(`${manifestPath} does not exist.`);
2658
+ const result = await migrateManifestIcons(manifestPath, { dryRun: options.dryRun, loader });
2659
+ const verb = options.dryRun ? "would migrate" : "migrated";
2660
+ console.log(`${manifestPath}: ${verb} ${result.changes.length} icon(s)${result.errors.length ? `, ${result.errors.length} error(s)` : ""}`);
2661
+ for (const change of result.changes) console.log(` ${change.field}: ${change.from} -> ${change.to}`);
2662
+ for (const file of result.written) console.log(` wrote ${file}`);
2663
+ for (const error of result.errors) console.error(` error: ${error}`);
2664
+ errorCount += result.errors.length;
2665
+ }
2666
+ if (errorCount > 0) {
2667
+ console.error(`${errorCount} icon(s) could not be migrated; replace them with your own SVG files.`);
2668
+ process.exitCode = 1;
2669
+ }
2670
+ });
2671
+ }
2672
+ function collect(value, previous) {
2673
+ return [...previous, value];
2674
+ }
2675
+ var APP_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2676
+ <rect x="2" y="2" width="28" height="28" rx="7" fill="#475569"/>
2677
+ <rect x="8" y="8" width="7" height="7" rx="1.5" fill="#f8fafc"/>
2678
+ <rect x="17" y="8" width="7" height="7" rx="1.5" fill="#f8fafc"/>
2679
+ <rect x="8" y="17" width="7" height="7" rx="1.5" fill="#f8fafc"/>
2680
+ <rect x="17" y="17" width="7" height="7" rx="1.5" fill="#cbd5e1"/>
2681
+ </svg>
2682
+ `;
2683
+ var ENGINE_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2684
+ <rect x="2" y="2" width="28" height="28" rx="7" fill="#334155"/>
2685
+ <path d="M9 11l5 5-5 5" fill="none" stroke="#f8fafc" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
2686
+ <path d="M16 21h7" fill="none" stroke="#f8fafc" stroke-width="2.5" stroke-linecap="round"/>
2687
+ </svg>
2688
+ `;
2689
+ var TEMPLATE_FILES = {
2690
+ application: { "icons/app.svg": APP_ICON_SVG },
2691
+ engine: { "icons/app.svg": ENGINE_ICON_SVG },
2692
+ bundle: {}
2693
+ };
2158
2694
  var TEMPLATES = {
2159
2695
  application: (name) => `api-version: verentis.io/v1
2160
2696
  kind: Application
@@ -2164,7 +2700,7 @@ metadata:
2164
2700
  package-id: ${name}
2165
2701
  display-name: ${titleCase(name)}
2166
2702
  description: ""
2167
- icon: layout-dashboard
2703
+ icon: ./icons/app.svg
2168
2704
  version: 0.1.0
2169
2705
  author: ""
2170
2706
 
@@ -2216,7 +2752,7 @@ metadata:
2216
2752
  package-id: ${name}
2217
2753
  display-name: ${titleCase(name)}
2218
2754
  description: ""
2219
- icon: lucide:terminal
2755
+ icon: ./icons/app.svg
2220
2756
  version: 0.1.0
2221
2757
  author: ""
2222
2758
 
@@ -2287,13 +2823,20 @@ function registerInit(program2) {
2287
2823
  await mkdir(targetDir, { recursive: true });
2288
2824
  const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
2289
2825
  const manifestPath = join(targetDir, "manifest.yaml");
2290
- if (await exists2(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2826
+ if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2291
2827
  await writeFile(manifestPath, template(name));
2292
2828
  console.log(`Created ${manifestPath} (kind: ${options.kind}).`);
2829
+ for (const [relativePath, content] of Object.entries(TEMPLATE_FILES[options.kind.toLowerCase()] ?? {})) {
2830
+ const path = join(targetDir, relativePath);
2831
+ if (await exists3(path)) continue;
2832
+ await mkdir(dirname(path), { recursive: true });
2833
+ await writeFile(path, content);
2834
+ console.log(`Created ${path}.`);
2835
+ }
2293
2836
  console.log("Fill in packaging.publisher and packaging.files, then run `verentis pack`.");
2294
2837
  });
2295
2838
  }
2296
- async function exists2(path) {
2839
+ async function exists3(path) {
2297
2840
  try {
2298
2841
  await stat(path);
2299
2842
  return true;
@@ -3145,9 +3688,18 @@ async function pack(options) {
3145
3688
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
3146
3689
  const packedManifest = stripTemplatePackagingFields(manifest);
3147
3690
  const manifestSanitized = packedManifest !== manifest;
3691
+ const icons = await resolveManifestIcons(packedManifest, projectDir);
3692
+ if (icons.errors.length > 0) throw new Error(`Invalid icons:
3693
+ ${icons.errors.join("\n ")}`);
3148
3694
  const staging = await mkdtemp(join(tmpdir(), "vpkg-"));
3149
3695
  try {
3150
- const manifestText = overrideApplied || manifestSanitized ? stringify(packedManifest) : await readFile(manifestPath, "utf8");
3696
+ const embedObject = overrideApplied || manifestSanitized;
3697
+ let manifestText = embedObject ? stringify(packedManifest) : await readFile(manifestPath, "utf8");
3698
+ if (icons.needsInlining) {
3699
+ const document = embedObject ? new Document(packedManifest) : parseDocument(manifestText);
3700
+ inlineIconsIntoDocument(document, icons);
3701
+ manifestText = document.toString();
3702
+ }
3151
3703
  await writeFile(join(staging, "manifest.yaml"), manifestText);
3152
3704
  const encrypt = (options.encryptFor?.length ?? 0) > 0;
3153
3705
  const contentKey = encrypt ? generateContentKey() : null;
@@ -3227,7 +3779,8 @@ async function pack(options) {
3227
3779
  catalogFiles: catalog ? ["index.json", ...catalog.entries.map((entry) => entry.path.replace(/^catalog\//, ""))] : [],
3228
3780
  treeDigest: sha256Hex(Buffer.from(digestsJson, "utf8")),
3229
3781
  signed,
3230
- encrypted: encrypt
3782
+ encrypted: encrypt,
3783
+ warnings: icons.warnings
3231
3784
  };
3232
3785
  } finally {
3233
3786
  await rm(staging, { recursive: true, force: true });
@@ -3372,6 +3925,7 @@ function registerPack(program2) {
3372
3925
  signingKey,
3373
3926
  encryptFor
3374
3927
  });
3928
+ for (const warning of result.warnings) console.warn(`Warning: ${warning}`);
3375
3929
  console.log(`Packed ${result.publisher}/${result.packageId}@${result.version} (${result.kind})`);
3376
3930
  console.log(` ${result.outFile}`);
3377
3931
  console.log(` ${result.files.length} payload file(s), tree digest ${result.treeDigest.slice(0, 16)}\u2026, ${result.signed ? "signed" : "UNSIGNED"}${result.encrypted ? ", ENCRYPTED" : ""}`);
@@ -4049,11 +4603,11 @@ function getCliVersion() {
4049
4603
  }
4050
4604
  function readVersion() {
4051
4605
  const candidates = ["../package.json", "../../package.json"];
4052
- for (const relative4 of candidates) {
4606
+ for (const relative5 of candidates) {
4053
4607
  try {
4054
- const raw = readFileSync(fileURLToPath(new URL(relative4, import.meta.url)), "utf8");
4608
+ const raw = readFileSync(fileURLToPath(new URL(relative5, import.meta.url)), "utf8");
4055
4609
  const pkg = JSON.parse(raw);
4056
- if (pkg.version && (relative4 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
4610
+ if (pkg.version && (relative5 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
4057
4611
  } catch {
4058
4612
  }
4059
4613
  }
@@ -4370,6 +4924,9 @@ function registerValidate(program2) {
4370
4924
  } catch (error) {
4371
4925
  issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
4372
4926
  }
4927
+ const icons = await resolveManifestIcons(manifest, dirname(manifestPath));
4928
+ issues.push(...icons.errors.filter((message) => !issues.some((issue) => issue.message === message)).map((message) => ({ level: "error", message })));
4929
+ issues.push(...icons.warnings.map((message) => ({ level: "warning", message })));
4373
4930
  if (manifest.marketplace && !issues.some((issue) => issue.level === "error" && issue.message.startsWith("marketplace"))) {
4374
4931
  try {
4375
4932
  await buildCatalog(dirname(manifestPath), manifest.marketplace);
@@ -4488,6 +5045,7 @@ registerExec(program);
4488
5045
  registerPolicy(program);
4489
5046
  registerDev(program);
4490
5047
  registerValidate(program);
5048
+ registerIcons(program);
4491
5049
  registerCreate(program);
4492
5050
  registerPublisher(program);
4493
5051
  registerKeygen(program);