@otwld/nx-argo 0.0.7 → 0.0.8

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 (54) hide show
  1. package/CHANGELOG.md +6 -3
  2. package/README.md +14 -13
  3. package/executors.json +34 -9
  4. package/package.json +1 -1
  5. package/src/executors/copy-image-lock/copy-image-lock.d.ts +5 -0
  6. package/src/executors/copy-image-lock/copy-image-lock.js +14 -0
  7. package/src/executors/copy-image-lock/schema.d.ts +19 -0
  8. package/src/executors/copy-image-lock/schema.json +48 -0
  9. package/src/executors/copy-source-revision/copy-source-revision.d.ts +5 -0
  10. package/src/executors/copy-source-revision/copy-source-revision.js +29 -0
  11. package/src/executors/copy-source-revision/schema.d.ts +19 -0
  12. package/src/executors/copy-source-revision/schema.json +41 -0
  13. package/src/executors/image-lock.d.ts +16 -0
  14. package/src/executors/image-lock.js +53 -0
  15. package/src/executors/set-source-revision/schema.d.ts +15 -0
  16. package/src/executors/set-source-revision/schema.json +28 -0
  17. package/src/executors/set-source-revision/set-source-revision.d.ts +5 -0
  18. package/src/executors/set-source-revision/set-source-revision.js +20 -0
  19. package/src/executors/shared.d.ts +28 -0
  20. package/src/executors/shared.js +112 -0
  21. package/src/executors/source-revision.d.ts +9 -0
  22. package/src/executors/source-revision.js +30 -0
  23. package/src/executors/validate-application/schema.d.ts +7 -0
  24. package/src/executors/validate-application/schema.json +19 -0
  25. package/src/executors/validate-application/validate-application.d.ts +5 -0
  26. package/src/executors/validate-application/validate-application.js +38 -0
  27. package/src/executors/validate-application-set/schema.d.ts +7 -0
  28. package/src/executors/validate-application-set/schema.json +20 -0
  29. package/src/executors/validate-application-set/validate-application-set.d.ts +5 -0
  30. package/src/executors/validate-application-set/validate-application-set.js +65 -0
  31. package/src/executors/validate-image-lock/schema.d.ts +15 -0
  32. package/src/executors/validate-image-lock/schema.json +36 -0
  33. package/src/executors/validate-image-lock/validate-image-lock.d.ts +5 -0
  34. package/src/executors/validate-image-lock/validate-image-lock.js +11 -0
  35. package/src/executors/{write-artifact-lock → write-image-lock}/schema.d.ts +5 -5
  36. package/src/executors/{write-artifact-lock → write-image-lock}/schema.json +10 -9
  37. package/src/executors/write-image-lock/write-image-lock.d.ts +5 -0
  38. package/src/executors/write-image-lock/write-image-lock.js +55 -0
  39. package/src/generators/environment-project/environment-project.d.ts +1 -1
  40. package/src/generators/environment-project/environment-project.js +56 -35
  41. package/src/generators/environment-project/schema.d.ts +11 -3
  42. package/src/generators/environment-project/schema.json +25 -7
  43. package/src/generators/preview-project/preview-project.d.ts +1 -1
  44. package/src/generators/preview-project/preview-project.js +16 -11
  45. package/src/generators/preview-project/schema.d.ts +6 -2
  46. package/src/generators/preview-project/schema.json +15 -7
  47. package/src/index.d.ts +14 -0
  48. package/src/index.js +15 -1
  49. package/src/executors/validate/schema.d.ts +0 -11
  50. package/src/executors/validate/schema.json +0 -28
  51. package/src/executors/validate/validate.d.ts +0 -5
  52. package/src/executors/validate/validate.js +0 -190
  53. package/src/executors/write-artifact-lock/write-artifact-lock.d.ts +0 -5
  54. package/src/executors/write-artifact-lock/write-artifact-lock.js +0 -168
@@ -2,16 +2,18 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = previewProjectGenerator;
4
4
  const devkit_1 = require("@nx/devkit");
5
- /** Creates a GitOps project boundary for an explicit preview stack. */
5
+ /** Creates a generic GitOps project boundary for an ApplicationSet workflow. */
6
6
  async function previewProjectGenerator(tree, options) {
7
7
  const name = (0, devkit_1.names)(options.name?.trim() || '').fileName;
8
- const apps = [
9
- ...new Set(options.apps?.map((app) => app.trim()).filter(Boolean)),
8
+ const dependencies = [
9
+ ...new Set(options.dependencies
10
+ ?.map((dependency) => dependency.trim())
11
+ .filter(Boolean)),
10
12
  ];
11
13
  const directory = (0, devkit_1.joinPathFragments)(options.directory?.trim() || 'gitops/previews', name);
12
14
  const projectFile = (0, devkit_1.joinPathFragments)(directory, 'project.json');
13
- if (!name || !apps.length) {
14
- throw new Error('[nx-argo] A preview name and at least one app are required.');
15
+ if (!name) {
16
+ throw new Error('[nx-argo] A preview name is required.');
15
17
  }
16
18
  if (tree.exists(projectFile)) {
17
19
  throw new Error(`[nx-argo] A GitOps preview project already exists at ${directory}.`);
@@ -21,18 +23,21 @@ async function previewProjectGenerator(tree, options) {
21
23
  root: directory,
22
24
  projectType: 'application',
23
25
  tags: ['type:gitops', 'environment:preview', `stack:${name}`],
24
- implicitDependencies: apps,
26
+ implicitDependencies: dependencies,
25
27
  metadata: {
26
28
  delivery: {
27
- previewStack: name,
29
+ preview: {
30
+ name,
31
+ ...(options.policy ? { policy: options.policy } : {}),
32
+ },
28
33
  },
29
34
  },
30
35
  targets: {
31
- validate: {
32
- executor: '@otwld/nx-argo:validate',
36
+ 'validate-application-set': {
37
+ executor: '@otwld/nx-argo:validate-application-set',
33
38
  options: {
34
- mode: 'preview',
35
- applicationSetFile: 'application-set.yaml',
39
+ file: options.applicationSetFile ?? 'application-set.yaml',
40
+ ...(options.policy ? { policy: options.policy } : {}),
36
41
  },
37
42
  },
38
43
  },
@@ -2,8 +2,12 @@
2
2
  export interface PreviewProjectGeneratorSchema {
3
3
  /** Preview stack identity. */
4
4
  name: string;
5
- /** Nx workload projects intentionally included in this stack. */
6
- apps: string[];
5
+ /** Nx projects this preview project implicitly depends on. */
6
+ dependencies?: string[];
7
+ /** Optional ApplicationSet policy to enforce. */
8
+ policy?: 'github-pr-preview';
9
+ /** Declared ApplicationSet file relative to the generated project. */
10
+ applicationSetFile?: string;
7
11
  /** Parent directory for generated preview stacks. */
8
12
  directory?: string;
9
13
  /** Skip Prettier formatting after generation. */
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/schema",
3
3
  "$id": "NxArgoPreviewProjectGeneratorSchema",
4
4
  "title": "GitOps preview project generator",
5
- "description": "Create an Nx GitOps project for an explicit multi-workload preview stack.",
5
+ "description": "Create an Nx GitOps project for a generic ApplicationSet preview workflow.",
6
6
  "type": "object",
7
7
  "properties": {
8
8
  "name": {
@@ -11,12 +11,20 @@
11
11
  "$default": { "source": "argv", "index": 0 },
12
12
  "x-priority": "important"
13
13
  },
14
- "apps": {
14
+ "dependencies": {
15
15
  "type": "array",
16
- "description": "Nx workload projects intentionally included in this stack.",
17
- "items": { "type": "string" },
18
- "minItems": 1,
19
- "x-priority": "important"
16
+ "description": "Nx projects this preview project implicitly depends on.",
17
+ "items": { "type": "string" }
18
+ },
19
+ "policy": {
20
+ "type": "string",
21
+ "enum": ["github-pr-preview"],
22
+ "description": "Optional ApplicationSet policy to enforce."
23
+ },
24
+ "applicationSetFile": {
25
+ "type": "string",
26
+ "default": "application-set.yaml",
27
+ "description": "Declared ApplicationSet file relative to the generated project."
20
28
  },
21
29
  "directory": {
22
30
  "type": "string",
@@ -29,6 +37,6 @@
29
37
  "default": false
30
38
  }
31
39
  },
32
- "required": ["name", "apps"],
40
+ "required": ["name"],
33
41
  "additionalProperties": false
34
42
  }
package/src/index.d.ts CHANGED
@@ -3,3 +3,17 @@ export { default as environmentProjectGenerator } from './generators/environment
3
3
  export type { EnvironmentProjectGeneratorSchema } from './generators/environment-project/schema';
4
4
  export { default as previewProjectGenerator } from './generators/preview-project/preview-project';
5
5
  export type { PreviewProjectGeneratorSchema } from './generators/preview-project/schema';
6
+ export { default as validateApplication } from './executors/validate-application/validate-application';
7
+ export type { ValidateApplicationExecutorSchema } from './executors/validate-application/schema';
8
+ export { default as validateApplicationSet } from './executors/validate-application-set/validate-application-set';
9
+ export type { ValidateApplicationSetExecutorSchema } from './executors/validate-application-set/schema';
10
+ export { default as validateImageLock } from './executors/validate-image-lock/validate-image-lock';
11
+ export type { ValidateImageLockExecutorSchema } from './executors/validate-image-lock/schema';
12
+ export { default as writeImageLock } from './executors/write-image-lock/write-image-lock';
13
+ export type { WriteImageLockExecutorSchema } from './executors/write-image-lock/schema';
14
+ export { default as copyImageLock } from './executors/copy-image-lock/copy-image-lock';
15
+ export type { CopyImageLockExecutorSchema } from './executors/copy-image-lock/schema';
16
+ export { default as setSourceRevision } from './executors/set-source-revision/set-source-revision';
17
+ export type { SetSourceRevisionExecutorSchema } from './executors/set-source-revision/schema';
18
+ export { default as copySourceRevision } from './executors/copy-source-revision/copy-source-revision';
19
+ export type { CopySourceRevisionExecutorSchema } from './executors/copy-source-revision/schema';
package/src/index.js CHANGED
@@ -3,9 +3,23 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.previewProjectGenerator = exports.environmentProjectGenerator = void 0;
6
+ exports.copySourceRevision = exports.setSourceRevision = exports.copyImageLock = exports.writeImageLock = exports.validateImageLock = exports.validateApplicationSet = exports.validateApplication = exports.previewProjectGenerator = exports.environmentProjectGenerator = void 0;
7
7
  /** Public generator and executor exports for the Argo CD package. */
8
8
  var environment_project_1 = require("./generators/environment-project/environment-project");
9
9
  Object.defineProperty(exports, "environmentProjectGenerator", { enumerable: true, get: function () { return __importDefault(environment_project_1).default; } });
10
10
  var preview_project_1 = require("./generators/preview-project/preview-project");
11
11
  Object.defineProperty(exports, "previewProjectGenerator", { enumerable: true, get: function () { return __importDefault(preview_project_1).default; } });
12
+ var validate_application_1 = require("./executors/validate-application/validate-application");
13
+ Object.defineProperty(exports, "validateApplication", { enumerable: true, get: function () { return __importDefault(validate_application_1).default; } });
14
+ var validate_application_set_1 = require("./executors/validate-application-set/validate-application-set");
15
+ Object.defineProperty(exports, "validateApplicationSet", { enumerable: true, get: function () { return __importDefault(validate_application_set_1).default; } });
16
+ var validate_image_lock_1 = require("./executors/validate-image-lock/validate-image-lock");
17
+ Object.defineProperty(exports, "validateImageLock", { enumerable: true, get: function () { return __importDefault(validate_image_lock_1).default; } });
18
+ var write_image_lock_1 = require("./executors/write-image-lock/write-image-lock");
19
+ Object.defineProperty(exports, "writeImageLock", { enumerable: true, get: function () { return __importDefault(write_image_lock_1).default; } });
20
+ var copy_image_lock_1 = require("./executors/copy-image-lock/copy-image-lock");
21
+ Object.defineProperty(exports, "copyImageLock", { enumerable: true, get: function () { return __importDefault(copy_image_lock_1).default; } });
22
+ var set_source_revision_1 = require("./executors/set-source-revision/set-source-revision");
23
+ Object.defineProperty(exports, "setSourceRevision", { enumerable: true, get: function () { return __importDefault(set_source_revision_1).default; } });
24
+ var copy_source_revision_1 = require("./executors/copy-source-revision/copy-source-revision");
25
+ Object.defineProperty(exports, "copySourceRevision", { enumerable: true, get: function () { return __importDefault(copy_source_revision_1).default; } });
@@ -1,11 +0,0 @@
1
- /** Options accepted by the Argo CD validation executor. */
2
- export interface ValidateExecutorSchema {
3
- /** GitOps project contract to validate. */
4
- mode: 'environment' | 'preview';
5
- /** Optional Application manifest relative to the owning Nx project root. */
6
- applicationFile?: string;
7
- /** ApplicationSet manifest relative to the owning Nx project root. */
8
- applicationSetFile?: string;
9
- /** Artifact lock file relative to the owning Nx project root. */
10
- artifactsFile?: string;
11
- }
@@ -1,28 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/schema",
3
- "version": 2,
4
- "title": "Validate Argo CD configuration",
5
- "description": "Validate a GitOps environment or preview project contract.",
6
- "type": "object",
7
- "properties": {
8
- "mode": {
9
- "type": "string",
10
- "enum": ["environment", "preview"],
11
- "description": "GitOps project contract to validate."
12
- },
13
- "applicationFile": {
14
- "type": "string",
15
- "description": "Optional Application manifest relative to the owning Nx project root."
16
- },
17
- "applicationSetFile": {
18
- "type": "string",
19
- "description": "ApplicationSet manifest relative to the owning Nx project root."
20
- },
21
- "artifactsFile": {
22
- "type": "string",
23
- "description": "Artifact lock file relative to the owning Nx project root."
24
- }
25
- },
26
- "required": ["mode"],
27
- "additionalProperties": false
28
- }
@@ -1,5 +0,0 @@
1
- import type { PromiseExecutor } from '@nx/devkit';
2
- import type { ValidateExecutorSchema } from './schema';
3
- /** Validates the declared Argo CD resources and artifact lock for one project. */
4
- declare const runExecutor: PromiseExecutor<ValidateExecutorSchema>;
5
- export default runExecutor;
@@ -1,190 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const node_fs_1 = require("node:fs");
4
- const node_path_1 = require("node:path");
5
- const yaml_1 = require("yaml");
6
- /** Validates the declared Argo CD resources and artifact lock for one project. */
7
- const runExecutor = async (options, context) => {
8
- const projectRoot = context.projectsConfigurations?.projects[context.projectName ?? '']?.root;
9
- if (!projectRoot) {
10
- throw new Error('[nx-argo] Validation requires an Nx project context.');
11
- }
12
- const root = (0, node_path_1.resolve)(context.root, projectRoot);
13
- if (options.mode === 'environment') {
14
- validateArtifacts(resolveProjectFile(root, options.artifactsFile, 'artifactsFile'));
15
- if (options.applicationFile) {
16
- validateApplication(resolveProjectFile(root, options.applicationFile, 'applicationFile'));
17
- }
18
- }
19
- else {
20
- validateApplicationSet(resolveProjectFile(root, options.applicationSetFile, 'applicationSetFile'));
21
- }
22
- return { success: true };
23
- };
24
- /** Resolves a required project-local file without accepting path escapes. */
25
- function resolveProjectFile(root, file, optionName) {
26
- if (!file?.trim()) {
27
- throw new Error(`[nx-argo] ${optionName} is required.`);
28
- }
29
- if ((0, node_path_1.isAbsolute)(file) || file.split(/[\\/]+/).includes('..')) {
30
- throw new Error(`[nx-argo] ${optionName} must stay within the project root.`);
31
- }
32
- const filePath = (0, node_path_1.resolve)(root, file);
33
- const pathFromRoot = (0, node_path_1.relative)(root, filePath);
34
- if (!pathFromRoot ||
35
- pathFromRoot === '..' ||
36
- pathFromRoot.startsWith(`..${node_path_1.sep}`) ||
37
- (0, node_path_1.isAbsolute)(pathFromRoot)) {
38
- throw new Error(`[nx-argo] ${optionName} must stay within the project root.`);
39
- }
40
- return filePath;
41
- }
42
- /** Parses an existing YAML mapping. */
43
- function readMapping(filePath, label) {
44
- if (!(0, node_fs_1.existsSync)(filePath)) {
45
- throw new Error(`[nx-argo] Required ${label} is missing: ${filePath}`);
46
- }
47
- const document = (0, yaml_1.parseDocument)((0, node_fs_1.readFileSync)(filePath, 'utf8'));
48
- if (document.errors.length ||
49
- !document.contents ||
50
- !(0, yaml_1.isMap)(document.contents)) {
51
- throw new Error(`[nx-argo] Invalid ${label}: ${filePath}`);
52
- }
53
- return document.toJS();
54
- }
55
- /** Validates an Application document. */
56
- function validateApplication(filePath) {
57
- const application = readMapping(filePath, 'Argo CD Application');
58
- if (application['apiVersion'] !== 'argoproj.io/v1alpha1' ||
59
- application['kind'] !== 'Application') {
60
- throw new Error(`[nx-argo] Invalid Argo CD Application: ${filePath}`);
61
- }
62
- const valueFiles = getHelmValueFiles(application);
63
- if (valueFiles.length &&
64
- valueFiles.at(-1)?.split('/').at(-1) !== 'artifacts.yaml') {
65
- throw new Error(`[nx-argo] artifacts.yaml must be the final Helm values file: ${filePath}`);
66
- }
67
- }
68
- /** Finds Helm value file lists across single- and multi-source Applications. */
69
- function getHelmValueFiles(application) {
70
- const spec = getMapping(application, 'spec');
71
- if (!spec) {
72
- return [];
73
- }
74
- const sources = [
75
- spec['source'],
76
- ...(Array.isArray(spec['sources']) ? spec['sources'] : []),
77
- ];
78
- return sources.flatMap((source) => {
79
- const helm = getMapping(source, 'helm');
80
- const valueFiles = helm?.['valueFiles'];
81
- return Array.isArray(valueFiles)
82
- ? valueFiles.filter((file) => typeof file === 'string')
83
- : [];
84
- });
85
- }
86
- /** Validates an ApplicationSet document needed by a preview project. */
87
- function validateApplicationSet(filePath) {
88
- const applicationSet = readMapping(filePath, 'Argo CD ApplicationSet');
89
- if (applicationSet['apiVersion'] !== 'argoproj.io/v1alpha1' ||
90
- applicationSet['kind'] !== 'ApplicationSet') {
91
- throw new Error(`[nx-argo] Invalid Argo CD ApplicationSet: ${filePath}`);
92
- }
93
- const spec = getMapping(applicationSet, 'spec');
94
- const template = getMapping(spec, 'template');
95
- const templateSpec = getMapping(template, 'spec');
96
- const project = templateSpec?.['project'];
97
- const automated = getMapping(getMapping(templateSpec, 'syncPolicy'), 'automated');
98
- if (!containsPullRequestGenerator(spec?.['generators']) ||
99
- typeof project !== 'string' ||
100
- !project.trim() ||
101
- /{{|}}/.test(project) ||
102
- automated?.['enabled'] !== true ||
103
- automated['prune'] !== true ||
104
- automated['selfHeal'] !== true ||
105
- getMapping(spec, 'syncPolicy')?.['preserveResourcesOnDeletion'] === true ||
106
- !hasArtifactLockLast(templateSpec)) {
107
- throw new Error(`[nx-argo] Invalid preview ApplicationSet contract: ${filePath}`);
108
- }
109
- }
110
- /** Requires the PR-specific immutable lock to be the final Helm values file. */
111
- function hasArtifactLockLast(templateSpec) {
112
- const sources = templateSpec?.['sources'];
113
- if (!Array.isArray(sources)) {
114
- return false;
115
- }
116
- return sources.some((source) => {
117
- const valueFiles = getMapping(source, 'helm')?.['valueFiles'];
118
- return (Array.isArray(valueFiles) &&
119
- typeof valueFiles.at(-1) === 'string' &&
120
- valueFiles.at(-1)?.includes('/locks/pr-'));
121
- });
122
- }
123
- /** Recursively finds a non-null ApplicationSet pull request generator. */
124
- function containsPullRequestGenerator(value) {
125
- if (Array.isArray(value)) {
126
- return value.some(containsPullRequestGenerator);
127
- }
128
- if (!isRecord(value)) {
129
- return false;
130
- }
131
- if (isRecord(value['pullRequest'])) {
132
- return true;
133
- }
134
- return Object.values(value).some(containsPullRequestGenerator);
135
- }
136
- /** Validates the complete artifact lock required by environment projects. */
137
- function validateArtifacts(filePath) {
138
- const artifacts = readMapping(filePath, 'artifact lock');
139
- const pending = getPath(artifacts, ['artifact', 'pending']);
140
- const values = [
141
- getPath(artifacts, ['image', 'repository']),
142
- getPath(artifacts, ['image', 'digest']),
143
- getPath(artifacts, ['artifact', 'service']),
144
- getPath(artifacts, ['artifact', 'sourceRevision']),
145
- ];
146
- if (pending === true) {
147
- if (values.every((value) => value === '')) {
148
- return;
149
- }
150
- throw new Error(`[nx-argo] Invalid pending artifact lock: ${filePath}`);
151
- }
152
- if (pending !== undefined && pending !== false) {
153
- throw new Error(`[nx-argo] Invalid artifact lock: ${filePath}`);
154
- }
155
- if (!isNonEmptyString(values[0]) ||
156
- !isDigest(values[1]) ||
157
- !isNonEmptyString(values[2]) ||
158
- !isNonEmptyString(values[3])) {
159
- throw new Error(`[nx-argo] Invalid artifact lock: ${filePath}`);
160
- }
161
- }
162
- /** Reads a nested mapping value without treating non-mappings as paths. */
163
- function getPath(root, path) {
164
- let current = root;
165
- for (const segment of path) {
166
- if (!isRecord(current)) {
167
- return undefined;
168
- }
169
- current = current[segment];
170
- }
171
- return current;
172
- }
173
- /** Returns a mapping when a value has the expected structural type. */
174
- function getMapping(value, key) {
175
- const candidate = key === undefined ? value : isRecord(value) ? value[key] : undefined;
176
- return isRecord(candidate) ? candidate : undefined;
177
- }
178
- /** Narrows unknown YAML values to simple object mappings. */
179
- function isRecord(value) {
180
- return typeof value === 'object' && value !== null && !Array.isArray(value);
181
- }
182
- /** Requires a non-empty string scalar. */
183
- function isNonEmptyString(value) {
184
- return typeof value === 'string' && Boolean(value.trim());
185
- }
186
- /** Validates an immutable SHA-256 image digest. */
187
- function isDigest(value) {
188
- return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value);
189
- }
190
- exports.default = runExecutor;
@@ -1,5 +0,0 @@
1
- import type { PromiseExecutor } from '@nx/devkit';
2
- import type { WriteArtifactLockExecutorSchema } from './schema';
3
- /** Writes or verifies one immutable artifact lock for a source revision. */
4
- declare const runExecutor: PromiseExecutor<WriteArtifactLockExecutorSchema>;
5
- export default runExecutor;
@@ -1,168 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const node_fs_1 = require("node:fs");
4
- const node_path_1 = require("node:path");
5
- const yaml_1 = require("yaml");
6
- /** Writes or verifies one immutable artifact lock for a source revision. */
7
- const runExecutor = async (options, context) => {
8
- const projectRoot = context.projectsConfigurations?.projects[context.projectName ?? '']?.root;
9
- if (!projectRoot) {
10
- throw new Error('[nx-argo] Artifact locking requires an Nx project context.');
11
- }
12
- if (!isNonEmptyString(options.repository)) {
13
- throw new Error('[nx-argo] An image repository is required.');
14
- }
15
- if (!/^sha256:[a-f0-9]{64}$/.test(options.digest)) {
16
- throw new Error('[nx-argo] An immutable sha256 image digest is required.');
17
- }
18
- if (!isNonEmptyString(options.service) ||
19
- !isNonEmptyString(options.sourceRevision)) {
20
- throw new Error('[nx-argo] A service and source revision are required.');
21
- }
22
- const root = (0, node_path_1.resolve)(context.root, projectRoot);
23
- const filePath = resolveProjectFile(root, options.file);
24
- if (!(0, node_fs_1.existsSync)(filePath)) {
25
- throw new Error(`[nx-argo] Artifact lock file is missing: ${filePath}`);
26
- }
27
- const paths = {
28
- repository: parsePath(options.repositoryPath),
29
- digest: parsePath(options.digestPath),
30
- service: parsePath(options.servicePath),
31
- sourceRevision: parsePath(options.sourceRevisionPath),
32
- };
33
- assertDistinctPaths(paths);
34
- const lock = parseYaml((0, node_fs_1.readFileSync)(filePath, 'utf8'));
35
- const isPending = getPath(lock, ['artifact', 'pending']) === true;
36
- if (isPending) {
37
- validatePendingLock(lock, paths);
38
- setPath(lock, ['artifact', 'pending'], false);
39
- }
40
- const existingRevision = getPath(lock, paths.sourceRevision);
41
- if (!isPending &&
42
- existingRevision !== undefined &&
43
- !isNonEmptyString(existingRevision)) {
44
- throw new Error('[nx-argo] Artifact source revision must be a string.');
45
- }
46
- if (!isPending && existingRevision === options.sourceRevision) {
47
- verifyValue(lock, paths.service, options.service, 'service');
48
- verifyValue(lock, paths.repository, options.repository, 'repository');
49
- verifyValue(lock, paths.digest, options.digest, 'digest');
50
- return { success: true };
51
- }
52
- setPath(lock, paths.repository, options.repository);
53
- setPath(lock, paths.digest, options.digest);
54
- setPath(lock, paths.service, options.service);
55
- setPath(lock, paths.sourceRevision, options.sourceRevision);
56
- (0, node_fs_1.writeFileSync)(filePath, (0, yaml_1.stringify)(lock, { lineWidth: 0 }));
57
- return { success: true };
58
- };
59
- /** Resolves a required project-local file without accepting path escapes. */
60
- function resolveProjectFile(root, file) {
61
- if (!file.trim() || (0, node_path_1.isAbsolute)(file) || file.split(/[\\/]+/).includes('..')) {
62
- throw new Error('[nx-argo] Artifact lock file must stay within the project root.');
63
- }
64
- const filePath = (0, node_path_1.resolve)(root, file);
65
- const pathFromRoot = (0, node_path_1.relative)(root, filePath);
66
- if (!pathFromRoot ||
67
- pathFromRoot === '..' ||
68
- pathFromRoot.startsWith(`..${node_path_1.sep}`) ||
69
- (0, node_path_1.isAbsolute)(pathFromRoot)) {
70
- throw new Error('[nx-argo] Artifact lock file must stay within the project root.');
71
- }
72
- return filePath;
73
- }
74
- /** Requires the four declared lock values to be empty before enrollment. */
75
- function validatePendingLock(lock, paths) {
76
- const pendingValues = [
77
- getPath(lock, paths['repository']),
78
- getPath(lock, paths['digest']),
79
- getPath(lock, paths['service']),
80
- getPath(lock, paths['sourceRevision']),
81
- ];
82
- if (!pendingValues.every((value) => value === '')) {
83
- throw new Error('[nx-argo] Pending artifact locks require empty artifact values.');
84
- }
85
- }
86
- /** Parses a YAML mapping without accepting malformed or empty documents. */
87
- function parseYaml(source) {
88
- const value = (0, yaml_1.parse)(source);
89
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
90
- throw new Error('[nx-argo] Artifact locks must contain a YAML mapping.');
91
- }
92
- return value;
93
- }
94
- /** Parses a dot-separated YAML mapping path. */
95
- function parsePath(path) {
96
- const segments = path.split('.');
97
- if (segments.some((segment) => !segment.trim())) {
98
- throw new Error('[nx-argo] Artifact mapping paths must not be empty.');
99
- }
100
- return segments;
101
- }
102
- /** Rejects equal or overlapping mapping paths before a write can corrupt data. */
103
- function assertDistinctPaths(paths) {
104
- const entries = [
105
- ['repository', paths.repository],
106
- ['digest', paths.digest],
107
- ['service', paths.service],
108
- ['sourceRevision', paths.sourceRevision],
109
- ];
110
- for (const [index, [name, path]] of entries.entries()) {
111
- for (const [otherName, otherPath] of entries.slice(index + 1)) {
112
- if (path.every((segment, pathIndex) => otherPath[pathIndex] === segment) ||
113
- otherPath.every((segment, pathIndex) => path[pathIndex] === segment)) {
114
- throw new Error(`[nx-argo] Artifact mapping paths conflict: ${name} and ${otherName}.`);
115
- }
116
- }
117
- }
118
- }
119
- /** Reads a mapping path and reports malformed intermediate values. */
120
- function getPath(root, path) {
121
- let current = root;
122
- for (const [index, segment] of path.entries()) {
123
- const value = current[segment];
124
- if (index === path.length - 1) {
125
- return value;
126
- }
127
- if (value === undefined) {
128
- return undefined;
129
- }
130
- if (!isRecord(value)) {
131
- throw new Error(`[nx-argo] Artifact mapping path conflicts at ${segment}.`);
132
- }
133
- current = value;
134
- }
135
- return undefined;
136
- }
137
- /** Verifies an idempotent write against the values recorded for its revision. */
138
- function verifyValue(lock, path, expected, label) {
139
- if (getPath(lock, path) !== expected) {
140
- throw new Error(`[nx-argo] Artifact ${label} conflicts with the existing source revision.`);
141
- }
142
- }
143
- /** Sets a dot-separated YAML mapping path. */
144
- function setPath(root, segments, value) {
145
- let current = root;
146
- for (const segment of segments.slice(0, -1)) {
147
- const child = current[segment];
148
- if (child === undefined) {
149
- current[segment] = {};
150
- }
151
- else if (typeof child !== 'object' ||
152
- child === null ||
153
- Array.isArray(child)) {
154
- throw new Error(`[nx-argo] Artifact mapping path conflicts at ${segment}.`);
155
- }
156
- current = current[segment];
157
- }
158
- current[segments.at(-1)] = value;
159
- }
160
- /** Narrows unknown YAML values to simple object mappings. */
161
- function isRecord(value) {
162
- return typeof value === 'object' && value !== null && !Array.isArray(value);
163
- }
164
- /** Requires a non-empty string option. */
165
- function isNonEmptyString(value) {
166
- return typeof value === 'string' && Boolean(value.trim());
167
- }
168
- exports.default = runExecutor;