@otwld/nx-argo 0.0.8 → 0.0.9

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
@@ -19,6 +19,48 @@ pnpm exec nx g @otwld/nx-argo:preview-project web \
19
19
  --dependencies=frontend,backend --policy=github-pr-preview
20
20
  ```
21
21
 
22
+ `stack-project` creates one complete boundary at `gitops/<stack>`. It writes
23
+ staging and production Applications, stable staging/production/preview values,
24
+ and an optional GitHub pull-request ApplicationSet. The stack project declares
25
+ the chart and every mapped application as `implicitDependencies` and records the
26
+ delivery contract consumed by `@otwld/nx-delivery`. It also declares the four
27
+ `delivery:stack-*` targets; install `@otwld/nx-delivery` before invoking them:
28
+
29
+ ```shell
30
+ pnpm exec nx g @otwld/nx-argo:stack-project catalog \
31
+ --chartPath=charts/catalog --chartProject=helm-catalog \
32
+ --applications='{"services.api":"api","services.web":"web"}' \
33
+ --repository='{"owner":"acme","name":"catalog"}' \
34
+ --namespacePrefix=catalog --policy=github-pr-preview
35
+ ```
36
+
37
+ The canonical metadata shape is:
38
+
39
+ ```jsonc
40
+ {
41
+ "metadata": {
42
+ "delivery": {
43
+ "stack": {
44
+ "chartPath": "charts/catalog",
45
+ "values": {
46
+ "staging": "values-staging.yaml",
47
+ "production": "values-production.yaml",
48
+ "preview": "values-preview.yaml",
49
+ "pullRequest": "values-pr.yaml",
50
+ },
51
+ "applications": { "services.api": "api" },
52
+ },
53
+ },
54
+ },
55
+ }
56
+ ```
57
+
58
+ `applications` values are Nx project names and keys are dot-separated paths in
59
+ the generated values files. `chartPath`, repository identity, namespace prefix,
60
+ and all file paths are explicit; the generator does not assume a frontend,
61
+ backend, web, or repository name. The pull-request policy requires repository
62
+ owner/name and generates a `values-pr.yaml` final Helm value file.
63
+
22
64
  ## Contracts
23
65
 
24
66
  `validate-application` validates Application kind and spec. Its optional `finalValueFile` requires that basename to end each declared Helm `valueFiles` list; image locks are never implied.
package/generators.json CHANGED
@@ -10,6 +10,11 @@
10
10
  "factory": "./src/generators/preview-project/preview-project",
11
11
  "schema": "./src/generators/preview-project/schema.json",
12
12
  "description": "Create a GitOps project boundary for an explicit preview stack."
13
+ },
14
+ "stack-project": {
15
+ "factory": "./src/generators/stack-project/stack-project",
16
+ "schema": "./src/generators/stack-project/schema.json",
17
+ "description": "Create one generic GitOps boundary for a complete Helm stack."
13
18
  }
14
19
  }
15
20
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@otwld/nx-argo",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -59,7 +59,11 @@ function hasPrLockAsFinalValue(templateSpec) {
59
59
  const valueFiles = (0, shared_1.getPath)(source, ['helm', 'valueFiles']);
60
60
  return (Array.isArray(valueFiles) &&
61
61
  typeof valueFiles.at(-1) === 'string' &&
62
- valueFiles.at(-1).includes('/locks/pr-'));
62
+ isPullRequestValuesFile(valueFiles.at(-1)));
63
63
  });
64
64
  }
65
+ /** Accepts legacy lock snapshots and the flat stack values-pr contract. */
66
+ function isPullRequestValuesFile(valueFile) {
67
+ return valueFile.includes('/locks/pr-') || valueFile.includes('/values-pr');
68
+ }
65
69
  exports.default = runExecutor;
@@ -0,0 +1,55 @@
1
+ /** Repository identity used by generated Argo sources and preview generators. */
2
+ export interface StackRepository {
3
+ /** Full Git repository URL. */
4
+ url?: string;
5
+ /** GitHub owner used by the optional pull-request generator. */
6
+ owner?: string;
7
+ /** GitHub repository name used by the optional pull-request generator. */
8
+ name?: string;
9
+ /** Branch or revision used by the stable Applications. */
10
+ revision?: string;
11
+ }
12
+
13
+ /** Explicit value-file paths owned by the generated stack project. */
14
+ export interface StackValueFiles {
15
+ /** Staging value file relative to the GitOps project. */
16
+ staging?: string;
17
+ /** Production value file relative to the GitOps project. */
18
+ production?: string;
19
+ /** Preview base value file relative to the GitOps project. */
20
+ preview?: string;
21
+ /** Pull-request value-file pattern relative to the GitOps project. */
22
+ pullRequest?: string;
23
+ }
24
+
25
+ /** Options accepted by the generic GitOps stack project generator. */
26
+ export interface StackProjectGeneratorSchema {
27
+ /** Stack identity and generated directory suffix. */
28
+ name: string;
29
+ /** Workspace-relative Helm chart path used by generated Argo sources. */
30
+ chartPath: string;
31
+ /** Nx project name for the Helm chart. */
32
+ chartProject: string;
33
+ /** Values-key to Nx project mapping for direct stack image dependencies. */
34
+ applications: Record<string, string>;
35
+ /** Git repository identity used by generated Argo sources. */
36
+ repository: StackRepository | string;
37
+ /** Namespace prefix used for stable and pull-request destinations. */
38
+ namespacePrefix: string;
39
+ /** Explicit project-local values paths. */
40
+ values?: StackValueFiles;
41
+ /** Argo CD project assigned to generated Applications. */
42
+ argoProject?: string;
43
+ /** Optional ApplicationSet policy for GitHub pull-request previews. */
44
+ policy?: 'github-pr-preview';
45
+ /** GitHub token secret name used by the optional preview generator. */
46
+ githubTokenSecretName?: string;
47
+ /** GitHub token secret key used by the optional preview generator. */
48
+ githubTokenSecretKey?: string;
49
+ /** Pull-request label required by the optional preview generator. */
50
+ previewLabel?: string;
51
+ /** ApplicationSet pull-request polling interval in seconds. */
52
+ requeueAfterSeconds?: number;
53
+ /** Skip Prettier formatting after generation. */
54
+ skipFormat?: boolean;
55
+ }
@@ -0,0 +1,110 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "$id": "NxArgoStackProjectGeneratorSchema",
4
+ "title": "GitOps stack project generator",
5
+ "description": "Create one generic GitOps boundary for a Helm application stack.",
6
+ "type": "object",
7
+ "properties": {
8
+ "name": {
9
+ "type": "string",
10
+ "description": "Stack identity and generated directory suffix.",
11
+ "$default": { "source": "argv", "index": 0 },
12
+ "x-priority": "important"
13
+ },
14
+ "chartPath": {
15
+ "type": "string",
16
+ "description": "Workspace-relative Helm chart path used by Argo sources.",
17
+ "x-priority": "important"
18
+ },
19
+ "chartProject": {
20
+ "type": "string",
21
+ "description": "Nx project name for the Helm chart.",
22
+ "x-priority": "important"
23
+ },
24
+ "applications": {
25
+ "type": "object",
26
+ "description": "Values-key to Nx project mapping for stack image dependencies.",
27
+ "minProperties": 1,
28
+ "additionalProperties": { "type": "string", "minLength": 1 },
29
+ "x-priority": "important"
30
+ },
31
+ "repository": {
32
+ "description": "Repository URL or identity object used by Argo sources.",
33
+ "oneOf": [
34
+ { "type": "string", "minLength": 1 },
35
+ {
36
+ "type": "object",
37
+ "properties": {
38
+ "url": { "type": "string", "minLength": 1 },
39
+ "owner": { "type": "string", "minLength": 1 },
40
+ "name": { "type": "string", "minLength": 1 },
41
+ "revision": { "type": "string", "minLength": 1 }
42
+ },
43
+ "additionalProperties": false,
44
+ "minProperties": 1
45
+ }
46
+ ],
47
+ "x-priority": "important"
48
+ },
49
+ "namespacePrefix": {
50
+ "type": "string",
51
+ "description": "Namespace prefix for stable and pull-request destinations.",
52
+ "x-priority": "important"
53
+ },
54
+ "values": {
55
+ "type": "object",
56
+ "description": "Optional project-relative value-file paths.",
57
+ "properties": {
58
+ "staging": { "type": "string", "minLength": 1 },
59
+ "production": { "type": "string", "minLength": 1 },
60
+ "preview": { "type": "string", "minLength": 1 },
61
+ "pullRequest": { "type": "string", "minLength": 1 }
62
+ },
63
+ "additionalProperties": false
64
+ },
65
+ "argoProject": {
66
+ "type": "string",
67
+ "description": "Argo CD project assigned to generated Applications.",
68
+ "default": "default"
69
+ },
70
+ "policy": {
71
+ "type": "string",
72
+ "enum": ["github-pr-preview"],
73
+ "description": "Optional GitHub pull-request preview policy."
74
+ },
75
+ "githubTokenSecretName": {
76
+ "type": "string",
77
+ "description": "GitHub token secret name for the preview generator."
78
+ },
79
+ "githubTokenSecretKey": {
80
+ "type": "string",
81
+ "description": "GitHub token secret key for the preview generator.",
82
+ "default": "token"
83
+ },
84
+ "previewLabel": {
85
+ "type": "string",
86
+ "description": "Pull-request label required for preview generation.",
87
+ "default": "preview-ready"
88
+ },
89
+ "requeueAfterSeconds": {
90
+ "type": "integer",
91
+ "minimum": 1,
92
+ "description": "ApplicationSet pull-request polling interval in seconds.",
93
+ "default": 1800
94
+ },
95
+ "skipFormat": {
96
+ "type": "boolean",
97
+ "description": "Skip Prettier formatting after generation.",
98
+ "default": false
99
+ }
100
+ },
101
+ "required": [
102
+ "name",
103
+ "chartPath",
104
+ "chartProject",
105
+ "applications",
106
+ "repository",
107
+ "namespacePrefix"
108
+ ],
109
+ "additionalProperties": false
110
+ }
@@ -0,0 +1,4 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { StackProjectGeneratorSchema } from './schema';
3
+ /** Creates one generic GitOps project boundary for a complete Helm stack. */
4
+ export default function stackProjectGenerator(tree: Tree, options: StackProjectGeneratorSchema): Promise<void>;
@@ -0,0 +1,428 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = stackProjectGenerator;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const yaml_1 = require("yaml");
6
+ const defaultValues = {
7
+ staging: 'values-staging.yaml',
8
+ production: 'values-production.yaml',
9
+ preview: 'values-preview.yaml',
10
+ pullRequest: 'values-pr.yaml',
11
+ };
12
+ /** Creates one generic GitOps project boundary for a complete Helm stack. */
13
+ async function stackProjectGenerator(tree, options) {
14
+ const stack = normalizeName(options.name, 'name');
15
+ const chartPath = normalizeRelativePath(options.chartPath, 'chartPath');
16
+ const chartProject = requireValue(options.chartProject, 'chartProject');
17
+ const namespacePrefix = normalizeName(options.namespacePrefix, 'namespacePrefix');
18
+ const applications = normalizeApplications(options.applications);
19
+ const repository = normalizeRepository(options.repository);
20
+ const values = normalizeValues(options.values);
21
+ const directory = (0, devkit_1.joinPathFragments)('gitops', stack);
22
+ const projectFile = (0, devkit_1.joinPathFragments)(directory, 'project.json');
23
+ if (tree.exists(projectFile)) {
24
+ throw new Error(`[nx-argo] A GitOps stack project already exists at ${directory}.`);
25
+ }
26
+ if (options.policy && (!repository.owner || !repository.name)) {
27
+ throw new Error('[nx-argo] github-pr-preview requires repository.owner and repository.name.');
28
+ }
29
+ const generatedFiles = getGeneratedFiles(directory, stack, chartPath, namespacePrefix, repository, values, applications, options);
30
+ const validationTargets = getValidationTargets(generatedFiles, options);
31
+ (0, devkit_1.writeJson)(tree, projectFile, {
32
+ name: `gitops-${stack}`,
33
+ root: directory,
34
+ projectType: 'application',
35
+ tags: ['type:gitops', `stack:${stack}`],
36
+ implicitDependencies: [
37
+ ...new Set([chartProject, ...Object.values(applications)]),
38
+ ],
39
+ metadata: {
40
+ delivery: {
41
+ stack: {
42
+ chartPath,
43
+ values,
44
+ applications,
45
+ },
46
+ },
47
+ },
48
+ targets: {
49
+ validate: {
50
+ executor: 'nx:noop',
51
+ dependsOn: [
52
+ ...Object.keys(validationTargets),
53
+ `${chartProject}:helm:validate`,
54
+ ],
55
+ },
56
+ ...validationTargets,
57
+ 'delivery:stack-stage': {
58
+ executor: '@otwld/nx-delivery:stack-stage',
59
+ cache: false,
60
+ },
61
+ 'delivery:stack-promote': {
62
+ executor: '@otwld/nx-delivery:stack-promote',
63
+ cache: false,
64
+ },
65
+ 'delivery:stack-preview': {
66
+ executor: '@otwld/nx-delivery:stack-preview',
67
+ cache: false,
68
+ },
69
+ 'delivery:stack-snapshot': {
70
+ executor: '@otwld/nx-delivery:stack-snapshot',
71
+ cache: false,
72
+ },
73
+ },
74
+ });
75
+ for (const [file, content] of Object.entries(generatedFiles.files)) {
76
+ tree.write(file, content);
77
+ }
78
+ updateKustomization(tree, generatedFiles);
79
+ if (!options.skipFormat) {
80
+ await (0, devkit_1.formatFiles)(tree);
81
+ }
82
+ }
83
+ /** Registers generated Argo resources in the workspace GitOps catalog. */
84
+ function updateKustomization(tree, generatedFiles) {
85
+ const file = 'gitops/kustomization.yaml';
86
+ const document = tree.exists(file)
87
+ ? (0, yaml_1.parse)(tree.read(file, 'utf8') ?? '')
88
+ : {
89
+ apiVersion: 'kustomize.config.k8s.io/v1beta1',
90
+ kind: 'Kustomization',
91
+ resources: [],
92
+ };
93
+ if (!isRecord(document)) {
94
+ throw new Error(`[nx-argo] Invalid Kustomization: ${file}`);
95
+ }
96
+ const resources = Array.isArray(document['resources'])
97
+ ? document['resources'].filter((resource) => typeof resource === 'string')
98
+ : [];
99
+ const generatedResources = [
100
+ ...Object.values(generatedFiles.applicationFiles),
101
+ ...(generatedFiles.applicationSetFile
102
+ ? [generatedFiles.applicationSetFile]
103
+ : []),
104
+ ].map((resource) => resource.replace(/^gitops\//, ''));
105
+ document['resources'] = [...new Set([...resources, ...generatedResources])];
106
+ tree.write(file, (0, yaml_1.stringify)(document, { lineWidth: 0 }));
107
+ }
108
+ /** Builds all Argo manifests and stable value files owned by the boundary. */
109
+ function getGeneratedFiles(directory, stack, chartPath, namespacePrefix, repository, values, applications, options) {
110
+ const applicationFiles = {
111
+ staging: (0, devkit_1.joinPathFragments)(directory, 'application-staging.yaml'),
112
+ production: (0, devkit_1.joinPathFragments)(directory, 'application-production.yaml'),
113
+ };
114
+ const files = {
115
+ [applicationFiles.staging]: (0, yaml_1.stringify)(createApplication(stack, 'staging', chartPath, namespacePrefix, repository, values.staging, directory, options.argoProject), { lineWidth: 0 }),
116
+ [applicationFiles.production]: (0, yaml_1.stringify)(createApplication(stack, 'production', chartPath, namespacePrefix, repository, values.production, directory, options.argoProject), { lineWidth: 0 }),
117
+ };
118
+ for (const environment of ['staging', 'production', 'preview']) {
119
+ files[(0, devkit_1.joinPathFragments)(directory, values[environment])] = (0, yaml_1.stringify)(createValues(applications, environment), { lineWidth: 0 });
120
+ }
121
+ if (!values.pullRequest.includes('{{')) {
122
+ files[(0, devkit_1.joinPathFragments)(directory, values.pullRequest)] = (0, yaml_1.stringify)(createValues(applications, 'preview'), { lineWidth: 0 });
123
+ }
124
+ let applicationSetFile;
125
+ if (options.policy === 'github-pr-preview') {
126
+ applicationSetFile = (0, devkit_1.joinPathFragments)(directory, 'application-set.yaml');
127
+ files[applicationSetFile] = (0, yaml_1.stringify)(createApplicationSet(stack, chartPath, namespacePrefix, repository, values.pullRequest, directory, options), { lineWidth: 0 });
128
+ }
129
+ return { applicationFiles, applicationSetFile, files };
130
+ }
131
+ /** Creates one stable Argo CD Application for an environment value file. */
132
+ function createApplication(stack, environment, chartPath, namespacePrefix, repository, valuesFile, directory, argoProject = 'default') {
133
+ const repositoryUrl = repository.url;
134
+ const repositoryRevision = repository.revision;
135
+ const gitopsValuesPath = (0, devkit_1.joinPathFragments)(directory, valuesFile);
136
+ return {
137
+ apiVersion: 'argoproj.io/v1alpha1',
138
+ kind: 'Application',
139
+ metadata: {
140
+ name: `${stack}-${environment}`,
141
+ namespace: 'argocd',
142
+ },
143
+ spec: {
144
+ project: argoProject,
145
+ sources: [
146
+ {
147
+ repoURL: repositoryUrl,
148
+ targetRevision: repositoryRevision,
149
+ path: chartPath,
150
+ helm: { valueFiles: [`$values/${gitopsValuesPath}`] },
151
+ },
152
+ {
153
+ repoURL: repositoryUrl,
154
+ targetRevision: repositoryRevision,
155
+ ref: 'values',
156
+ },
157
+ ],
158
+ destination: {
159
+ server: 'https://kubernetes.default.svc',
160
+ namespace: `${namespacePrefix}-${environment}`,
161
+ },
162
+ syncPolicy: {
163
+ syncOptions: ['CreateNamespace=true'],
164
+ managedNamespaceMetadata: {
165
+ labels: { 'delivery.otwld.com/managed': 'true' },
166
+ },
167
+ automated: { enabled: true, prune: true, selfHeal: true },
168
+ },
169
+ },
170
+ };
171
+ }
172
+ /** Creates the optional generic GitHub pull-request ApplicationSet. */
173
+ function createApplicationSet(stack, chartPath, namespacePrefix, repository, valuesFile, directory, options) {
174
+ const repositoryUrl = repository.url;
175
+ const secretName = options.githubTokenSecretName?.trim() || `argocd-github-${stack}`;
176
+ const secretKey = options.githubTokenSecretKey?.trim() || 'token';
177
+ const previewLabel = options.previewLabel?.trim() || 'preview-ready';
178
+ const revision = options.requeueAfterSeconds ?? 1800;
179
+ const gitopsValuesPath = (0, devkit_1.joinPathFragments)(directory, valuesFile);
180
+ return {
181
+ apiVersion: 'argoproj.io/v1alpha1',
182
+ kind: 'ApplicationSet',
183
+ metadata: { name: `${stack}-preview`, namespace: 'argocd' },
184
+ spec: {
185
+ goTemplate: true,
186
+ goTemplateOptions: ['missingkey=error'],
187
+ generators: [
188
+ {
189
+ matrix: {
190
+ generators: [
191
+ {
192
+ pullRequest: {
193
+ github: {
194
+ owner: repository.owner,
195
+ repo: repository.name,
196
+ tokenRef: { secretName, key: secretKey },
197
+ labels: [previewLabel],
198
+ },
199
+ requeueAfterSeconds: revision,
200
+ },
201
+ },
202
+ {
203
+ git: {
204
+ repoURL: repositoryUrl,
205
+ revision: 'preview/pr-{{ .number }}',
206
+ files: [{ path: gitopsValuesPath }],
207
+ },
208
+ },
209
+ ],
210
+ },
211
+ },
212
+ ],
213
+ template: {
214
+ metadata: {
215
+ name: `${stack}-pr-{{ .number }}`,
216
+ finalizers: ['resources-finalizer.argocd.argoproj.io'],
217
+ labels: {
218
+ 'app.kubernetes.io/part-of': stack,
219
+ 'delivery.otwld.com/preview': stack,
220
+ 'delivery.otwld.com/pull-request': '{{ .number }}',
221
+ },
222
+ },
223
+ spec: {
224
+ project: options.argoProject?.trim() || 'default',
225
+ sources: [
226
+ {
227
+ repoURL: repositoryUrl,
228
+ targetRevision: '{{ .global.sourceRevision }}',
229
+ path: chartPath,
230
+ helm: {
231
+ valueFiles: [`$values/${gitopsValuesPath}`],
232
+ parameters: [
233
+ { name: 'global.previewId', value: 'pr-{{ .number }}' },
234
+ ],
235
+ },
236
+ },
237
+ {
238
+ repoURL: repositoryUrl,
239
+ targetRevision: 'preview/pr-{{ .number }}',
240
+ ref: 'values',
241
+ },
242
+ ],
243
+ destination: {
244
+ server: 'https://kubernetes.default.svc',
245
+ namespace: `${namespacePrefix}-pr-{{ .number }}`,
246
+ },
247
+ syncPolicy: {
248
+ managedNamespaceMetadata: {
249
+ labels: { 'delivery.otwld.com/managed': 'true' },
250
+ annotations: {
251
+ 'argocd.argoproj.io/tracking-id': `${stack}-pr-{{ .number }}:/Namespace:/${namespacePrefix}-pr-{{ .number }}`,
252
+ },
253
+ },
254
+ syncOptions: ['CreateNamespace=true'],
255
+ automated: { enabled: true, prune: true, selfHeal: true },
256
+ retry: {
257
+ limit: 3,
258
+ backoff: { duration: '5s', factor: 2, maxDuration: '3m' },
259
+ },
260
+ },
261
+ },
262
+ },
263
+ },
264
+ };
265
+ }
266
+ /** Creates one image-value skeleton for every mapped application. */
267
+ function createValues(applications, environment) {
268
+ const values = {
269
+ global: { environment, sourceRevision: '' },
270
+ };
271
+ for (const [valuesKey, project] of Object.entries(applications)) {
272
+ setPath(values, parseValuePath(valuesKey), {
273
+ project,
274
+ image: { repository: '', digest: '' },
275
+ });
276
+ }
277
+ return values;
278
+ }
279
+ /** Declares Argo validation targets for generated manifests. */
280
+ function getValidationTargets(files, options) {
281
+ const targets = {
282
+ 'validate-application-staging': {
283
+ executor: '@otwld/nx-argo:validate-application',
284
+ options: { file: relativeToProject(files.applicationFiles.staging) },
285
+ },
286
+ 'validate-application-production': {
287
+ executor: '@otwld/nx-argo:validate-application',
288
+ options: { file: relativeToProject(files.applicationFiles.production) },
289
+ },
290
+ };
291
+ if (options.policy === 'github-pr-preview' && files.applicationSetFile) {
292
+ targets['validate-application-set'] = {
293
+ executor: '@otwld/nx-argo:validate-application-set',
294
+ options: {
295
+ file: relativeToProject(files.applicationSetFile),
296
+ policy: options.policy,
297
+ },
298
+ };
299
+ }
300
+ return targets;
301
+ }
302
+ /** Converts a generated project path into its project-relative target option. */
303
+ function relativeToProject(path) {
304
+ const marker = path.indexOf('gitops/');
305
+ if (marker < 0) {
306
+ throw new Error(`[nx-argo] Generated project path is invalid: ${path}`);
307
+ }
308
+ const projectPath = path.slice(marker);
309
+ const slash = projectPath.indexOf('/');
310
+ return slash < 0
311
+ ? ''
312
+ : projectPath.slice(projectPath.indexOf('/', slash + 1) + 1);
313
+ }
314
+ /** Normalizes a repository URL or owner/name identity object. */
315
+ function normalizeRepository(value) {
316
+ if (typeof value === 'string') {
317
+ const url = requireValue(value, 'repository');
318
+ const identity = parseGitHubIdentity(url);
319
+ return { ...identity, url, revision: 'main' };
320
+ }
321
+ if (!value || typeof value !== 'object') {
322
+ throw new Error('[nx-argo] A repository URL or identity is required.');
323
+ }
324
+ const owner = readValue(value.owner);
325
+ const name = readValue(value.name);
326
+ const url = readValue(value.url) ||
327
+ (owner && name ? `https://github.com/${owner}/${name}.git` : undefined);
328
+ if (!url) {
329
+ throw new Error('[nx-argo] repository.url or repository.owner/name is required.');
330
+ }
331
+ return {
332
+ url,
333
+ ...(owner ? { owner } : {}),
334
+ ...(name ? { name } : {}),
335
+ revision: readValue(value.revision) || 'main',
336
+ };
337
+ }
338
+ /** Derives GitHub owner/name values when a GitHub URL is supplied. */
339
+ function parseGitHubIdentity(url) {
340
+ const match = url.match(/github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?$/i);
341
+ return match ? { owner: match[1], name: match[2] } : {};
342
+ }
343
+ /** Normalizes project-local values paths while preserving the PR template. */
344
+ function normalizeValues(value) {
345
+ const normalized = {
346
+ ...defaultValues,
347
+ ...value,
348
+ };
349
+ for (const [key, path] of Object.entries(normalized)) {
350
+ normalized[key] = normalizeRelativePath(path, `values.${key}`);
351
+ }
352
+ return normalized;
353
+ }
354
+ /** Normalizes values-key mappings without inventing project names. */
355
+ function normalizeApplications(value) {
356
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
357
+ throw new Error('[nx-argo] applications must map values keys to Nx projects.');
358
+ }
359
+ const applications = {};
360
+ for (const [valuesKey, project] of Object.entries(value)) {
361
+ const key = parseValuePath(valuesKey).join('.');
362
+ applications[key] = requireValue(project, `applications.${key}`);
363
+ }
364
+ if (Object.keys(applications).length === 0) {
365
+ throw new Error('[nx-argo] At least one application mapping is required.');
366
+ }
367
+ return applications;
368
+ }
369
+ /** Parses a dot-separated values mapping path. */
370
+ function parseValuePath(value) {
371
+ const segments = value.split('.').map((segment) => segment.trim());
372
+ if (!value.trim() ||
373
+ segments.some((segment) => !segment ||
374
+ segment === '..' ||
375
+ segment.includes('/') ||
376
+ segment.includes('\\'))) {
377
+ throw new Error(`[nx-argo] Invalid values key: ${value}`);
378
+ }
379
+ return segments;
380
+ }
381
+ /** Sets a nested mapping path for generated values. */
382
+ function setPath(root, path, value) {
383
+ let current = root;
384
+ for (const segment of path.slice(0, -1)) {
385
+ const child = current[segment];
386
+ if (child === undefined) {
387
+ current[segment] = {};
388
+ }
389
+ else if (!isRecord(child)) {
390
+ throw new Error(`[nx-argo] Values key conflicts at ${segment}.`);
391
+ }
392
+ current = current[segment];
393
+ }
394
+ current[path.at(-1)] = value;
395
+ }
396
+ /** Narrows a generated value to a mapping. */
397
+ function isRecord(value) {
398
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
399
+ }
400
+ /** Normalizes a project or namespace identifier. */
401
+ function normalizeName(value, label) {
402
+ const normalized = (0, devkit_1.names)(requireValue(value, label)).fileName;
403
+ if (!normalized) {
404
+ throw new Error(`[nx-argo] A ${label} is required.`);
405
+ }
406
+ return normalized;
407
+ }
408
+ /** Validates a project-relative path without allowing escapes. */
409
+ function normalizeRelativePath(value, label) {
410
+ const normalized = requireValue(value, label).replaceAll('\\', '/');
411
+ if (normalized.startsWith('/') ||
412
+ normalized.split('/').some((segment) => segment === '..' || !segment)) {
413
+ throw new Error(`[nx-argo] ${label} must stay within the project root.`);
414
+ }
415
+ return normalized;
416
+ }
417
+ /** Requires a non-empty string scalar. */
418
+ function requireValue(value, label) {
419
+ const normalized = value?.trim();
420
+ if (!normalized) {
421
+ throw new Error(`[nx-argo] A ${label} is required.`);
422
+ }
423
+ return normalized;
424
+ }
425
+ /** Returns a trimmed optional string. */
426
+ function readValue(value) {
427
+ return value?.trim() || undefined;
428
+ }
package/src/index.d.ts CHANGED
@@ -3,6 +3,8 @@ 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 stackProjectGenerator } from './generators/stack-project/stack-project';
7
+ export type { StackProjectGeneratorSchema, StackRepository, StackValueFiles, } from './generators/stack-project/schema';
6
8
  export { default as validateApplication } from './executors/validate-application/validate-application';
7
9
  export type { ValidateApplicationExecutorSchema } from './executors/validate-application/schema';
8
10
  export { default as validateApplicationSet } from './executors/validate-application-set/validate-application-set';
package/src/index.js CHANGED
@@ -3,12 +3,14 @@ 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.copySourceRevision = exports.setSourceRevision = exports.copyImageLock = exports.writeImageLock = exports.validateImageLock = exports.validateApplicationSet = exports.validateApplication = exports.previewProjectGenerator = exports.environmentProjectGenerator = void 0;
6
+ exports.copySourceRevision = exports.setSourceRevision = exports.copyImageLock = exports.writeImageLock = exports.validateImageLock = exports.validateApplicationSet = exports.validateApplication = exports.stackProjectGenerator = 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 stack_project_1 = require("./generators/stack-project/stack-project");
13
+ Object.defineProperty(exports, "stackProjectGenerator", { enumerable: true, get: function () { return __importDefault(stack_project_1).default; } });
12
14
  var validate_application_1 = require("./executors/validate-application/validate-application");
13
15
  Object.defineProperty(exports, "validateApplication", { enumerable: true, get: function () { return __importDefault(validate_application_1).default; } });
14
16
  var validate_application_set_1 = require("./executors/validate-application-set/validate-application-set");