@otwld/nx-argo 0.0.4 → 0.0.6

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/CHANGELOG.md CHANGED
@@ -1,3 +1,30 @@
1
+ ## 0.0.6 (unreleased)
2
+
3
+ ### Breaking changes
4
+
5
+ - Replace `application`, `service-application`, and `preview-stack` with `environment-project` and `preview-project`.
6
+ - Validate project-local environment locks and preview ApplicationSets; artifact writes are revision-idempotent.
7
+
8
+ ## 0.0.5 (2026-08-12)
9
+
10
+ ### 🚀 Features
11
+
12
+ - **argo:** add GitOps project tooling ([b291a720](https://github.com/otwld/devops/commit/b291a720))
13
+
14
+ ### ❤️ Thank You
15
+
16
+ - Tréhout Nathan
17
+
18
+ ## 0.0.4 (2026-08-12)
19
+
20
+ ### 🚀 Features
21
+
22
+ - **plugins:** add nx helm and argo plugins ([eb30b828](https://github.com/otwld/devops/commit/eb30b828))
23
+
24
+ ### ❤️ Thank You
25
+
26
+ - Tréhout Nathan
27
+
1
28
  ## 0.0.3 (2026-08-12)
2
29
 
3
30
  ### 🚀 Features
package/README.md CHANGED
@@ -1,53 +1,37 @@
1
1
  # @otwld/nx-argo
2
2
 
3
- Nx generator for Argo CD Applications and Helm values files.
3
+ Nx contract tooling for GitOps projects. It does not create or operate Argo CD resources.
4
4
 
5
- ## Generate an Application
5
+ ## Generators
6
+
7
+ `environment-project` creates `gitops/environments/<service>/<environment>` with:
8
+
9
+ - `project.json`: `gitops-<service>-<environment>`, one owning app dependency, delivery metadata, validation, and uncached artifact writes.
10
+ - `values.yaml`: human-owned configuration.
11
+ - `artifacts.yaml`: automation-owned immutable artifact lock.
6
12
 
7
13
  ```shell
8
- pnpm exec nx g @otwld/nx-argo:application \
9
- --directory=deployments/service/development \
10
- --name=service-development \
11
- --chart=service \
12
- --chartRepository=oci://registry.example.com/charts \
13
- --chartVersion=0.1.0 \
14
- --valuesRepoUrl=https://github.com/example/config.git \
15
- --valuesRevision=main \
16
- --project=default \
17
- --destinationServer=https://kubernetes.default.svc \
18
- --namespace=service-development
14
+ pnpm exec nx g @otwld/nx-argo:environment-project frontend \
15
+ --environment=staging --app=frontend
19
16
  ```
20
17
 
21
- The generator writes `application.yaml` and `values.yaml` to `--directory`.
22
-
23
- ```yaml
24
- spec:
25
- sources:
26
- - repoURL: registry.example.com/charts
27
- chart: service
28
- targetRevision: 0.1.0
29
- helm:
30
- releaseName: service
31
- valueFiles:
32
- - $values/deployments/service/development/values.yaml
33
- - repoURL: https://github.com/example/config.git
34
- targetRevision: main
35
- ref: values
18
+ `preview-project` creates `gitops/previews/<name>/project.json` with explicit app dependencies and `delivery.previewStack`. It creates no PR-specific lock. Add `application-set.yaml` before running validation.
19
+
20
+ ```shell
21
+ pnpm exec nx g @otwld/nx-argo:preview-project web \
22
+ --apps=frontend,backend
36
23
  ```
37
24
 
38
- The values repository URL must use HTTPS. Chart repositories may use HTTP(S) or
39
- OCI URLs; `oci://` is removed from OCI chart-source URLs.
25
+ ## Contracts
40
26
 
41
- ## Package Targets
27
+ Environment validation accepts either a pending or completed `artifacts.yaml`. A pending lock has `artifact.pending: true` and exactly empty string values for `image.repository`, `image.digest`, `artifact.service`, and `artifact.sourceRevision`. A completed lock has `artifact.pending: false` (or no pending field), a nonempty repository/service/source revision, and an immutable digest. An optional `application.yaml` must be an Argo CD `Application`; when it declares Helm value files, `artifacts.yaml` is last.
42
28
 
43
- - `nx build nx-argo`
44
- - `nx lint nx-argo`
45
- - `nx test nx-argo`
29
+ Preview validation requires an Argo CD `ApplicationSet` at `application-set.yaml`, a PR generator, a literal nonempty template project, enabled automated sync with `prune` and `selfHeal`, and no `preserveResourcesOnDeletion`.
46
30
 
47
- ## npm Release
31
+ `write-artifact-lock` requires an existing project-local lock and accepts image repository/digest plus service/source revision values. It converts a valid pending lock to `artifact.pending: false`, advances a new revision, and only verifies identical service, repository, and digest for an existing revision.
48
32
 
49
- ```shell
50
- pnpm exec nx release version --groups=npm --first-release --dry-run
51
- pnpm exec nx release publish --groups=npm --first-release --dry-run --access=public
52
- pnpm exec nx release --groups=npm --first-release
53
- ```
33
+ ## Package Targets
34
+
35
+ - `pnpm exec nx build nx-argo`
36
+ - `pnpm exec nx lint nx-argo`
37
+ - `pnpm exec nx test nx-argo`
package/executors.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "executors": {
4
+ "validate": {
5
+ "implementation": "./src/executors/validate/validate",
6
+ "schema": "./src/executors/validate/schema.json",
7
+ "description": "Validate an Argo CD Application and declared artifact lock files."
8
+ },
9
+ "write-artifact-lock": {
10
+ "implementation": "./src/executors/write-artifact-lock/write-artifact-lock",
11
+ "schema": "./src/executors/write-artifact-lock/schema.json",
12
+ "description": "Write an immutable image reference to a declared artifact lock file."
13
+ }
14
+ }
15
+ }
package/generators.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/schema",
3
3
  "generators": {
4
- "application": {
5
- "factory": "./src/generators/application/application",
6
- "schema": "./src/generators/application/schema.json",
7
- "description": "Create an Argo CD Application and its Helm values file."
4
+ "environment-project": {
5
+ "factory": "./src/generators/environment-project/environment-project",
6
+ "schema": "./src/generators/environment-project/schema.json",
7
+ "description": "Create a GitOps project boundary for one service environment."
8
+ },
9
+ "preview-project": {
10
+ "factory": "./src/generators/preview-project/preview-project",
11
+ "schema": "./src/generators/preview-project/schema.json",
12
+ "description": "Create a GitOps project boundary for an explicit preview stack."
8
13
  }
9
14
  }
10
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@otwld/nx-argo",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -10,7 +10,8 @@
10
10
  "default": "./src/index.js"
11
11
  },
12
12
  "./package.json": "./package.json",
13
- "./generators.json": "./generators.json"
13
+ "./generators.json": "./generators.json",
14
+ "./executors.json": "./executors.json"
14
15
  },
15
16
  "main": "./src/index.js",
16
17
  "types": "./src/index.d.ts",
@@ -26,5 +27,6 @@
26
27
  "publishConfig": {
27
28
  "access": "public"
28
29
  },
29
- "generators": "./generators.json"
30
+ "generators": "./generators.json",
31
+ "executors": "./executors.json"
30
32
  }
@@ -0,0 +1,11 @@
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
+ }
@@ -0,0 +1,28 @@
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
+ }
@@ -0,0 +1,5 @@
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;
@@ -0,0 +1,174 @@
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 || !document.contents || !(0, yaml_1.isMap)(document.contents)) {
49
+ throw new Error(`[nx-argo] Invalid ${label}: ${filePath}`);
50
+ }
51
+ return document.toJS();
52
+ }
53
+ /** Validates an Application document. */
54
+ function validateApplication(filePath) {
55
+ const application = readMapping(filePath, 'Argo CD Application');
56
+ if (application['apiVersion'] !== 'argoproj.io/v1alpha1' ||
57
+ application['kind'] !== 'Application') {
58
+ throw new Error(`[nx-argo] Invalid Argo CD Application: ${filePath}`);
59
+ }
60
+ const valueFiles = getHelmValueFiles(application);
61
+ if (valueFiles.length &&
62
+ valueFiles.at(-1)?.split('/').at(-1) !== 'artifacts.yaml') {
63
+ throw new Error(`[nx-argo] artifacts.yaml must be the final Helm values file: ${filePath}`);
64
+ }
65
+ }
66
+ /** Finds Helm value file lists across single- and multi-source Applications. */
67
+ function getHelmValueFiles(application) {
68
+ const spec = getMapping(application, 'spec');
69
+ if (!spec) {
70
+ return [];
71
+ }
72
+ const sources = [
73
+ spec['source'],
74
+ ...(Array.isArray(spec['sources']) ? spec['sources'] : []),
75
+ ];
76
+ return sources.flatMap((source) => {
77
+ const helm = getMapping(source, 'helm');
78
+ const valueFiles = helm?.['valueFiles'];
79
+ return Array.isArray(valueFiles)
80
+ ? valueFiles.filter((file) => typeof file === 'string')
81
+ : [];
82
+ });
83
+ }
84
+ /** Validates an ApplicationSet document needed by a preview project. */
85
+ function validateApplicationSet(filePath) {
86
+ const applicationSet = readMapping(filePath, 'Argo CD ApplicationSet');
87
+ if (applicationSet['apiVersion'] !== 'argoproj.io/v1alpha1' ||
88
+ applicationSet['kind'] !== 'ApplicationSet') {
89
+ throw new Error(`[nx-argo] Invalid Argo CD ApplicationSet: ${filePath}`);
90
+ }
91
+ const spec = getMapping(applicationSet, 'spec');
92
+ const template = getMapping(spec, 'template');
93
+ const templateSpec = getMapping(template, 'spec');
94
+ const project = templateSpec?.['project'];
95
+ const automated = getMapping(getMapping(templateSpec, 'syncPolicy'), 'automated');
96
+ if (!containsPullRequestGenerator(spec?.['generators']) ||
97
+ typeof project !== 'string' ||
98
+ !project.trim() ||
99
+ /{{|}}/.test(project) ||
100
+ automated?.['enabled'] !== true ||
101
+ automated['prune'] !== true ||
102
+ automated['selfHeal'] !== true ||
103
+ getMapping(spec, 'syncPolicy')?.['preserveResourcesOnDeletion'] === true) {
104
+ throw new Error(`[nx-argo] Invalid preview ApplicationSet contract: ${filePath}`);
105
+ }
106
+ }
107
+ /** Recursively finds a non-null ApplicationSet pull request generator. */
108
+ function containsPullRequestGenerator(value) {
109
+ if (Array.isArray(value)) {
110
+ return value.some(containsPullRequestGenerator);
111
+ }
112
+ if (!isRecord(value)) {
113
+ return false;
114
+ }
115
+ if (isRecord(value['pullRequest'])) {
116
+ return true;
117
+ }
118
+ return Object.values(value).some(containsPullRequestGenerator);
119
+ }
120
+ /** Validates the complete artifact lock required by environment projects. */
121
+ function validateArtifacts(filePath) {
122
+ const artifacts = readMapping(filePath, 'artifact lock');
123
+ const pending = getPath(artifacts, ['artifact', 'pending']);
124
+ const values = [
125
+ getPath(artifacts, ['image', 'repository']),
126
+ getPath(artifacts, ['image', 'digest']),
127
+ getPath(artifacts, ['artifact', 'service']),
128
+ getPath(artifacts, ['artifact', 'sourceRevision']),
129
+ ];
130
+ if (pending === true) {
131
+ if (values.every((value) => value === '')) {
132
+ return;
133
+ }
134
+ throw new Error(`[nx-argo] Invalid pending artifact lock: ${filePath}`);
135
+ }
136
+ if (pending !== undefined && pending !== false) {
137
+ throw new Error(`[nx-argo] Invalid artifact lock: ${filePath}`);
138
+ }
139
+ if (!isNonEmptyString(values[0]) ||
140
+ !isDigest(values[1]) ||
141
+ !isNonEmptyString(values[2]) ||
142
+ !isNonEmptyString(values[3])) {
143
+ throw new Error(`[nx-argo] Invalid artifact lock: ${filePath}`);
144
+ }
145
+ }
146
+ /** Reads a nested mapping value without treating non-mappings as paths. */
147
+ function getPath(root, path) {
148
+ let current = root;
149
+ for (const segment of path) {
150
+ if (!isRecord(current)) {
151
+ return undefined;
152
+ }
153
+ current = current[segment];
154
+ }
155
+ return current;
156
+ }
157
+ /** Returns a mapping when a value has the expected structural type. */
158
+ function getMapping(value, key) {
159
+ const candidate = key === undefined ? value : isRecord(value) ? value[key] : undefined;
160
+ return isRecord(candidate) ? candidate : undefined;
161
+ }
162
+ /** Narrows unknown YAML values to simple object mappings. */
163
+ function isRecord(value) {
164
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
165
+ }
166
+ /** Requires a non-empty string scalar. */
167
+ function isNonEmptyString(value) {
168
+ return typeof value === 'string' && Boolean(value.trim());
169
+ }
170
+ /** Validates an immutable SHA-256 image digest. */
171
+ function isDigest(value) {
172
+ return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value);
173
+ }
174
+ exports.default = runExecutor;
@@ -0,0 +1,21 @@
1
+ /** Options accepted by the artifact lock writer executor. */
2
+ export interface WriteArtifactLockExecutorSchema {
3
+ /** Artifact lock file relative to the owning Nx project root. */
4
+ file: string;
5
+ /** Dot-separated YAML path for the image repository. */
6
+ repositoryPath: string;
7
+ /** Dot-separated YAML path for the immutable image digest. */
8
+ digestPath: string;
9
+ /** Dot-separated YAML path for the deployment service identity. */
10
+ servicePath: string;
11
+ /** Dot-separated YAML path for the source revision. */
12
+ sourceRevisionPath: string;
13
+ /** Deployment service identity to write. */
14
+ service: string;
15
+ /** Source revision that produced this immutable artifact. */
16
+ sourceRevision: string;
17
+ /** Image repository to write. */
18
+ repository: string;
19
+ /** Immutable image digest to write. */
20
+ digest: string;
21
+ }
@@ -0,0 +1,50 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "version": 2,
4
+ "title": "Write artifact lock",
5
+ "description": "Write one immutable image reference to a declared YAML lock file.",
6
+ "type": "object",
7
+ "properties": {
8
+ "file": {
9
+ "type": "string",
10
+ "description": "Artifact lock file relative to the owning Nx project root."
11
+ },
12
+ "repositoryPath": {
13
+ "type": "string",
14
+ "description": "Dot-separated YAML path for the image repository."
15
+ },
16
+ "digestPath": {
17
+ "type": "string",
18
+ "description": "Dot-separated YAML path for the immutable image digest."
19
+ },
20
+ "servicePath": {
21
+ "type": "string",
22
+ "description": "Dot-separated YAML path for the deployment service identity."
23
+ },
24
+ "sourceRevisionPath": {
25
+ "type": "string",
26
+ "description": "Dot-separated YAML path for the source revision."
27
+ },
28
+ "service": {
29
+ "type": "string",
30
+ "description": "Deployment service identity to write.",
31
+ "minLength": 1
32
+ },
33
+ "sourceRevision": {
34
+ "type": "string",
35
+ "description": "Source revision that produced this immutable artifact.",
36
+ "minLength": 1
37
+ },
38
+ "repository": {
39
+ "type": "string",
40
+ "description": "Image repository to write."
41
+ },
42
+ "digest": {
43
+ "type": "string",
44
+ "description": "Immutable image digest to write.",
45
+ "pattern": "^sha256:[a-f0-9]{64}$"
46
+ }
47
+ },
48
+ "required": ["file", "repositoryPath", "digestPath", "servicePath", "sourceRevisionPath", "service", "sourceRevision", "repository", "digest"],
49
+ "additionalProperties": false
50
+ }
@@ -0,0 +1,5 @@
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;
@@ -0,0 +1,167 @@
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) || !isNonEmptyString(options.sourceRevision)) {
19
+ throw new Error('[nx-argo] A service and source revision are required.');
20
+ }
21
+ const root = (0, node_path_1.resolve)(context.root, projectRoot);
22
+ const filePath = resolveProjectFile(root, options.file);
23
+ if (!(0, node_fs_1.existsSync)(filePath)) {
24
+ throw new Error(`[nx-argo] Artifact lock file is missing: ${filePath}`);
25
+ }
26
+ const paths = {
27
+ repository: parsePath(options.repositoryPath),
28
+ digest: parsePath(options.digestPath),
29
+ service: parsePath(options.servicePath),
30
+ sourceRevision: parsePath(options.sourceRevisionPath),
31
+ };
32
+ assertDistinctPaths(paths);
33
+ const lock = parseYaml((0, node_fs_1.readFileSync)(filePath, 'utf8'));
34
+ const isPending = getPath(lock, ['artifact', 'pending']) === true;
35
+ if (isPending) {
36
+ validatePendingLock(lock, paths);
37
+ setPath(lock, ['artifact', 'pending'], false);
38
+ }
39
+ const existingRevision = getPath(lock, paths.sourceRevision);
40
+ if (!isPending &&
41
+ existingRevision !== undefined &&
42
+ !isNonEmptyString(existingRevision)) {
43
+ throw new Error('[nx-argo] Artifact source revision must be a string.');
44
+ }
45
+ if (!isPending && existingRevision === options.sourceRevision) {
46
+ verifyValue(lock, paths.service, options.service, 'service');
47
+ verifyValue(lock, paths.repository, options.repository, 'repository');
48
+ verifyValue(lock, paths.digest, options.digest, 'digest');
49
+ return { success: true };
50
+ }
51
+ setPath(lock, paths.repository, options.repository);
52
+ setPath(lock, paths.digest, options.digest);
53
+ setPath(lock, paths.service, options.service);
54
+ setPath(lock, paths.sourceRevision, options.sourceRevision);
55
+ (0, node_fs_1.writeFileSync)(filePath, (0, yaml_1.stringify)(lock, { lineWidth: 0 }));
56
+ return { success: true };
57
+ };
58
+ /** Resolves a required project-local file without accepting path escapes. */
59
+ function resolveProjectFile(root, file) {
60
+ if (!file.trim() || (0, node_path_1.isAbsolute)(file) || file.split(/[\\/]+/).includes('..')) {
61
+ throw new Error('[nx-argo] Artifact lock file must stay within the project root.');
62
+ }
63
+ const filePath = (0, node_path_1.resolve)(root, file);
64
+ const pathFromRoot = (0, node_path_1.relative)(root, filePath);
65
+ if (!pathFromRoot ||
66
+ pathFromRoot === '..' ||
67
+ pathFromRoot.startsWith(`..${node_path_1.sep}`) ||
68
+ (0, node_path_1.isAbsolute)(pathFromRoot)) {
69
+ throw new Error('[nx-argo] Artifact lock file must stay within the project root.');
70
+ }
71
+ return filePath;
72
+ }
73
+ /** Requires the four declared lock values to be empty before enrollment. */
74
+ function validatePendingLock(lock, paths) {
75
+ const pendingValues = [
76
+ getPath(lock, paths['repository']),
77
+ getPath(lock, paths['digest']),
78
+ getPath(lock, paths['service']),
79
+ getPath(lock, paths['sourceRevision']),
80
+ ];
81
+ if (!pendingValues.every((value) => value === '')) {
82
+ throw new Error('[nx-argo] Pending artifact locks require empty artifact values.');
83
+ }
84
+ }
85
+ /** Parses a YAML mapping without accepting malformed or empty documents. */
86
+ function parseYaml(source) {
87
+ const value = (0, yaml_1.parse)(source);
88
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
89
+ throw new Error('[nx-argo] Artifact locks must contain a YAML mapping.');
90
+ }
91
+ return value;
92
+ }
93
+ /** Parses a dot-separated YAML mapping path. */
94
+ function parsePath(path) {
95
+ const segments = path.split('.');
96
+ if (segments.some((segment) => !segment.trim())) {
97
+ throw new Error('[nx-argo] Artifact mapping paths must not be empty.');
98
+ }
99
+ return segments;
100
+ }
101
+ /** Rejects equal or overlapping mapping paths before a write can corrupt data. */
102
+ function assertDistinctPaths(paths) {
103
+ const entries = [
104
+ ['repository', paths.repository],
105
+ ['digest', paths.digest],
106
+ ['service', paths.service],
107
+ ['sourceRevision', paths.sourceRevision],
108
+ ];
109
+ for (const [index, [name, path]] of entries.entries()) {
110
+ for (const [otherName, otherPath] of entries.slice(index + 1)) {
111
+ if (path.every((segment, pathIndex) => otherPath[pathIndex] === segment) ||
112
+ otherPath.every((segment, pathIndex) => path[pathIndex] === segment)) {
113
+ throw new Error(`[nx-argo] Artifact mapping paths conflict: ${name} and ${otherName}.`);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ /** Reads a mapping path and reports malformed intermediate values. */
119
+ function getPath(root, path) {
120
+ let current = root;
121
+ for (const [index, segment] of path.entries()) {
122
+ const value = current[segment];
123
+ if (index === path.length - 1) {
124
+ return value;
125
+ }
126
+ if (value === undefined) {
127
+ return undefined;
128
+ }
129
+ if (!isRecord(value)) {
130
+ throw new Error(`[nx-argo] Artifact mapping path conflicts at ${segment}.`);
131
+ }
132
+ current = value;
133
+ }
134
+ return undefined;
135
+ }
136
+ /** Verifies an idempotent write against the values recorded for its revision. */
137
+ function verifyValue(lock, path, expected, label) {
138
+ if (getPath(lock, path) !== expected) {
139
+ throw new Error(`[nx-argo] Artifact ${label} conflicts with the existing source revision.`);
140
+ }
141
+ }
142
+ /** Sets a dot-separated YAML mapping path. */
143
+ function setPath(root, segments, value) {
144
+ let current = root;
145
+ for (const segment of segments.slice(0, -1)) {
146
+ const child = current[segment];
147
+ if (child === undefined) {
148
+ current[segment] = {};
149
+ }
150
+ else if (typeof child !== 'object' ||
151
+ child === null ||
152
+ Array.isArray(child)) {
153
+ throw new Error(`[nx-argo] Artifact mapping path conflicts at ${segment}.`);
154
+ }
155
+ current = current[segment];
156
+ }
157
+ current[segments.at(-1)] = value;
158
+ }
159
+ /** Narrows unknown YAML values to simple object mappings. */
160
+ function isRecord(value) {
161
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
162
+ }
163
+ /** Requires a non-empty string option. */
164
+ function isNonEmptyString(value) {
165
+ return typeof value === 'string' && Boolean(value.trim());
166
+ }
167
+ exports.default = runExecutor;
@@ -0,0 +1,4 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { EnvironmentProjectGeneratorSchema } from './schema';
3
+ /** Creates a GitOps project boundary for one service environment. */
4
+ export default function environmentProjectGenerator(tree: Tree, options: EnvironmentProjectGeneratorSchema): Promise<void>;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = environmentProjectGenerator;
4
+ const devkit_1 = require("@nx/devkit");
5
+ /** Creates a GitOps project boundary for one service environment. */
6
+ async function environmentProjectGenerator(tree, options) {
7
+ const service = getName(options.service, 'service');
8
+ const environment = getName(options.environment, 'environment');
9
+ const directory = (0, devkit_1.joinPathFragments)(options.directory?.trim() || 'gitops/environments', service, environment);
10
+ const projectFile = (0, devkit_1.joinPathFragments)(directory, 'project.json');
11
+ if (tree.exists(projectFile)) {
12
+ throw new Error(`[nx-argo] A GitOps environment project already exists at ${directory}.`);
13
+ }
14
+ (0, devkit_1.writeJson)(tree, projectFile, {
15
+ name: `gitops-${service}-${environment}`,
16
+ root: directory,
17
+ projectType: 'application',
18
+ tags: ['type:gitops', `service:${service}`, `environment:${environment}`],
19
+ implicitDependencies: [requireValue(options.app, 'app')],
20
+ metadata: {
21
+ delivery: {
22
+ service,
23
+ artifacts: {
24
+ file: 'artifacts.yaml',
25
+ image: {
26
+ repositoryPath: 'image.repository',
27
+ digestPath: 'image.digest',
28
+ },
29
+ sourceRevisionPath: 'artifact.sourceRevision',
30
+ servicePath: 'artifact.service',
31
+ },
32
+ },
33
+ },
34
+ targets: {
35
+ validate: {
36
+ executor: '@otwld/nx-argo:validate',
37
+ options: {
38
+ mode: 'environment',
39
+ artifactsFile: 'artifacts.yaml',
40
+ },
41
+ },
42
+ 'write-artifact-lock': {
43
+ executor: '@otwld/nx-argo:write-artifact-lock',
44
+ cache: false,
45
+ options: {
46
+ file: 'artifacts.yaml',
47
+ repositoryPath: 'image.repository',
48
+ digestPath: 'image.digest',
49
+ servicePath: 'artifact.service',
50
+ sourceRevisionPath: 'artifact.sourceRevision',
51
+ },
52
+ },
53
+ },
54
+ });
55
+ tree.write((0, devkit_1.joinPathFragments)(directory, 'values.yaml'), '# Environment configuration owned by humans.\n{}\n');
56
+ tree.write((0, devkit_1.joinPathFragments)(directory, 'artifacts.yaml'), '# Immutable artifacts written by automation.\nartifact:\n pending: true\n service: \'\'\n sourceRevision: \'\'\nimage:\n repository: \'\'\n digest: \'\'\n');
57
+ if (!options.skipFormat) {
58
+ await (0, devkit_1.formatFiles)(tree);
59
+ }
60
+ }
61
+ /** Normalizes an identifier used in directory and tag names. */
62
+ function getName(value, label) {
63
+ const normalized = (0, devkit_1.names)(requireValue(value, label)).fileName;
64
+ if (!normalized) {
65
+ throw new Error(`[nx-argo] A ${label} is required.`);
66
+ }
67
+ return normalized;
68
+ }
69
+ /** Requires a non-empty option. */
70
+ function requireValue(value, label) {
71
+ const normalized = value?.trim();
72
+ if (!normalized) {
73
+ throw new Error(`[nx-argo] A ${label} is required.`);
74
+ }
75
+ return normalized;
76
+ }
@@ -0,0 +1,13 @@
1
+ /** Options accepted by the GitOps environment project generator. */
2
+ export interface EnvironmentProjectGeneratorSchema {
3
+ /** Deployment identity shared with workloads and GitOps. */
4
+ service: string;
5
+ /** Environment represented by the generated GitOps project. */
6
+ environment: string;
7
+ /** Nx workload project that owns this GitOps environment. */
8
+ app: string;
9
+ /** Parent directory for generated GitOps environments. */
10
+ directory?: string;
11
+ /** Skip Prettier formatting after generation. */
12
+ skipFormat?: boolean;
13
+ }
@@ -0,0 +1,37 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "$id": "NxArgoEnvironmentProjectGeneratorSchema",
4
+ "title": "GitOps environment project generator",
5
+ "description": "Create an Nx GitOps project for one service environment.",
6
+ "type": "object",
7
+ "properties": {
8
+ "service": {
9
+ "type": "string",
10
+ "description": "Deployment identity shared with workloads and GitOps.",
11
+ "$default": { "source": "argv", "index": 0 },
12
+ "x-priority": "important"
13
+ },
14
+ "environment": {
15
+ "type": "string",
16
+ "description": "Environment represented by this GitOps project.",
17
+ "x-priority": "important"
18
+ },
19
+ "app": {
20
+ "type": "string",
21
+ "description": "Owning Nx workload project.",
22
+ "x-priority": "important"
23
+ },
24
+ "directory": {
25
+ "type": "string",
26
+ "description": "Parent directory for GitOps environments.",
27
+ "default": "gitops/environments"
28
+ },
29
+ "skipFormat": {
30
+ "type": "boolean",
31
+ "description": "Skip Prettier formatting after generation.",
32
+ "default": false
33
+ }
34
+ },
35
+ "required": ["service", "environment", "app"],
36
+ "additionalProperties": false
37
+ }
@@ -0,0 +1,4 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { PreviewProjectGeneratorSchema } from './schema';
3
+ /** Creates a GitOps project boundary for an explicit preview stack. */
4
+ export default function previewProjectGenerator(tree: Tree, options: PreviewProjectGeneratorSchema): Promise<void>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = previewProjectGenerator;
4
+ const devkit_1 = require("@nx/devkit");
5
+ /** Creates a GitOps project boundary for an explicit preview stack. */
6
+ async function previewProjectGenerator(tree, options) {
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)),
10
+ ];
11
+ const directory = (0, devkit_1.joinPathFragments)(options.directory?.trim() || 'gitops/previews', name);
12
+ 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
+ }
16
+ if (tree.exists(projectFile)) {
17
+ throw new Error(`[nx-argo] A GitOps preview project already exists at ${directory}.`);
18
+ }
19
+ (0, devkit_1.writeJson)(tree, projectFile, {
20
+ name: `gitops-preview-${name}`,
21
+ root: directory,
22
+ projectType: 'application',
23
+ tags: ['type:gitops', 'environment:preview', `stack:${name}`],
24
+ implicitDependencies: apps,
25
+ metadata: {
26
+ delivery: {
27
+ previewStack: name,
28
+ },
29
+ },
30
+ targets: {
31
+ validate: {
32
+ executor: '@otwld/nx-argo:validate',
33
+ options: {
34
+ mode: 'preview',
35
+ applicationSetFile: 'application-set.yaml',
36
+ },
37
+ },
38
+ },
39
+ });
40
+ if (!options.skipFormat) {
41
+ await (0, devkit_1.formatFiles)(tree);
42
+ }
43
+ }
@@ -0,0 +1,11 @@
1
+ /** Options accepted by the GitOps preview project generator. */
2
+ export interface PreviewProjectGeneratorSchema {
3
+ /** Preview stack identity. */
4
+ name: string;
5
+ /** Nx workload projects intentionally included in this stack. */
6
+ apps: string[];
7
+ /** Parent directory for generated preview stacks. */
8
+ directory?: string;
9
+ /** Skip Prettier formatting after generation. */
10
+ skipFormat?: boolean;
11
+ }
@@ -0,0 +1,34 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "$id": "NxArgoPreviewProjectGeneratorSchema",
4
+ "title": "GitOps preview project generator",
5
+ "description": "Create an Nx GitOps project for an explicit multi-workload preview stack.",
6
+ "type": "object",
7
+ "properties": {
8
+ "name": {
9
+ "type": "string",
10
+ "description": "Preview stack identity.",
11
+ "$default": { "source": "argv", "index": 0 },
12
+ "x-priority": "important"
13
+ },
14
+ "apps": {
15
+ "type": "array",
16
+ "description": "Nx workload projects intentionally included in this stack.",
17
+ "items": { "type": "string" },
18
+ "minItems": 1,
19
+ "x-priority": "important"
20
+ },
21
+ "directory": {
22
+ "type": "string",
23
+ "description": "Parent directory for preview stacks.",
24
+ "default": "gitops/previews"
25
+ },
26
+ "skipFormat": {
27
+ "type": "boolean",
28
+ "description": "Skip Prettier formatting after generation.",
29
+ "default": false
30
+ }
31
+ },
32
+ "required": ["name", "apps"],
33
+ "additionalProperties": false
34
+ }
package/src/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
- /** Public generator exports for the Argo CD package. */
2
- export { default as applicationGenerator } from './generators/application/application';
3
- export type { ApplicationGeneratorSchema } from './generators/application/schema';
1
+ /** Public generator and executor exports for the Argo CD package. */
2
+ export { default as environmentProjectGenerator } from './generators/environment-project/environment-project';
3
+ export type { EnvironmentProjectGeneratorSchema } from './generators/environment-project/schema';
4
+ export { default as previewProjectGenerator } from './generators/preview-project/preview-project';
5
+ export type { PreviewProjectGeneratorSchema } from './generators/preview-project/schema';
package/src/index.js CHANGED
@@ -3,7 +3,9 @@ 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.applicationGenerator = void 0;
7
- /** Public generator exports for the Argo CD package. */
8
- var application_1 = require("./generators/application/application");
9
- Object.defineProperty(exports, "applicationGenerator", { enumerable: true, get: function () { return __importDefault(application_1).default; } });
6
+ exports.previewProjectGenerator = exports.environmentProjectGenerator = void 0;
7
+ /** Public generator and executor exports for the Argo CD package. */
8
+ var environment_project_1 = require("./generators/environment-project/environment-project");
9
+ Object.defineProperty(exports, "environmentProjectGenerator", { enumerable: true, get: function () { return __importDefault(environment_project_1).default; } });
10
+ var preview_project_1 = require("./generators/preview-project/preview-project");
11
+ Object.defineProperty(exports, "previewProjectGenerator", { enumerable: true, get: function () { return __importDefault(preview_project_1).default; } });
@@ -1,9 +0,0 @@
1
- import { type Tree } from '@nx/devkit';
2
- import type { ApplicationGeneratorSchema } from './schema';
3
- /**
4
- * Creates a multi-source Argo CD Application and its Helm values file.
5
- * @param tree Workspace tree to update.
6
- * @param options Generator options supplied by Nx.
7
- * @returns A promise that resolves after optional formatting.
8
- */
9
- export default function applicationGenerator(tree: Tree, options: ApplicationGeneratorSchema): Promise<void>;
@@ -1,263 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = applicationGenerator;
4
- const devkit_1 = require("@nx/devkit");
5
- const node_path_1 = require("node:path");
6
- const semver_1 = require("semver");
7
- const yaml_1 = require("yaml");
8
- const applicationApiVersion = 'argoproj.io/v1alpha1';
9
- const defaultArgoNamespace = 'argocd';
10
- const valuesFileName = 'values.yaml';
11
- const valuesSourceRef = 'values';
12
- /**
13
- * Creates a multi-source Argo CD Application and its Helm values file.
14
- * @param tree Workspace tree to update.
15
- * @param options Generator options supplied by Nx.
16
- * @returns A promise that resolves after optional formatting.
17
- */
18
- async function applicationGenerator(tree, options) {
19
- const input = resolveInput(options);
20
- const applicationFile = (0, devkit_1.joinPathFragments)(input.directory, 'application.yaml');
21
- const valuesFile = (0, devkit_1.joinPathFragments)(input.directory, valuesFileName);
22
- if (tree.exists(applicationFile) || tree.exists(valuesFile)) {
23
- throw new Error(`[nx-argo] An Application already exists at ${input.directory}.`);
24
- }
25
- tree.write(applicationFile, createApplicationYaml(input));
26
- tree.write(valuesFile, createValuesYaml(input.applicationName));
27
- if (!options.skipFormat) {
28
- await (0, devkit_1.formatFiles)(tree);
29
- }
30
- }
31
- /**
32
- * Resolves and validates generator inputs.
33
- * @param options Generator options supplied by Nx.
34
- * @returns Normalized Application input.
35
- */
36
- function resolveInput(options) {
37
- const applicationName = getRequiredName(options.name, 'application name');
38
- const chartName = (0, devkit_1.names)(options.chart?.trim() || applicationName).fileName;
39
- const directory = normalizeDirectory(options.directory);
40
- const project = getRequiredString(options.project, 'Argo CD project');
41
- const destinationServer = getRequiredString(options.destinationServer, 'destination server');
42
- const namespace = getKubernetesName(options.namespace, 'namespace');
43
- const chartVersion = getSemver(options.chartVersion);
44
- const valuesRepoUrl = getValuesRepositoryUrl(options.valuesRepoUrl);
45
- const valuesRevision = getRequiredString(options.valuesRevision, 'values repository revision');
46
- const chartRepository = getChartRepositoryUrl(options.chartRepository);
47
- const argocdNamespace = options.argocdNamespace?.trim() || defaultArgoNamespace;
48
- const valuesPath = (0, devkit_1.joinPathFragments)(directory, valuesFileName);
49
- return {
50
- applicationName,
51
- argocdNamespace,
52
- chartName,
53
- chartRepository,
54
- chartVersion,
55
- destinationServer,
56
- directory,
57
- namespace,
58
- project,
59
- valuesPath,
60
- valuesRepoUrl,
61
- valuesRevision,
62
- };
63
- }
64
- /**
65
- * Renders a Helm chart source and a Git values source in one Application.
66
- * @param input Resolved Application source values.
67
- * @returns YAML Application manifest contents.
68
- */
69
- function createApplicationYaml(input) {
70
- const manifest = {
71
- apiVersion: applicationApiVersion,
72
- kind: 'Application',
73
- metadata: {
74
- name: input.applicationName,
75
- namespace: input.argocdNamespace,
76
- },
77
- spec: {
78
- project: input.project,
79
- sources: [
80
- {
81
- repoURL: input.chartRepository,
82
- chart: input.chartName,
83
- targetRevision: input.chartVersion,
84
- helm: {
85
- releaseName: input.chartName,
86
- valueFiles: [`$${valuesSourceRef}/${input.valuesPath}`],
87
- },
88
- },
89
- {
90
- repoURL: input.valuesRepoUrl,
91
- targetRevision: input.valuesRevision,
92
- ref: valuesSourceRef,
93
- },
94
- ],
95
- destination: {
96
- server: input.destinationServer,
97
- namespace: input.namespace,
98
- },
99
- },
100
- };
101
- return `# Generated Argo CD Application.\n${(0, yaml_1.stringify)(manifest, { lineWidth: 0 })}`;
102
- }
103
- /**
104
- * Creates the values document.
105
- * @param applicationName Application name used in the comment.
106
- * @returns Initial values.yaml contents.
107
- */
108
- function createValuesYaml(applicationName) {
109
- return `# Helm values for ${applicationName}.\n{}\n`;
110
- }
111
- /**
112
- * Requires a non-empty application name and normalizes it for Kubernetes.
113
- * @param value Raw name.
114
- * @param label Human-readable input label.
115
- * @returns Normalized name.
116
- */
117
- function getRequiredName(value, label) {
118
- const normalizedName = (0, devkit_1.names)(value?.trim() || '').fileName;
119
- if (!normalizedName) {
120
- throw new Error(`[nx-argo] A ${label} is required.`);
121
- }
122
- return normalizedName;
123
- }
124
- /**
125
- * Requires a non-empty string input.
126
- * @param value Raw input.
127
- * @param label Human-readable input label.
128
- * @returns Trimmed input.
129
- */
130
- function getRequiredString(value, label) {
131
- const normalizedValue = value?.trim();
132
- if (!normalizedValue) {
133
- throw new Error(`[nx-argo] A ${label} is required.`);
134
- }
135
- return normalizedValue;
136
- }
137
- /**
138
- * Validates an exact semantic chart version.
139
- * @param version Raw chart version.
140
- * @returns Valid semantic version.
141
- */
142
- function getSemver(version) {
143
- const normalizedVersion = getRequiredString(version, 'chart version');
144
- const parsedVersion = (0, semver_1.valid)(normalizedVersion);
145
- if (!parsedVersion || parsedVersion !== normalizedVersion) {
146
- throw new Error(`[nx-argo] Chart version must be an exact semantic version: ${version}`);
147
- }
148
- return normalizedVersion;
149
- }
150
- /**
151
- * Normalizes a workspace-relative output directory.
152
- * @param directory Raw output directory.
153
- * @returns POSIX workspace-relative directory.
154
- */
155
- function normalizeDirectory(directory) {
156
- const normalizedDirectory = trimTrailingSlashes(getRequiredString(directory, 'output directory')
157
- .split('\\')
158
- .join('/')
159
- .replace(/^\.\//, ''));
160
- if ((0, node_path_1.isAbsolute)(normalizedDirectory) ||
161
- normalizedDirectory === '..' ||
162
- normalizedDirectory.startsWith('../') ||
163
- normalizedDirectory.split('/').includes('..')) {
164
- throw new Error(`[nx-argo] Output directory must be workspace-relative: ${directory}`);
165
- }
166
- return normalizedDirectory;
167
- }
168
- /**
169
- * Validates a Kubernetes DNS label.
170
- * @param value Raw Kubernetes name.
171
- * @param label Human-readable input label.
172
- * @returns Valid Kubernetes name.
173
- */
174
- function getKubernetesName(value, label) {
175
- const normalizedName = getRequiredString(value, label);
176
- if (!isKubernetesName(normalizedName)) {
177
- throw new Error(`[nx-argo] ${label} is not a valid Kubernetes name: ${value}`);
178
- }
179
- return normalizedName;
180
- }
181
- /**
182
- * Converts a Helm repository input into Argo's Helm chart source syntax.
183
- * @param repositoryUrl Helm repository or OCI registry URL.
184
- * @returns Argo-compatible repository URL.
185
- */
186
- function getChartRepositoryUrl(repositoryUrl) {
187
- const normalizedUrl = trimTrailingSlashes(getRequiredString(repositoryUrl, 'chart repository URL'));
188
- if (normalizedUrl.toLowerCase().startsWith('oci://')) {
189
- return normalizedUrl.slice('oci://'.length);
190
- }
191
- if (hasHttpScheme(normalizedUrl)) {
192
- return normalizedUrl;
193
- }
194
- if (normalizedUrl.includes('://')) {
195
- throw new Error(`[nx-argo] Unsupported chart repository URL scheme: ${repositoryUrl}`);
196
- }
197
- return normalizedUrl;
198
- }
199
- /**
200
- * Requires an HTTPS Git repository for environment values.
201
- * @param repositoryUrl Git values repository URL.
202
- * @returns Normalized HTTPS repository URL.
203
- */
204
- function getValuesRepositoryUrl(repositoryUrl) {
205
- const normalizedUrl = trimTrailingSlashes(getRequiredString(repositoryUrl, 'values repository URL'));
206
- if (!normalizedUrl.toLowerCase().startsWith('https://')) {
207
- throw new Error('[nx-argo] Values repository URL must use https://.');
208
- }
209
- return normalizedUrl;
210
- }
211
- /**
212
- * Checks whether a repository URL uses HTTP or HTTPS.
213
- * @param value Repository URL to inspect.
214
- * @returns Whether the URL starts with an HTTP scheme.
215
- */
216
- function hasHttpScheme(value) {
217
- const normalizedValue = value.toLowerCase();
218
- return (normalizedValue.startsWith('http://') ||
219
- normalizedValue.startsWith('https://'));
220
- }
221
- /**
222
- * Checks the DNS label shape required for Kubernetes names.
223
- * @param value Name to inspect.
224
- * @returns Whether the value is a lowercase Kubernetes DNS label.
225
- */
226
- function isKubernetesName(value) {
227
- if (!value || value.length > 63) {
228
- return false;
229
- }
230
- if (!isLowercaseAlphaNumeric(value[0]) ||
231
- !isLowercaseAlphaNumeric(value[value.length - 1])) {
232
- return false;
233
- }
234
- for (const character of value) {
235
- if (!isLowercaseAlphaNumeric(character) && character !== '-') {
236
- return false;
237
- }
238
- }
239
- return true;
240
- }
241
- /**
242
- * Checks one lowercase ASCII alphanumeric character.
243
- * @param character Character to inspect.
244
- * @returns Whether the character is valid in a Kubernetes name boundary.
245
- */
246
- function isLowercaseAlphaNumeric(character) {
247
- return (typeof character === 'string' &&
248
- character.length === 1 &&
249
- ((character >= 'a' && character <= 'z') ||
250
- (character >= '0' && character <= '9')));
251
- }
252
- /**
253
- * Removes path separators from the end of a normalized path.
254
- * @param value Path value to normalize.
255
- * @returns Path without trailing separators.
256
- */
257
- function trimTrailingSlashes(value) {
258
- let end = value.length;
259
- while (end > 0 && value[end - 1] === '/') {
260
- end -= 1;
261
- }
262
- return value.slice(0, end);
263
- }
@@ -1,27 +0,0 @@
1
- /** Options accepted by the `@otwld/nx-argo:application` generator. */
2
- export interface ApplicationGeneratorSchema {
3
- /** Application metadata name. */
4
- name: string;
5
- /** Workspace-relative output directory for both generated files. */
6
- directory: string;
7
- /** Helm chart name; defaults to the application name. */
8
- chart?: string;
9
- /** Helm repository or OCI registry URL. */
10
- chartRepository: string;
11
- /** Exact semantic chart version. */
12
- chartVersion: string;
13
- /** HTTPS Git repository containing the generated values file. */
14
- valuesRepoUrl: string;
15
- /** Git revision containing the generated values file. */
16
- valuesRevision: string;
17
- /** Argo CD AppProject name. */
18
- project: string;
19
- /** Kubernetes API server URL. */
20
- destinationServer: string;
21
- /** Kubernetes namespace for the deployed chart. */
22
- namespace: string;
23
- /** Namespace where the Argo CD Application is created. */
24
- argocdNamespace?: string;
25
- /** Skip Prettier formatting after generation. */
26
- skipFormat?: boolean;
27
- }
@@ -1,97 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/schema",
3
- "$id": "NxArgoApplicationGeneratorSchema",
4
- "title": "Argo CD Application generator",
5
- "description": "Create a multi-source Argo CD Application and its Helm values file.",
6
- "type": "object",
7
- "properties": {
8
- "name": {
9
- "type": "string",
10
- "description": "Application metadata name.",
11
- "pattern": "^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$",
12
- "$default": {
13
- "$source": "argv",
14
- "index": 0
15
- },
16
- "x-prompt": "What is the Application name?",
17
- "x-priority": "important"
18
- },
19
- "directory": {
20
- "type": "string",
21
- "description": "Workspace-relative output directory for application.yaml and values.yaml.",
22
- "x-prompt": "Where should the Application files be generated?",
23
- "x-priority": "important"
24
- },
25
- "chart": {
26
- "type": "string",
27
- "description": "Helm chart name. Defaults to the Application name.",
28
- "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$"
29
- },
30
- "chartRepository": {
31
- "type": "string",
32
- "description": "HTTP(S) Helm repository or OCI registry URL.",
33
- "x-prompt": "What Helm repository or OCI registry contains the chart?",
34
- "x-priority": "important"
35
- },
36
- "chartVersion": {
37
- "type": "string",
38
- "description": "Exact semantic chart version.",
39
- "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$",
40
- "x-prompt": "What Helm chart version should Argo CD deploy?",
41
- "x-priority": "important"
42
- },
43
- "valuesRepoUrl": {
44
- "type": "string",
45
- "description": "HTTPS Git repository containing the generated values file.",
46
- "pattern": "^https://",
47
- "x-prompt": "What HTTPS Git repository contains the values file?",
48
- "x-priority": "important"
49
- },
50
- "valuesRevision": {
51
- "type": "string",
52
- "description": "Git revision containing the generated values file.",
53
- "x-prompt": "Which Git revision contains the values file?",
54
- "x-priority": "important"
55
- },
56
- "project": {
57
- "type": "string",
58
- "description": "Argo CD AppProject name.",
59
- "x-prompt": "Which Argo CD AppProject should own the Application?",
60
- "x-priority": "important"
61
- },
62
- "destinationServer": {
63
- "type": "string",
64
- "description": "Kubernetes API server URL.",
65
- "x-prompt": "Which Kubernetes API server should receive the Application?",
66
- "x-priority": "important"
67
- },
68
- "namespace": {
69
- "type": "string",
70
- "description": "Kubernetes namespace for the deployed chart.",
71
- "x-prompt": "Which Kubernetes namespace should receive the chart?",
72
- "x-priority": "important"
73
- },
74
- "argocdNamespace": {
75
- "type": "string",
76
- "description": "Namespace where the Argo CD Application is created.",
77
- "default": "argocd"
78
- },
79
- "skipFormat": {
80
- "type": "boolean",
81
- "description": "Skip Prettier formatting after the files are generated.",
82
- "default": false
83
- }
84
- },
85
- "required": [
86
- "name",
87
- "directory",
88
- "chartRepository",
89
- "chartVersion",
90
- "valuesRepoUrl",
91
- "valuesRevision",
92
- "project",
93
- "destinationServer",
94
- "namespace"
95
- ],
96
- "additionalProperties": false
97
- }