@verentis/cli 0.2.22 → 0.2.24

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/README.md CHANGED
@@ -252,6 +252,9 @@ verentis yank my-app 1.0.3
252
252
 
253
253
  Published versions are `Submitted` for moderation; once approved the marketplace countersigns them and they become installable.
254
254
 
255
+ `verentis install` replaces an existing installation of the same package in the workspace branch in place, like the
256
+ marketplace install dialog. This upgrades or reinstalls an installed package and retries a `Failed` installation.
257
+
255
258
  ### Publisher publishing from GitHub Actions
256
259
 
257
260
  Register a GitHub federated credential on your publisher in each target Verentis
@@ -311,6 +314,27 @@ Packing behaviour:
311
314
  - `packaging.files` globs select the complete payload and override automatic selection. Without it,
312
315
  the packer derives payload files from manifest-relative schema `source` values and
313
316
  `spec.install[].from` globs.
317
+ - `packaging.variables` declares non-empty string values that can be substituted into selected text
318
+ payloads. `packaging.templates` uses the same glob semantics as `packaging.files`; matching payload
319
+ files are read as UTF-8 and `${var:<name>}` placeholders are replaced before digests and signatures
320
+ are computed. Variable names use lowercase letters, digits and internal hyphens, for example:
321
+
322
+ ```yaml
323
+ packaging:
324
+ publisher: verentis
325
+ files: [views/*.yaml]
326
+ variables:
327
+ canvas-origin: https://canvas.apps.localtest.me
328
+ templates:
329
+ - views/*.form.yaml
330
+ ```
331
+
332
+ Environment overlays can replace variables through the normal deep merge, e.g.
333
+ `environments/production.yaml` may set `packaging.variables.canvas-origin:
334
+ https://canvas.apps.verentis.dev`. Escape a literal placeholder with `$${var:name}`. Placeholders in
335
+ non-template payloads are left untouched; `verentis validate` warns so authors can add the file to
336
+ `packaging.templates` when substitution was intended. The packed manifest omits
337
+ `packaging.variables` and `packaging.templates` after they have been applied.
314
338
  - `pack --env production` merges `environments/production.yaml` and includes `production` in the
315
339
  output filename; `--overlay <path>` selects an explicit overlay, `--set-version <version>`
316
340
  overrides the packed manifest version, and `--bump-version` increments the authored patch version.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { mkdir, stat, writeFile, readFile, readdir, realpath, mkdtemp, rm, glob } from 'fs/promises';
3
+ import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm } from 'fs/promises';
4
4
  import { tmpdir, homedir } from 'os';
5
- import { resolve, basename, dirname, posix, join, isAbsolute, extname, relative, sep } from 'path';
5
+ import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
7
- import { promisify } from 'util';
7
+ 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';
@@ -388,7 +388,6 @@ var SCOPES = {
388
388
  packageCreate: "marketplace.package.create",
389
389
  packagePublish: "marketplace.package.publish",
390
390
  installCreate: "marketplace.install.create",
391
- installDelete: "marketplace.install.delete",
392
391
  resourceReadAll: "resources.resource.read-all",
393
392
  resourceUpdate: "resources.resource.update"
394
393
  };
@@ -447,7 +446,9 @@ var EXECUTION = {
447
446
  run: "execution.execution.run"
448
447
  };
449
448
  var MARKETPLACE = {
449
+ installDelete: "marketplace.install.delete",
450
450
  installRead: "marketplace.install.read",
451
+ installUpdate: "marketplace.install.update",
451
452
  packageDelete: "marketplace.package.delete",
452
453
  packageRead: "marketplace.package.read",
453
454
  packageUpdate: "marketplace.package.update",
@@ -558,7 +559,9 @@ var marketplace = {
558
559
  grantVisibility: e({ method: "POST", path: "/v1/packages/{packageId}/visibility-grants", scopes: [MARKETPLACE.packageVisibilityManage] }),
559
560
  revokeVisibility: e({ method: "DELETE", path: "/v1/packages/{packageId}/visibility-grants/{grantId}", scopes: [MARKETPLACE.packageVisibilityManage] }),
560
561
  getPackageStats: e({ method: "GET", path: "/v1/packages/{packageId}/stats", scopes: [MARKETPLACE.statsRead] }),
561
- listInstallations: e({ method: "GET", path: "/v1/installations", scopes: [MARKETPLACE.installRead], paged: true })};
562
+ listInstallations: e({ method: "GET", path: "/v1/installations", scopes: [MARKETPLACE.installRead], paged: true }),
563
+ uninstall: e({ method: "DELETE", path: "/v1/installations/{id}", scopes: [MARKETPLACE.installDelete, NODE.fileDelete, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate], workspaceBound: true })
564
+ };
562
565
 
563
566
  // src/api/client.ts
564
567
  function fillPath(template, params = {}) {
@@ -2616,6 +2619,58 @@ function formatMiB(bytes) {
2616
2619
  function toEntryPath(path) {
2617
2620
  return path.split(sep).join("/");
2618
2621
  }
2622
+ async function resolvePayloadFiles(projectDir, manifestPath, manifest) {
2623
+ const includes = manifest.packaging?.files ?? defaultIncludes(manifest);
2624
+ const excludes = manifest.packaging?.exclude ?? [];
2625
+ const matched = /* @__PURE__ */ new Set();
2626
+ for (const pattern of includes) {
2627
+ for await (const entry of glob(pattern, { cwd: projectDir, exclude: excludes })) {
2628
+ const abs = join(projectDir, entry);
2629
+ if (!(await stat(abs)).isFile()) continue;
2630
+ if (abs === manifestPath) continue;
2631
+ const rel = relative(projectDir, abs);
2632
+ if (rel.startsWith("..")) throw new Error(`Packaging glob '${pattern}' matched '${rel}' outside the project directory.`);
2633
+ matched.add(rel);
2634
+ }
2635
+ }
2636
+ return [...matched].sort();
2637
+ }
2638
+ function defaultIncludes(manifest) {
2639
+ const sources = /* @__PURE__ */ new Set();
2640
+ collectSchemaSources(manifest.spec, sources);
2641
+ collectInstallSources(manifest, sources);
2642
+ if (sources.size === 0) return [];
2643
+ return [...sources];
2644
+ }
2645
+ function collectInstallSources(manifest, sources) {
2646
+ const spec = manifest.spec;
2647
+ const install = spec?.install;
2648
+ if (!Array.isArray(install)) return;
2649
+ for (const directive of install) {
2650
+ const from = directive?.from;
2651
+ if (typeof from === "string" && from.length > 0 && !from.startsWith("/")) {
2652
+ sources.add(from);
2653
+ }
2654
+ }
2655
+ }
2656
+ function collectSchemaSources(node, sources) {
2657
+ if (Array.isArray(node)) {
2658
+ for (const item of node) collectSchemaSources(item, sources);
2659
+ return;
2660
+ }
2661
+ if (node && typeof node === "object") {
2662
+ for (const [key, value] of Object.entries(node)) {
2663
+ if (key === "source" && typeof value === "string" && value.startsWith("./")) {
2664
+ sources.add(value.slice(2));
2665
+ } else {
2666
+ collectSchemaSources(value, sources);
2667
+ }
2668
+ }
2669
+ }
2670
+ }
2671
+ function toEntryPath2(file) {
2672
+ return file.split(sep).join("/");
2673
+ }
2619
2674
  function isPlainObject(value) {
2620
2675
  return typeof value === "object" && value !== null && !Array.isArray(value);
2621
2676
  }
@@ -2658,6 +2713,178 @@ async function loadOverlay(path) {
2658
2713
  }
2659
2714
  return parsed;
2660
2715
  }
2716
+ var VARIABLE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
2717
+ var PLACEHOLDER_PATTERN = /(?<!\$)\$\{var:([^}]*)\}/g;
2718
+ var ESCAPED_PLACEHOLDER_PATTERN = /\$\$\{var:([^}]*)\}/g;
2719
+ var UTF8_DECODER = new TextDecoder$1("utf-8", { fatal: true });
2720
+ async function inspectPackagingTemplates(projectDir, manifest, payloadFiles) {
2721
+ const issues = [];
2722
+ const variables = readTemplateVariables(manifest, issues);
2723
+ const templateFiles = await resolveTemplateFiles(projectDir, manifest, payloadFiles, issues);
2724
+ for (const file of payloadFiles) {
2725
+ const sourcePath = join(projectDir, file);
2726
+ const bytes = await readFile(sourcePath);
2727
+ if (templateFiles.has(file)) {
2728
+ let text;
2729
+ try {
2730
+ text = UTF8_DECODER.decode(bytes);
2731
+ } catch {
2732
+ issues.push({ level: "error", message: `Template file '${toEntryPath2(file)}' must be valid UTF-8 text.` });
2733
+ continue;
2734
+ }
2735
+ validateTemplatePlaceholders(toEntryPath2(file), text, variables, issues);
2736
+ } else if (bytes.includes("${var:")) {
2737
+ const text = bytes.toString("utf8");
2738
+ for (const placeholder of findPlaceholders(text)) {
2739
+ issues.push({
2740
+ level: "warning",
2741
+ message: `${toEntryPath2(file)} contains template placeholder '${placeholder.raw}' but is not listed in packaging.templates; it will not be substituted when packed.`
2742
+ });
2743
+ }
2744
+ }
2745
+ }
2746
+ return { variables, templateFiles, issues };
2747
+ }
2748
+ async function createTemplatePlan(projectDir, manifest, payloadFiles) {
2749
+ const inspection = await inspectPackagingTemplates(projectDir, manifest, payloadFiles);
2750
+ const errors = inspection.issues.filter((issue) => issue.level === "error");
2751
+ if (errors.length > 0) {
2752
+ throw new Error(`Invalid packaging templates:
2753
+ ${errors.map((issue) => `- ${issue.message}`).join("\n")}`);
2754
+ }
2755
+ return { variables: inspection.variables, templateFiles: inspection.templateFiles };
2756
+ }
2757
+ function stripTemplatePackagingFields(manifest) {
2758
+ const packaging = manifest.packaging;
2759
+ if (!packaging || !Object.prototype.hasOwnProperty.call(packaging, "variables") && !Object.prototype.hasOwnProperty.call(packaging, "templates")) {
2760
+ return manifest;
2761
+ }
2762
+ const { variables: _variables, templates: _templates, ...rest } = packaging;
2763
+ const sanitized = { ...manifest };
2764
+ if (Object.keys(rest).length > 0) {
2765
+ sanitized.packaging = rest;
2766
+ } else {
2767
+ delete sanitized.packaging;
2768
+ }
2769
+ return sanitized;
2770
+ }
2771
+ async function readTemplatedPayloadBytes(projectDir, file, plan) {
2772
+ const sourcePath = join(projectDir, file);
2773
+ const bytes = await readFile(sourcePath);
2774
+ if (!plan.templateFiles.has(file)) return bytes;
2775
+ let text;
2776
+ try {
2777
+ text = UTF8_DECODER.decode(bytes);
2778
+ } catch {
2779
+ throw new Error(`Template file '${toEntryPath2(file)}' must be valid UTF-8 text.`);
2780
+ }
2781
+ return Buffer.from(substituteTemplateText(toEntryPath2(file), text, plan.variables), "utf8");
2782
+ }
2783
+ function readTemplateVariables(manifest, issues) {
2784
+ const section = manifest.packaging;
2785
+ const raw = section?.variables;
2786
+ const variables = {};
2787
+ if (raw === void 0) return variables;
2788
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
2789
+ issues.push({ level: "error", message: "packaging.variables must be an object of non-empty string values." });
2790
+ return variables;
2791
+ }
2792
+ for (const [name, value] of Object.entries(raw)) {
2793
+ if (!VARIABLE_NAME_PATTERN.test(name)) {
2794
+ issues.push({
2795
+ level: "error",
2796
+ message: `packaging.variables.${name} has an invalid name; use lowercase letters, digits, and internal hyphens.`
2797
+ });
2798
+ continue;
2799
+ }
2800
+ if (typeof value !== "string" || value.trim().length === 0) {
2801
+ issues.push({ level: "error", message: `packaging.variables.${name} must be a non-empty string.` });
2802
+ continue;
2803
+ }
2804
+ variables[name] = value;
2805
+ }
2806
+ return variables;
2807
+ }
2808
+ async function resolveTemplateFiles(projectDir, manifest, payloadFiles, issues) {
2809
+ const section = manifest.packaging;
2810
+ const templates = section?.templates;
2811
+ const templateFiles = /* @__PURE__ */ new Set();
2812
+ if (templates === void 0) return templateFiles;
2813
+ if (!Array.isArray(templates)) {
2814
+ issues.push({ level: "error", message: "packaging.templates must be a list of non-empty glob strings." });
2815
+ return templateFiles;
2816
+ }
2817
+ const payloadByEntryPath = new Map(payloadFiles.map((file) => [toEntryPath2(file), file]));
2818
+ const excludes = manifest.packaging?.exclude ?? [];
2819
+ for (const [index, value] of templates.entries()) {
2820
+ if (typeof value !== "string" || value.trim().length === 0) {
2821
+ issues.push({ level: "error", message: `packaging.templates[${index}] must be a non-empty glob string.` });
2822
+ continue;
2823
+ }
2824
+ const matchedPackagedFiles = /* @__PURE__ */ new Set();
2825
+ try {
2826
+ for await (const entry of glob(value, { cwd: projectDir, exclude: excludes })) {
2827
+ const abs = join(projectDir, entry);
2828
+ if (!(await stat(abs)).isFile()) continue;
2829
+ const rel = toEntryPath2(relative(projectDir, abs));
2830
+ const payloadFile = payloadByEntryPath.get(rel);
2831
+ if (payloadFile) matchedPackagedFiles.add(payloadFile);
2832
+ }
2833
+ } catch (error) {
2834
+ issues.push({
2835
+ level: "error",
2836
+ message: `packaging.templates[${index}] glob '${value}' is invalid: ${error instanceof Error ? error.message : String(error)}`
2837
+ });
2838
+ continue;
2839
+ }
2840
+ if (matchedPackagedFiles.size === 0) {
2841
+ issues.push({
2842
+ level: "error",
2843
+ message: `packaging.templates[${index}] glob '${value}' did not match any packaged file.`
2844
+ });
2845
+ continue;
2846
+ }
2847
+ for (const file of matchedPackagedFiles) templateFiles.add(file);
2848
+ }
2849
+ return templateFiles;
2850
+ }
2851
+ function validateTemplatePlaceholders(file, text, variables, issues) {
2852
+ for (const placeholder of findPlaceholders(text)) {
2853
+ if (!VARIABLE_NAME_PATTERN.test(placeholder.name)) {
2854
+ issues.push({
2855
+ level: "error",
2856
+ message: `${file} contains invalid template placeholder '${placeholder.raw}'; variable names must use lowercase letters, digits, and internal hyphens.`
2857
+ });
2858
+ continue;
2859
+ }
2860
+ if (!Object.prototype.hasOwnProperty.call(variables, placeholder.name)) {
2861
+ issues.push({
2862
+ level: "error",
2863
+ message: `${file} references undeclared template variable '${placeholder.raw}'. Declare packaging.variables.${placeholder.name}.`
2864
+ });
2865
+ }
2866
+ }
2867
+ }
2868
+ function substituteTemplateText(file, text, variables) {
2869
+ const substituted = text.replace(PLACEHOLDER_PATTERN, (raw, name) => {
2870
+ if (!VARIABLE_NAME_PATTERN.test(name)) {
2871
+ throw new Error(`${file} contains invalid template placeholder '${raw}'; variable names must use lowercase letters, digits, and internal hyphens.`);
2872
+ }
2873
+ if (!Object.prototype.hasOwnProperty.call(variables, name)) {
2874
+ throw new Error(`${file} references undeclared template variable '${raw}'. Declare packaging.variables.${name}.`);
2875
+ }
2876
+ return variables[name];
2877
+ });
2878
+ return substituted.replace(ESCAPED_PLACEHOLDER_PATTERN, (_raw, name) => `\${var:${name}}`);
2879
+ }
2880
+ function findPlaceholders(text) {
2881
+ const placeholders = [];
2882
+ PLACEHOLDER_PATTERN.lastIndex = 0;
2883
+ for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {
2884
+ placeholders.push({ raw: match[0], name: match[1] ?? "" });
2885
+ }
2886
+ return placeholders;
2887
+ }
2661
2888
 
2662
2889
  // src/vpkg/pack.ts
2663
2890
  async function pack(options) {
@@ -2696,10 +2923,13 @@ async function pack(options) {
2696
2923
  validatePackageName(publisher, "publisher name");
2697
2924
  const version = manifest.metadata.version;
2698
2925
  const payloadFiles = await resolvePayloadFiles(projectDir, manifestPath, manifest);
2926
+ const templatePlan = await createTemplatePlan(projectDir, manifest, payloadFiles);
2699
2927
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
2928
+ const packedManifest = stripTemplatePackagingFields(manifest);
2929
+ const manifestSanitized = packedManifest !== manifest;
2700
2930
  const staging = await mkdtemp(join(tmpdir(), "vpkg-"));
2701
2931
  try {
2702
- const manifestText = overrideApplied ? stringify(manifest) : await readFile(manifestPath, "utf8");
2932
+ const manifestText = overrideApplied || manifestSanitized ? stringify(packedManifest) : await readFile(manifestPath, "utf8");
2703
2933
  await writeFile(join(staging, "manifest.yaml"), manifestText);
2704
2934
  const encrypt = (options.encryptFor?.length ?? 0) > 0;
2705
2935
  const contentKey = encrypt ? generateContentKey() : null;
@@ -2707,11 +2937,11 @@ async function pack(options) {
2707
2937
  "manifest.yaml": sha256Hex(Buffer.from(manifestText, "utf8"))
2708
2938
  };
2709
2939
  for (const file of payloadFiles) {
2710
- const sourcePath = join(projectDir, file);
2711
2940
  const entryName = `files/${toEntryPath2(file)}`;
2712
2941
  const targetPath = join(staging, "files", file);
2713
2942
  await mkdir(dirname(targetPath), { recursive: true });
2714
- const bytes = contentKey ? encryptBytes(contentKey, await readFile(sourcePath)) : await readFile(sourcePath);
2943
+ const payloadBytes = await readTemplatedPayloadBytes(projectDir, file, templatePlan);
2944
+ const bytes = contentKey ? encryptBytes(contentKey, payloadBytes) : payloadBytes;
2715
2945
  await writeFile(targetPath, bytes);
2716
2946
  digests[entryName] = sha256Hex(bytes);
2717
2947
  }
@@ -2785,58 +3015,6 @@ async function pack(options) {
2785
3015
  await rm(staging, { recursive: true, force: true });
2786
3016
  }
2787
3017
  }
2788
- async function resolvePayloadFiles(projectDir, manifestPath, manifest) {
2789
- const includes = manifest.packaging?.files ?? defaultIncludes(manifest);
2790
- const excludes = manifest.packaging?.exclude ?? [];
2791
- const matched = /* @__PURE__ */ new Set();
2792
- for (const pattern of includes) {
2793
- for await (const entry of glob(pattern, { cwd: projectDir, exclude: excludes })) {
2794
- const abs = join(projectDir, entry);
2795
- if (!(await stat(abs)).isFile()) continue;
2796
- if (abs === manifestPath) continue;
2797
- const rel = relative(projectDir, abs);
2798
- if (rel.startsWith("..")) throw new Error(`Packaging glob '${pattern}' matched '${rel}' outside the project directory.`);
2799
- matched.add(rel);
2800
- }
2801
- }
2802
- return [...matched].sort();
2803
- }
2804
- function defaultIncludes(manifest) {
2805
- const sources = /* @__PURE__ */ new Set();
2806
- collectSchemaSources(manifest.spec, sources);
2807
- collectInstallSources(manifest, sources);
2808
- if (sources.size === 0) return [];
2809
- return [...sources];
2810
- }
2811
- function collectInstallSources(manifest, sources) {
2812
- const spec = manifest.spec;
2813
- const install = spec?.install;
2814
- if (!Array.isArray(install)) return;
2815
- for (const directive of install) {
2816
- const from = directive?.from;
2817
- if (typeof from === "string" && from.length > 0 && !from.startsWith("/")) {
2818
- sources.add(from);
2819
- }
2820
- }
2821
- }
2822
- function collectSchemaSources(node, sources) {
2823
- if (Array.isArray(node)) {
2824
- for (const item of node) collectSchemaSources(item, sources);
2825
- return;
2826
- }
2827
- if (node && typeof node === "object") {
2828
- for (const [key, value] of Object.entries(node)) {
2829
- if (key === "source" && typeof value === "string" && value.startsWith("./")) {
2830
- sources.add(value.slice(2));
2831
- } else {
2832
- collectSchemaSources(value, sources);
2833
- }
2834
- }
2835
- }
2836
- }
2837
- function toEntryPath2(file) {
2838
- return file.split(sep).join("/");
2839
- }
2840
3018
  function sha256Hex(data) {
2841
3019
  return createHash("sha256").update(data).digest("hex");
2842
3020
  }
@@ -3373,20 +3551,37 @@ function registerRegistry(program2) {
3373
3551
  console.log(`${pkg.publisherName}/${pkg.packageId}${version} \u2014 ${pkg.displayName} [${pkg.kind}, ${pkg.visibility.toLowerCase()}]`);
3374
3552
  }
3375
3553
  });
3376
- program2.command("install <ref> [version]").description("Install a package into a workspace").option("--workspace <workspaceId>", "target workspace (default: configured default workspace)").option("--path <path>", "install path override (bundles)").option("--branch <branch>", "workspace branch", "main").option("--sealed", "install as a sealed tarball instead of extracting").action(async (ref, version, options) => {
3554
+ program2.command("install <ref> [version]").description("Install a package into a workspace (replaces an existing or failed installation of the same package in place)").option("--workspace <workspaceId>", "target workspace (default: configured default workspace)").option("--path <path>", "install path override (bundles)").option("--branch <branch>", "workspace branch", "main").option("--sealed", "install as a sealed tarball instead of extracting").action(async (ref, version, options) => {
3377
3555
  const config = await loadConfig();
3378
3556
  const workspaceId = options.workspace ?? config.defaultWorkspaceId;
3379
3557
  if (!workspaceId) throw new Error("No workspace: pass --workspace <id> or set defaultWorkspaceId in ~/.verentis/config.json.");
3380
3558
  const api = await createApiClient();
3381
3559
  const { package: pkg } = await resolvePackageRef(api, ref);
3560
+ const consentScopes = pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
3561
+ const existing = await findActiveInstallation(api, workspaceId, pkg.id, options.branch);
3562
+ if (existing) {
3563
+ if (options.path && existing.installPath && options.path !== existing.installPath) {
3564
+ throw new Error(`${ref} is already installed at '${existing.installPath}' (installation ${existing.id}). Uninstall it before installing at '${options.path}'.`);
3565
+ }
3566
+ const result = await api.request("PUT", `/v1/installations/${existing.id}`, {
3567
+ scopes: [MARKETPLACE.installUpdate, NODE.fileDelete, ...INSTALL_NODE_SCOPES, ...consentScopes],
3568
+ tokenWorkspaceId: workspaceId,
3569
+ body: {
3570
+ id: existing.id,
3571
+ workspaceId,
3572
+ packageVersion: version ?? void 0,
3573
+ installMode: options.sealed ? "Sealed" : existing.installMode ?? "Extracted"
3574
+ }
3575
+ });
3576
+ if (result && result.succeeded === false) {
3577
+ throw new Error(`Reinstall of ${ref} failed (installation ${existing.id}, status ${result.status}): ${result.error ?? "unknown error"}`);
3578
+ }
3579
+ const from = existing.status === "Failed" ? "failed installation" : "installation";
3580
+ console.log(`Replaced ${from} ${existing.id} with ${ref}${version ? `@${version}` : ""} in workspace ${workspaceId} (${result?.status ?? "Installed"}).`);
3581
+ return;
3582
+ }
3382
3583
  const installationId = await api.request("POST", "/v1/installations", {
3383
- // Marketplace forwards this workspace-bound token to Node for extraction
3384
- // and to Resource for the administrator's consent decision.
3385
- scopes: [
3386
- SCOPES.installCreate,
3387
- "node.node.create",
3388
- ...pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : []
3389
- ],
3584
+ scopes: [SCOPES.installCreate, ...INSTALL_NODE_SCOPES, ...consentScopes],
3390
3585
  tokenWorkspaceId: workspaceId,
3391
3586
  body: {
3392
3587
  workspaceId,
@@ -3401,14 +3596,21 @@ function registerRegistry(program2) {
3401
3596
  });
3402
3597
  program2.command("uninstall <installationId>").description("Uninstall a package from a workspace").requiredOption("--workspace <workspaceId>", "the workspace the installation belongs to").action(async (installationId, options) => {
3403
3598
  const api = await createApiClient();
3404
- await api.request("DELETE", `/v1/installations/${installationId}`, {
3405
- scopes: [SCOPES.installDelete, "node.file.delete"],
3406
- tokenWorkspaceId: options.workspace,
3407
- body: { id: installationId, workspaceId: options.workspace }
3599
+ await call(api, marketplace.uninstall, {
3600
+ params: { id: installationId },
3601
+ query: { workspaceId: options.workspace },
3602
+ workspaceId: options.workspace
3408
3603
  });
3409
3604
  console.log(`Uninstalled ${installationId}.`);
3410
3605
  });
3411
3606
  }
3607
+ var INSTALL_NODE_SCOPES = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
3608
+ async function findActiveInstallation(api, workspaceId, packageId, branch) {
3609
+ const page = await call(api, marketplace.listInstallations, {
3610
+ query: { workspaceId, packageId, branch, pageNo: 1, pageSize: 100, orderBy: "createdAt desc" }
3611
+ });
3612
+ return pageItems(page).find((installation) => installation.status !== "Uninstalled") ?? null;
3613
+ }
3412
3614
 
3413
3615
  // src/commands/settings.ts
3414
3616
  async function settingScope(flags) {
@@ -3470,11 +3672,11 @@ function getCliVersion() {
3470
3672
  }
3471
3673
  function readVersion() {
3472
3674
  const candidates = ["../package.json", "../../package.json"];
3473
- for (const relative3 of candidates) {
3675
+ for (const relative4 of candidates) {
3474
3676
  try {
3475
- const raw = readFileSync(fileURLToPath(new URL(relative3, import.meta.url)), "utf8");
3677
+ const raw = readFileSync(fileURLToPath(new URL(relative4, import.meta.url)), "utf8");
3476
3678
  const pkg = JSON.parse(raw);
3477
- if (pkg.version && (relative3 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
3679
+ if (pkg.version && (relative4 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
3478
3680
  } catch {
3479
3681
  }
3480
3682
  }
@@ -3784,6 +3986,13 @@ function registerValidate(program2) {
3784
3986
  const overlayPath = resolveOverlayPath(dirname(manifestPath), { env: options.env, overlay: options.overlay });
3785
3987
  const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath)) : base;
3786
3988
  const issues = validateManifest(manifest);
3989
+ try {
3990
+ const payloadFiles = await resolvePayloadFiles(dirname(manifestPath), manifestPath, manifest);
3991
+ const templateInspection = await inspectPackagingTemplates(dirname(manifestPath), manifest, payloadFiles);
3992
+ issues.push(...templateInspection.issues);
3993
+ } catch (error) {
3994
+ issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
3995
+ }
3787
3996
  if (manifest.marketplace && !issues.some((issue) => issue.level === "error" && issue.message.startsWith("marketplace"))) {
3788
3997
  try {
3789
3998
  await buildCatalog(dirname(manifestPath), manifest.marketplace);