@verentis/cli 0.2.22 → 0.2.23

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
@@ -311,6 +311,27 @@ Packing behaviour:
311
311
  - `packaging.files` globs select the complete payload and override automatic selection. Without it,
312
312
  the packer derives payload files from manifest-relative schema `source` values and
313
313
  `spec.install[].from` globs.
314
+ - `packaging.variables` declares non-empty string values that can be substituted into selected text
315
+ payloads. `packaging.templates` uses the same glob semantics as `packaging.files`; matching payload
316
+ files are read as UTF-8 and `${var:<name>}` placeholders are replaced before digests and signatures
317
+ are computed. Variable names use lowercase letters, digits and internal hyphens, for example:
318
+
319
+ ```yaml
320
+ packaging:
321
+ publisher: verentis
322
+ files: [views/*.yaml]
323
+ variables:
324
+ canvas-origin: https://canvas.apps.localtest.me
325
+ templates:
326
+ - views/*.form.yaml
327
+ ```
328
+
329
+ Environment overlays can replace variables through the normal deep merge, e.g.
330
+ `environments/production.yaml` may set `packaging.variables.canvas-origin:
331
+ https://canvas.apps.verentis.dev`. Escape a literal placeholder with `$${var:name}`. Placeholders in
332
+ non-template payloads are left untouched; `verentis validate` warns so authors can add the file to
333
+ `packaging.templates` when substitution was intended. The packed manifest omits
334
+ `packaging.variables` and `packaging.templates` after they have been applied.
314
335
  - `pack --env production` merges `environments/production.yaml` and includes `production` in the
315
336
  output filename; `--overlay <path>` selects an explicit overlay, `--set-version <version>`
316
337
  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';
@@ -2616,6 +2616,58 @@ function formatMiB(bytes) {
2616
2616
  function toEntryPath(path) {
2617
2617
  return path.split(sep).join("/");
2618
2618
  }
2619
+ async function resolvePayloadFiles(projectDir, manifestPath, manifest) {
2620
+ const includes = manifest.packaging?.files ?? defaultIncludes(manifest);
2621
+ const excludes = manifest.packaging?.exclude ?? [];
2622
+ const matched = /* @__PURE__ */ new Set();
2623
+ for (const pattern of includes) {
2624
+ for await (const entry of glob(pattern, { cwd: projectDir, exclude: excludes })) {
2625
+ const abs = join(projectDir, entry);
2626
+ if (!(await stat(abs)).isFile()) continue;
2627
+ if (abs === manifestPath) continue;
2628
+ const rel = relative(projectDir, abs);
2629
+ if (rel.startsWith("..")) throw new Error(`Packaging glob '${pattern}' matched '${rel}' outside the project directory.`);
2630
+ matched.add(rel);
2631
+ }
2632
+ }
2633
+ return [...matched].sort();
2634
+ }
2635
+ function defaultIncludes(manifest) {
2636
+ const sources = /* @__PURE__ */ new Set();
2637
+ collectSchemaSources(manifest.spec, sources);
2638
+ collectInstallSources(manifest, sources);
2639
+ if (sources.size === 0) return [];
2640
+ return [...sources];
2641
+ }
2642
+ function collectInstallSources(manifest, sources) {
2643
+ const spec = manifest.spec;
2644
+ const install = spec?.install;
2645
+ if (!Array.isArray(install)) return;
2646
+ for (const directive of install) {
2647
+ const from = directive?.from;
2648
+ if (typeof from === "string" && from.length > 0 && !from.startsWith("/")) {
2649
+ sources.add(from);
2650
+ }
2651
+ }
2652
+ }
2653
+ function collectSchemaSources(node, sources) {
2654
+ if (Array.isArray(node)) {
2655
+ for (const item of node) collectSchemaSources(item, sources);
2656
+ return;
2657
+ }
2658
+ if (node && typeof node === "object") {
2659
+ for (const [key, value] of Object.entries(node)) {
2660
+ if (key === "source" && typeof value === "string" && value.startsWith("./")) {
2661
+ sources.add(value.slice(2));
2662
+ } else {
2663
+ collectSchemaSources(value, sources);
2664
+ }
2665
+ }
2666
+ }
2667
+ }
2668
+ function toEntryPath2(file) {
2669
+ return file.split(sep).join("/");
2670
+ }
2619
2671
  function isPlainObject(value) {
2620
2672
  return typeof value === "object" && value !== null && !Array.isArray(value);
2621
2673
  }
@@ -2658,6 +2710,178 @@ async function loadOverlay(path) {
2658
2710
  }
2659
2711
  return parsed;
2660
2712
  }
2713
+ var VARIABLE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
2714
+ var PLACEHOLDER_PATTERN = /(?<!\$)\$\{var:([^}]*)\}/g;
2715
+ var ESCAPED_PLACEHOLDER_PATTERN = /\$\$\{var:([^}]*)\}/g;
2716
+ var UTF8_DECODER = new TextDecoder$1("utf-8", { fatal: true });
2717
+ async function inspectPackagingTemplates(projectDir, manifest, payloadFiles) {
2718
+ const issues = [];
2719
+ const variables = readTemplateVariables(manifest, issues);
2720
+ const templateFiles = await resolveTemplateFiles(projectDir, manifest, payloadFiles, issues);
2721
+ for (const file of payloadFiles) {
2722
+ const sourcePath = join(projectDir, file);
2723
+ const bytes = await readFile(sourcePath);
2724
+ if (templateFiles.has(file)) {
2725
+ let text;
2726
+ try {
2727
+ text = UTF8_DECODER.decode(bytes);
2728
+ } catch {
2729
+ issues.push({ level: "error", message: `Template file '${toEntryPath2(file)}' must be valid UTF-8 text.` });
2730
+ continue;
2731
+ }
2732
+ validateTemplatePlaceholders(toEntryPath2(file), text, variables, issues);
2733
+ } else if (bytes.includes("${var:")) {
2734
+ const text = bytes.toString("utf8");
2735
+ for (const placeholder of findPlaceholders(text)) {
2736
+ issues.push({
2737
+ level: "warning",
2738
+ message: `${toEntryPath2(file)} contains template placeholder '${placeholder.raw}' but is not listed in packaging.templates; it will not be substituted when packed.`
2739
+ });
2740
+ }
2741
+ }
2742
+ }
2743
+ return { variables, templateFiles, issues };
2744
+ }
2745
+ async function createTemplatePlan(projectDir, manifest, payloadFiles) {
2746
+ const inspection = await inspectPackagingTemplates(projectDir, manifest, payloadFiles);
2747
+ const errors = inspection.issues.filter((issue) => issue.level === "error");
2748
+ if (errors.length > 0) {
2749
+ throw new Error(`Invalid packaging templates:
2750
+ ${errors.map((issue) => `- ${issue.message}`).join("\n")}`);
2751
+ }
2752
+ return { variables: inspection.variables, templateFiles: inspection.templateFiles };
2753
+ }
2754
+ function stripTemplatePackagingFields(manifest) {
2755
+ const packaging = manifest.packaging;
2756
+ if (!packaging || !Object.prototype.hasOwnProperty.call(packaging, "variables") && !Object.prototype.hasOwnProperty.call(packaging, "templates")) {
2757
+ return manifest;
2758
+ }
2759
+ const { variables: _variables, templates: _templates, ...rest } = packaging;
2760
+ const sanitized = { ...manifest };
2761
+ if (Object.keys(rest).length > 0) {
2762
+ sanitized.packaging = rest;
2763
+ } else {
2764
+ delete sanitized.packaging;
2765
+ }
2766
+ return sanitized;
2767
+ }
2768
+ async function readTemplatedPayloadBytes(projectDir, file, plan) {
2769
+ const sourcePath = join(projectDir, file);
2770
+ const bytes = await readFile(sourcePath);
2771
+ if (!plan.templateFiles.has(file)) return bytes;
2772
+ let text;
2773
+ try {
2774
+ text = UTF8_DECODER.decode(bytes);
2775
+ } catch {
2776
+ throw new Error(`Template file '${toEntryPath2(file)}' must be valid UTF-8 text.`);
2777
+ }
2778
+ return Buffer.from(substituteTemplateText(toEntryPath2(file), text, plan.variables), "utf8");
2779
+ }
2780
+ function readTemplateVariables(manifest, issues) {
2781
+ const section = manifest.packaging;
2782
+ const raw = section?.variables;
2783
+ const variables = {};
2784
+ if (raw === void 0) return variables;
2785
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
2786
+ issues.push({ level: "error", message: "packaging.variables must be an object of non-empty string values." });
2787
+ return variables;
2788
+ }
2789
+ for (const [name, value] of Object.entries(raw)) {
2790
+ if (!VARIABLE_NAME_PATTERN.test(name)) {
2791
+ issues.push({
2792
+ level: "error",
2793
+ message: `packaging.variables.${name} has an invalid name; use lowercase letters, digits, and internal hyphens.`
2794
+ });
2795
+ continue;
2796
+ }
2797
+ if (typeof value !== "string" || value.trim().length === 0) {
2798
+ issues.push({ level: "error", message: `packaging.variables.${name} must be a non-empty string.` });
2799
+ continue;
2800
+ }
2801
+ variables[name] = value;
2802
+ }
2803
+ return variables;
2804
+ }
2805
+ async function resolveTemplateFiles(projectDir, manifest, payloadFiles, issues) {
2806
+ const section = manifest.packaging;
2807
+ const templates = section?.templates;
2808
+ const templateFiles = /* @__PURE__ */ new Set();
2809
+ if (templates === void 0) return templateFiles;
2810
+ if (!Array.isArray(templates)) {
2811
+ issues.push({ level: "error", message: "packaging.templates must be a list of non-empty glob strings." });
2812
+ return templateFiles;
2813
+ }
2814
+ const payloadByEntryPath = new Map(payloadFiles.map((file) => [toEntryPath2(file), file]));
2815
+ const excludes = manifest.packaging?.exclude ?? [];
2816
+ for (const [index, value] of templates.entries()) {
2817
+ if (typeof value !== "string" || value.trim().length === 0) {
2818
+ issues.push({ level: "error", message: `packaging.templates[${index}] must be a non-empty glob string.` });
2819
+ continue;
2820
+ }
2821
+ const matchedPackagedFiles = /* @__PURE__ */ new Set();
2822
+ try {
2823
+ for await (const entry of glob(value, { cwd: projectDir, exclude: excludes })) {
2824
+ const abs = join(projectDir, entry);
2825
+ if (!(await stat(abs)).isFile()) continue;
2826
+ const rel = toEntryPath2(relative(projectDir, abs));
2827
+ const payloadFile = payloadByEntryPath.get(rel);
2828
+ if (payloadFile) matchedPackagedFiles.add(payloadFile);
2829
+ }
2830
+ } catch (error) {
2831
+ issues.push({
2832
+ level: "error",
2833
+ message: `packaging.templates[${index}] glob '${value}' is invalid: ${error instanceof Error ? error.message : String(error)}`
2834
+ });
2835
+ continue;
2836
+ }
2837
+ if (matchedPackagedFiles.size === 0) {
2838
+ issues.push({
2839
+ level: "error",
2840
+ message: `packaging.templates[${index}] glob '${value}' did not match any packaged file.`
2841
+ });
2842
+ continue;
2843
+ }
2844
+ for (const file of matchedPackagedFiles) templateFiles.add(file);
2845
+ }
2846
+ return templateFiles;
2847
+ }
2848
+ function validateTemplatePlaceholders(file, text, variables, issues) {
2849
+ for (const placeholder of findPlaceholders(text)) {
2850
+ if (!VARIABLE_NAME_PATTERN.test(placeholder.name)) {
2851
+ issues.push({
2852
+ level: "error",
2853
+ message: `${file} contains invalid template placeholder '${placeholder.raw}'; variable names must use lowercase letters, digits, and internal hyphens.`
2854
+ });
2855
+ continue;
2856
+ }
2857
+ if (!Object.prototype.hasOwnProperty.call(variables, placeholder.name)) {
2858
+ issues.push({
2859
+ level: "error",
2860
+ message: `${file} references undeclared template variable '${placeholder.raw}'. Declare packaging.variables.${placeholder.name}.`
2861
+ });
2862
+ }
2863
+ }
2864
+ }
2865
+ function substituteTemplateText(file, text, variables) {
2866
+ const substituted = text.replace(PLACEHOLDER_PATTERN, (raw, name) => {
2867
+ if (!VARIABLE_NAME_PATTERN.test(name)) {
2868
+ throw new Error(`${file} contains invalid template placeholder '${raw}'; variable names must use lowercase letters, digits, and internal hyphens.`);
2869
+ }
2870
+ if (!Object.prototype.hasOwnProperty.call(variables, name)) {
2871
+ throw new Error(`${file} references undeclared template variable '${raw}'. Declare packaging.variables.${name}.`);
2872
+ }
2873
+ return variables[name];
2874
+ });
2875
+ return substituted.replace(ESCAPED_PLACEHOLDER_PATTERN, (_raw, name) => `\${var:${name}}`);
2876
+ }
2877
+ function findPlaceholders(text) {
2878
+ const placeholders = [];
2879
+ PLACEHOLDER_PATTERN.lastIndex = 0;
2880
+ for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {
2881
+ placeholders.push({ raw: match[0], name: match[1] ?? "" });
2882
+ }
2883
+ return placeholders;
2884
+ }
2661
2885
 
2662
2886
  // src/vpkg/pack.ts
2663
2887
  async function pack(options) {
@@ -2696,10 +2920,13 @@ async function pack(options) {
2696
2920
  validatePackageName(publisher, "publisher name");
2697
2921
  const version = manifest.metadata.version;
2698
2922
  const payloadFiles = await resolvePayloadFiles(projectDir, manifestPath, manifest);
2923
+ const templatePlan = await createTemplatePlan(projectDir, manifest, payloadFiles);
2699
2924
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
2925
+ const packedManifest = stripTemplatePackagingFields(manifest);
2926
+ const manifestSanitized = packedManifest !== manifest;
2700
2927
  const staging = await mkdtemp(join(tmpdir(), "vpkg-"));
2701
2928
  try {
2702
- const manifestText = overrideApplied ? stringify(manifest) : await readFile(manifestPath, "utf8");
2929
+ const manifestText = overrideApplied || manifestSanitized ? stringify(packedManifest) : await readFile(manifestPath, "utf8");
2703
2930
  await writeFile(join(staging, "manifest.yaml"), manifestText);
2704
2931
  const encrypt = (options.encryptFor?.length ?? 0) > 0;
2705
2932
  const contentKey = encrypt ? generateContentKey() : null;
@@ -2707,11 +2934,11 @@ async function pack(options) {
2707
2934
  "manifest.yaml": sha256Hex(Buffer.from(manifestText, "utf8"))
2708
2935
  };
2709
2936
  for (const file of payloadFiles) {
2710
- const sourcePath = join(projectDir, file);
2711
2937
  const entryName = `files/${toEntryPath2(file)}`;
2712
2938
  const targetPath = join(staging, "files", file);
2713
2939
  await mkdir(dirname(targetPath), { recursive: true });
2714
- const bytes = contentKey ? encryptBytes(contentKey, await readFile(sourcePath)) : await readFile(sourcePath);
2940
+ const payloadBytes = await readTemplatedPayloadBytes(projectDir, file, templatePlan);
2941
+ const bytes = contentKey ? encryptBytes(contentKey, payloadBytes) : payloadBytes;
2715
2942
  await writeFile(targetPath, bytes);
2716
2943
  digests[entryName] = sha256Hex(bytes);
2717
2944
  }
@@ -2785,58 +3012,6 @@ async function pack(options) {
2785
3012
  await rm(staging, { recursive: true, force: true });
2786
3013
  }
2787
3014
  }
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
3015
  function sha256Hex(data) {
2841
3016
  return createHash("sha256").update(data).digest("hex");
2842
3017
  }
@@ -3470,11 +3645,11 @@ function getCliVersion() {
3470
3645
  }
3471
3646
  function readVersion() {
3472
3647
  const candidates = ["../package.json", "../../package.json"];
3473
- for (const relative3 of candidates) {
3648
+ for (const relative4 of candidates) {
3474
3649
  try {
3475
- const raw = readFileSync(fileURLToPath(new URL(relative3, import.meta.url)), "utf8");
3650
+ const raw = readFileSync(fileURLToPath(new URL(relative4, import.meta.url)), "utf8");
3476
3651
  const pkg = JSON.parse(raw);
3477
- if (pkg.version && (relative3 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
3652
+ if (pkg.version && (relative4 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
3478
3653
  } catch {
3479
3654
  }
3480
3655
  }
@@ -3784,6 +3959,13 @@ function registerValidate(program2) {
3784
3959
  const overlayPath = resolveOverlayPath(dirname(manifestPath), { env: options.env, overlay: options.overlay });
3785
3960
  const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath)) : base;
3786
3961
  const issues = validateManifest(manifest);
3962
+ try {
3963
+ const payloadFiles = await resolvePayloadFiles(dirname(manifestPath), manifestPath, manifest);
3964
+ const templateInspection = await inspectPackagingTemplates(dirname(manifestPath), manifest, payloadFiles);
3965
+ issues.push(...templateInspection.issues);
3966
+ } catch (error) {
3967
+ issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
3968
+ }
3787
3969
  if (manifest.marketplace && !issues.some((issue) => issue.level === "error" && issue.message.startsWith("marketplace"))) {
3788
3970
  try {
3789
3971
  await buildCatalog(dirname(manifestPath), manifest.marketplace);