@aws/nx-plugin 1.0.0-rc.89 → 1.0.0-rc.90
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 +22 -22
- package/executors.json +5 -0
- package/generators.json +2 -1
- package/migrations.json +47 -2
- package/package.json +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +24 -12
- package/src/infra/app/generator.js +9 -7
- package/src/infra/app/generator.js.map +1 -1
- package/src/mcp-server/generator-info.d.ts +5 -0
- package/src/mcp-server/generator-info.js +6 -2
- package/src/mcp-server/generator-info.js.map +1 -1
- package/src/migrations/latest/add-assemble-target/metadata.json +3 -0
- package/src/migrations/latest/add-assemble-target/migration.d.ts +6 -0
- package/src/migrations/latest/add-assemble-target/migration.js +241 -0
- package/src/migrations/latest/add-assemble-target/migration.js.map +1 -0
- package/src/migrations/latest/declare-cacheable-target-inputs/metadata.json +3 -0
- package/src/migrations/latest/declare-cacheable-target-inputs/migration.d.ts +6 -0
- package/src/migrations/latest/declare-cacheable-target-inputs/migration.js +94 -0
- package/src/migrations/latest/declare-cacheable-target-inputs/migration.js.map +1 -0
- package/src/migrations/latest/dev-target-depends-on-pull-image/metadata.json +3 -0
- package/src/migrations/latest/dev-target-depends-on-pull-image/migration.d.ts +6 -0
- package/src/migrations/latest/dev-target-depends-on-pull-image/migration.js +67 -0
- package/src/migrations/latest/dev-target-depends-on-pull-image/migration.js.map +1 -0
- package/src/migrations/latest/docker-target-cache-soundness/metadata.json +3 -0
- package/src/migrations/latest/docker-target-cache-soundness/migration.d.ts +6 -0
- package/src/migrations/latest/docker-target-cache-soundness/migration.js +95 -0
- package/src/migrations/latest/docker-target-cache-soundness/migration.js.map +1 -0
- package/src/migrations/latest/open-api-codegen-executor/metadata.json +3 -0
- package/src/migrations/latest/open-api-codegen-executor/migration.d.ts +6 -0
- package/src/migrations/latest/open-api-codegen-executor/migration.js +100 -0
- package/src/migrations/latest/open-api-codegen-executor/migration.js.map +1 -0
- package/src/migrations/latest/python-test-input-scoping/metadata.json +3 -0
- package/src/migrations/latest/python-test-input-scoping/migration.d.ts +6 -0
- package/src/migrations/latest/python-test-input-scoping/migration.js +142 -0
- package/src/migrations/latest/python-test-input-scoping/migration.js.map +1 -0
- package/src/migrations/latest/terraform-fmt-check/metadata.json +3 -0
- package/src/migrations/latest/terraform-fmt-check/migration.d.ts +6 -0
- package/src/migrations/latest/terraform-fmt-check/migration.js +165 -0
- package/src/migrations/latest/terraform-fmt-check/migration.js.map +1 -0
- package/src/migrations/latest/terraform-provider-plugin-cache/metadata.json +3 -0
- package/src/migrations/latest/terraform-provider-plugin-cache/migration.d.ts +6 -0
- package/src/migrations/latest/terraform-provider-plugin-cache/migration.js +164 -0
- package/src/migrations/latest/terraform-provider-plugin-cache/migration.js.map +1 -0
- package/src/migrations/latest/vitest-coverage-output-dir/metadata.json +3 -0
- package/src/migrations/latest/vitest-coverage-output-dir/migration.d.ts +6 -0
- package/src/migrations/latest/vitest-coverage-output-dir/migration.js +177 -0
- package/src/migrations/latest/vitest-coverage-output-dir/migration.js.map +1 -0
- package/src/open-api/codegen/executor-schema.d.js +6 -0
- package/src/open-api/codegen/executor-schema.d.js.map +1 -0
- package/src/open-api/codegen/executor-schema.d.ts +18 -0
- package/src/open-api/codegen/executor-schema.json +33 -0
- package/src/open-api/codegen/executor.d.ts +18 -0
- package/src/open-api/codegen/executor.js +56 -0
- package/src/open-api/codegen/executor.js.map +1 -0
- package/src/preset/__snapshots__/generator.spec.ts.snap +2 -1
- package/src/py/agent/generator.js +21 -22
- package/src/py/agent/generator.js.map +1 -1
- package/src/py/agent/react-connection/generator.js +9 -0
- package/src/py/agent/react-connection/generator.js.map +1 -1
- package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +0 -30
- package/src/py/fast-api/react/open-api.js +19 -7
- package/src/py/fast-api/react/open-api.js.map +1 -1
- package/src/py/mcp-server/generator.js +4 -4
- package/src/py/mcp-server/generator.js.map +1 -1
- package/src/py/project/generator.d.ts +9 -0
- package/src/py/project/generator.js +51 -1
- package/src/py/project/generator.js.map +1 -1
- package/src/py/rdb/generator.js +10 -4
- package/src/py/rdb/generator.js.map +1 -1
- package/src/smithy/project/__snapshots__/generator.spec.ts.snap +15 -0
- package/src/smithy/project/generator.js +10 -0
- package/src/smithy/project/generator.js.map +1 -1
- package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +7 -0
- package/src/terraform/project/files/application/scripts/env.ts.template +11 -0
- package/src/terraform/project/files/application/scripts/init.ts.template +2 -1
- package/src/terraform/project/files/application/src/providers.tf.template +2 -2
- package/src/terraform/project/generator.d.ts +11 -1
- package/src/terraform/project/generator.js +104 -20
- package/src/terraform/project/generator.js.map +1 -1
- package/src/trpc/backend/generator.js +2 -2
- package/src/trpc/backend/generator.js.map +1 -1
- package/src/ts/agent/generator.js +4 -7
- package/src/ts/agent/generator.js.map +1 -1
- package/src/ts/astro-docs/generator.js +5 -0
- package/src/ts/astro-docs/generator.js.map +1 -1
- package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +0 -30
- package/src/ts/dynamodb/generator.js +3 -0
- package/src/ts/dynamodb/generator.js.map +1 -1
- package/src/ts/lib/__snapshots__/generator.spec.ts.snap +10 -1
- package/src/ts/lib/__snapshots__/vitest.spec.ts.snap +1 -1
- package/src/ts/lib/generator.d.ts +16 -0
- package/src/ts/lib/generator.js +31 -5
- package/src/ts/lib/generator.js.map +1 -1
- package/src/ts/lib/vitest.d.ts +11 -0
- package/src/ts/lib/vitest.js +31 -2
- package/src/ts/lib/vitest.js.map +1 -1
- package/src/ts/mcp-server/generator.js +4 -7
- package/src/ts/mcp-server/generator.js.map +1 -1
- package/src/ts/rdb/generator.js +8 -5
- package/src/ts/rdb/generator.js.map +1 -1
- package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +27 -11
- package/src/ts/react-website/app/generator.js +9 -1
- package/src/ts/react-website/app/generator.js.map +1 -1
- package/src/ts/sync/generator.js +19 -2
- package/src/ts/sync/generator.js.map +1 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js +3 -3
- package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
- package/src/utils/api-constructs/api-constructs.js +2 -2
- package/src/utils/api-constructs/api-constructs.js.map +1 -1
- package/src/utils/api-constructs/open-api-metadata.js +15 -36
- package/src/utils/api-constructs/open-api-metadata.js.map +1 -1
- package/src/utils/api-constructs/trpc-operations-metadata.js +9 -3
- package/src/utils/api-constructs/trpc-operations-metadata.js.map +1 -1
- package/src/utils/bundle/bundle.js +13 -4
- package/src/utils/bundle/bundle.js.map +1 -1
- package/src/utils/connection/open-api/react.js +7 -17
- package/src/utils/connection/open-api/react.js.map +1 -1
- package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js +2 -2
- package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js.map +1 -1
- package/src/utils/docker.d.ts +22 -10
- package/src/utils/docker.js +27 -17
- package/src/utils/docker.js.map +1 -1
- package/src/utils/dynamodb-constructs/dynamodb-constructs.js +2 -2
- package/src/utils/dynamodb-constructs/dynamodb-constructs.js.map +1 -1
- package/src/utils/files/common/scripts/src/dynamodb/start-container.ts.template +0 -15
- package/src/utils/files/common/scripts/src/rdb/shared/start-container.ts.template +0 -15
- package/src/utils/format.d.ts +5 -0
- package/src/utils/format.js +5 -0
- package/src/utils/format.js.map +1 -1
- package/src/utils/function-constructs/function-constructs.js +2 -2
- package/src/utils/function-constructs/function-constructs.js.map +1 -1
- package/src/utils/generators.d.ts +33 -0
- package/src/utils/generators.js +18 -3
- package/src/utils/generators.js.map +1 -1
- package/src/utils/init.js +4 -6
- package/src/utils/init.js.map +1 -1
- package/src/utils/mock-project-graph.js +5 -2
- package/src/utils/mock-project-graph.js.map +1 -1
- package/src/utils/nx.d.ts +19 -0
- package/src/utils/nx.js +23 -0
- package/src/utils/nx.js.map +1 -1
- package/src/utils/open-api-codegen-target.d.ts +28 -0
- package/src/utils/open-api-codegen-target.js +31 -0
- package/src/utils/open-api-codegen-target.js.map +1 -0
- package/src/utils/rdb-constructs/rdb-constructs.js +2 -2
- package/src/utils/rdb-constructs/rdb-constructs.js.map +1 -1
- package/src/utils/website-constructs/website-constructs.js +2 -2
- package/src/utils/website-constructs/website-constructs.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/function-constructs/function-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast.js';\nimport type { Iac } from '../iac.js';\nimport { esmVars } from '../module-format.js';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/function-constructs/function-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast.js';\nimport type { Iac } from '../iac.js';\nimport { esmVars } from '../module-format.js';\nimport { addArtifactProjectToTargets } from '../nx.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants.js';\nimport {\n cdkLambdaRuntime,\n terraformLambdaRuntime,\n terraformProviderVersions,\n} from '../versions.js';\n\nexport interface AddLambdaFunctionConstructOptions {\n functionProjectName: string;\n nameClassName: string;\n nameKebabCase: string;\n bundlePathFromRoot: string;\n handler: string;\n runtime: 'node' | 'python';\n}\n\n/**\n * Add infrastructure for a lambda function\n */\nexport const addLambdaFunctionInfra = async (\n tree: Tree,\n options: AddLambdaFunctionConstructOptions & {\n iac: Iac;\n },\n) => {\n if (options.iac === 'cdk') {\n await addLambdaFunctionCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addLambdaFunctionTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n\n updateJson(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n options.iac === 'cdk' ? SHARED_CONSTRUCTS_DIR : SHARED_TERRAFORM_DIR,\n 'project.json',\n ),\n (config: ProjectConfiguration) => {\n addArtifactProjectToTargets(config, options.functionProjectName);\n return config;\n },\n );\n};\n\nconst addLambdaFunctionCdkConstructs = async (\n tree: Tree,\n options: AddLambdaFunctionConstructOptions,\n) => {\n // Generate app specific CDK construct\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'cdk',\n 'app',\n 'lambda-functions',\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'lambda-functions',\n ),\n {\n ...options,\n runtime: cdkLambdaRuntime(options.runtime),\n ...esmVars(tree),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Export app specific CDK construct\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'lambda-functions',\n 'index.ts',\n ),\n `./${options.nameKebabCase}.js`,\n );\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'index.ts',\n ),\n './lambda-functions/index.js',\n );\n};\n\nconst addLambdaFunctionTerraformModules = (\n tree: Tree,\n options: AddLambdaFunctionConstructOptions,\n) => {\n // Generate app specific terraform module\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'terraform',\n 'app',\n 'lambda-functions',\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'app',\n 'lambda-functions',\n ),\n {\n ...options,\n runtime: terraformLambdaRuntime(options.runtime),\n ...terraformProviderVersions(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","updateJson","addStarExport","esmVars","addArtifactProjectToTargets","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_TERRAFORM_DIR","cdkLambdaRuntime","terraformLambdaRuntime","terraformProviderVersions","addLambdaFunctionInfra","tree","options","iac","addLambdaFunctionCdkConstructs","addLambdaFunctionTerraformModules","Error","config","functionProjectName","dirname","runtime","overwriteStrategy","KeepExisting","nameKebabCase"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAGjBC,UAAU,QACL,aAAa;AACpB,SAASC,aAAa,QAAQ,YAAY;AAE1C,SAASC,OAAO,QAAQ,sBAAsB;AAC9C,SAASC,2BAA2B,QAAQ,WAAW;AACvD,SACEC,YAAY,EACZC,qBAAqB,EACrBC,oBAAoB,QACf,oCAAoC;AAC3C,SACEC,gBAAgB,EAChBC,sBAAsB,EACtBC,yBAAyB,QACpB,iBAAiB;AAWxB;;CAEC,GACD,OAAO,MAAMC,yBAAyB,OACpCC,MACAC;IAIA,IAAIA,QAAQC,GAAG,KAAK,OAAO;QACzB,MAAMC,+BAA+BH,MAAMC;IAC7C,OAAO,IAAIA,QAAQC,GAAG,KAAK,aAAa;QACtCE,kCAAkCJ,MAAMC;IAC1C,OAAO;QACL,MAAM,IAAII,MAAM,CAAC,gBAAgB,EAAEJ,QAAQC,GAAG,EAAE;IAClD;IAEAb,WACEW,MACAb,kBACEM,cACAQ,QAAQC,GAAG,KAAK,QAAQR,wBAAwBC,sBAChD,iBAEF,CAACW;QACCd,4BAA4Bc,QAAQL,QAAQM,mBAAmB;QAC/D,OAAOD;IACT;AAEJ,EAAE;AAEF,MAAMH,iCAAiC,OACrCH,MACAC;IAEA,sCAAsC;IACtCf,cACEc,MACAb,kBACE,YAAYqB,OAAO,EACnB,SACA,OACA,OACA,qBAEFrB,kBACEM,cACAC,uBACA,OACA,OACA,qBAEF;QACE,GAAGO,OAAO;QACVQ,SAASb,iBAAiBK,QAAQQ,OAAO;QACzC,GAAGlB,QAAQS,KAAK;IAClB,GACA;QACEU,mBAAmBtB,kBAAkBuB,YAAY;IACnD;IAGF,oCAAoC;IACpC,MAAMrB,cACJU,MACAb,kBACEM,cACAC,uBACA,OACA,OACA,oBACA,aAEF,CAAC,EAAE,EAAEO,QAAQW,aAAa,CAAC,GAAG,CAAC;IAEjC,MAAMtB,cACJU,MACAb,kBACEM,cACAC,uBACA,OACA,OACA,aAEF;AAEJ;AAEA,MAAMU,oCAAoC,CACxCJ,MACAC;IAEA,yCAAyC;IACzCf,cACEc,MACAb,kBACE,YAAYqB,OAAO,EACnB,SACA,aACA,OACA,qBAEFrB,kBACEM,cACAE,sBACA,OACA,OACA,qBAEF;QACE,GAAGM,OAAO;QACVQ,SAASZ,uBAAuBI,QAAQQ,OAAO;QAC/C,GAAGX,2BAA2B;IAChC,GACA;QACEY,mBAAmBtB,kBAAkBuB,YAAY;IACnD;AAEJ"}
|
|
@@ -2,12 +2,40 @@
|
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
*/
|
|
5
|
+
/**
|
|
6
|
+
* A single entry in `generators.json`.
|
|
7
|
+
*/
|
|
8
|
+
export interface GeneratorsJsonEntry {
|
|
9
|
+
readonly factory: string;
|
|
10
|
+
readonly schema: string;
|
|
11
|
+
readonly description: string;
|
|
12
|
+
readonly metric: string;
|
|
13
|
+
readonly hidden?: boolean;
|
|
14
|
+
readonly experimental?: boolean;
|
|
15
|
+
readonly guidePages?: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Typed view of the `generators.json` entries, keyed by generator id, so every
|
|
19
|
+
* consumer that describes a generator reads the same declared shape.
|
|
20
|
+
*/
|
|
21
|
+
export declare const generatorsJsonEntries: Readonly<Record<string, GeneratorsJsonEntry>>;
|
|
22
|
+
/**
|
|
23
|
+
* Look up a generator's `generators.json` entry by id, returning `undefined`
|
|
24
|
+
* when no generator has that id.
|
|
25
|
+
*/
|
|
26
|
+
export declare const findGeneratorsJsonEntry: (generatorId: string) => GeneratorsJsonEntry | undefined;
|
|
5
27
|
export interface GeneratorInfo {
|
|
6
28
|
readonly id: string;
|
|
7
29
|
readonly metric: string;
|
|
8
30
|
readonly resolvedFactoryPath: string;
|
|
9
31
|
readonly resolvedSchemaPath: string;
|
|
10
32
|
readonly hidden?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Experimental generators may change without a migration being published to
|
|
35
|
+
* apply the change to an existing workspace. Surfaced as a banner on the
|
|
36
|
+
* generator's guide page and in the MCP server's generator listings.
|
|
37
|
+
*/
|
|
38
|
+
readonly experimental?: boolean;
|
|
11
39
|
readonly description: string;
|
|
12
40
|
readonly guidePages?: readonly string[];
|
|
13
41
|
}
|
|
@@ -19,3 +47,8 @@ export type NxGeneratorInfo = GeneratorInfo;
|
|
|
19
47
|
* Build the list of generator info, resolving schema/factory paths relative to the given base directory.
|
|
20
48
|
*/
|
|
21
49
|
export declare const buildGeneratorInfoList: (baseDir: string) => GeneratorInfo[];
|
|
50
|
+
/**
|
|
51
|
+
* Describe a generator for a catalogue listing, marking an experimental
|
|
52
|
+
* generator so a reader knows its output may change without a migration.
|
|
53
|
+
*/
|
|
54
|
+
export declare const describeGeneratorForCatalogue: (info: Pick<GeneratorsJsonEntry, "description" | "experimental">) => string;
|
package/src/utils/generators.js
CHANGED
|
@@ -5,20 +5,35 @@
|
|
|
5
5
|
import GeneratorsJson from "../../generators.json" with {
|
|
6
6
|
type: 'json'
|
|
7
7
|
};
|
|
8
|
+
/**
|
|
9
|
+
* Typed view of the `generators.json` entries, keyed by generator id, so every
|
|
10
|
+
* consumer that describes a generator reads the same declared shape.
|
|
11
|
+
*/ export const generatorsJsonEntries = GeneratorsJson.generators;
|
|
12
|
+
/**
|
|
13
|
+
* Look up a generator's `generators.json` entry by id, returning `undefined`
|
|
14
|
+
* when no generator has that id.
|
|
15
|
+
*/ export const findGeneratorsJsonEntry = (generatorId)=>generatorsJsonEntries[generatorId];
|
|
8
16
|
/**
|
|
9
17
|
* Build the list of generator info, resolving schema/factory paths relative to the given base directory.
|
|
10
|
-
*/ export const buildGeneratorInfoList = (baseDir)=>Object.entries(
|
|
18
|
+
*/ export const buildGeneratorInfoList = (baseDir)=>Object.entries(generatorsJsonEntries).map(([id, info])=>({
|
|
11
19
|
id,
|
|
12
20
|
metric: info.metric,
|
|
13
21
|
resolvedFactoryPath: path.resolve(baseDir, info.factory),
|
|
14
22
|
resolvedSchemaPath: path.resolve(baseDir, info.schema),
|
|
15
23
|
description: info.description,
|
|
16
|
-
...
|
|
24
|
+
...info.hidden ? {
|
|
17
25
|
hidden: info.hidden
|
|
18
26
|
} : {},
|
|
19
|
-
...
|
|
27
|
+
...info.experimental ? {
|
|
28
|
+
experimental: info.experimental
|
|
29
|
+
} : {},
|
|
30
|
+
...info.guidePages ? {
|
|
20
31
|
guidePages: info.guidePages
|
|
21
32
|
} : {}
|
|
22
33
|
}));
|
|
34
|
+
/**
|
|
35
|
+
* Describe a generator for a catalogue listing, marking an experimental
|
|
36
|
+
* generator so a reader knows its output may change without a migration.
|
|
37
|
+
*/ export const describeGeneratorForCatalogue = (info)=>info.experimental ? `${info.description} (experimental)` : info.description;
|
|
23
38
|
|
|
24
39
|
//# sourceMappingURL=generators.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/generators.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as path from 'path';\nimport GeneratorsJson from '../../generators.json' with { type: 'json' };\n\nexport interface GeneratorInfo {\n readonly id: string;\n readonly metric: string;\n readonly resolvedFactoryPath: string;\n readonly resolvedSchemaPath: string;\n readonly hidden?: boolean;\n readonly description: string;\n readonly guidePages?: readonly string[];\n}\n\n/**\n * Alias for GeneratorInfo used by MCP server and generators\n */\nexport type NxGeneratorInfo = GeneratorInfo;\n\n/**\n * Build the list of generator info, resolving schema/factory paths relative to the given base directory.\n */\nexport const buildGeneratorInfoList = (baseDir: string): GeneratorInfo[] =>\n Object.entries(
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/generators.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as path from 'path';\nimport GeneratorsJson from '../../generators.json' with { type: 'json' };\n\n/**\n * A single entry in `generators.json`.\n */\nexport interface GeneratorsJsonEntry {\n readonly factory: string;\n readonly schema: string;\n readonly description: string;\n readonly metric: string;\n readonly hidden?: boolean;\n readonly experimental?: boolean;\n readonly guidePages?: readonly string[];\n}\n\n/**\n * Typed view of the `generators.json` entries, keyed by generator id, so every\n * consumer that describes a generator reads the same declared shape.\n */\nexport const generatorsJsonEntries: Readonly<\n Record<string, GeneratorsJsonEntry>\n> = (GeneratorsJson as { generators: Record<string, GeneratorsJsonEntry> })\n .generators;\n\n/**\n * Look up a generator's `generators.json` entry by id, returning `undefined`\n * when no generator has that id.\n */\nexport const findGeneratorsJsonEntry = (\n generatorId: string,\n): GeneratorsJsonEntry | undefined => generatorsJsonEntries[generatorId];\n\nexport interface GeneratorInfo {\n readonly id: string;\n readonly metric: string;\n readonly resolvedFactoryPath: string;\n readonly resolvedSchemaPath: string;\n readonly hidden?: boolean;\n /**\n * Experimental generators may change without a migration being published to\n * apply the change to an existing workspace. Surfaced as a banner on the\n * generator's guide page and in the MCP server's generator listings.\n */\n readonly experimental?: boolean;\n readonly description: string;\n readonly guidePages?: readonly string[];\n}\n\n/**\n * Alias for GeneratorInfo used by MCP server and generators\n */\nexport type NxGeneratorInfo = GeneratorInfo;\n\n/**\n * Build the list of generator info, resolving schema/factory paths relative to the given base directory.\n */\nexport const buildGeneratorInfoList = (baseDir: string): GeneratorInfo[] =>\n Object.entries(generatorsJsonEntries).map(([id, info]) => ({\n id,\n metric: info.metric,\n resolvedFactoryPath: path.resolve(baseDir, info.factory),\n resolvedSchemaPath: path.resolve(baseDir, info.schema),\n description: info.description,\n ...(info.hidden ? { hidden: info.hidden } : {}),\n ...(info.experimental ? { experimental: info.experimental } : {}),\n ...(info.guidePages ? { guidePages: info.guidePages } : {}),\n }));\n\n/**\n * Describe a generator for a catalogue listing, marking an experimental\n * generator so a reader knows its output may change without a migration.\n */\nexport const describeGeneratorForCatalogue = (\n info: Pick<GeneratorsJsonEntry, 'description' | 'experimental'>,\n): string =>\n info.experimental ? `${info.description} (experimental)` : info.description;\n"],"names":["path","GeneratorsJson","type","generatorsJsonEntries","generators","findGeneratorsJsonEntry","generatorId","buildGeneratorInfoList","baseDir","Object","entries","map","id","info","metric","resolvedFactoryPath","resolve","factory","resolvedSchemaPath","schema","description","hidden","experimental","guidePages","describeGeneratorForCatalogue"],"mappings":"AAAA;;;CAGC,GAED,YAAYA,UAAU,OAAO;AAC7B,OAAOC,oBAAoB,6BAA6B;IAAEC,MAAM;AAAO,EAAE;AAezE;;;CAGC,GACD,OAAO,MAAMC,wBAET,AAACF,eACFG,UAAU,CAAC;AAEd;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,CACrCC,cACoCH,qBAAqB,CAACG,YAAY,CAAC;AAuBzE;;CAEC,GACD,OAAO,MAAMC,yBAAyB,CAACC,UACrCC,OAAOC,OAAO,CAACP,uBAAuBQ,GAAG,CAAC,CAAC,CAACC,IAAIC,KAAK,GAAM,CAAA;YACzDD;YACAE,QAAQD,KAAKC,MAAM;YACnBC,qBAAqBf,KAAKgB,OAAO,CAACR,SAASK,KAAKI,OAAO;YACvDC,oBAAoBlB,KAAKgB,OAAO,CAACR,SAASK,KAAKM,MAAM;YACrDC,aAAaP,KAAKO,WAAW;YAC7B,GAAIP,KAAKQ,MAAM,GAAG;gBAAEA,QAAQR,KAAKQ,MAAM;YAAC,IAAI,CAAC,CAAC;YAC9C,GAAIR,KAAKS,YAAY,GAAG;gBAAEA,cAAcT,KAAKS,YAAY;YAAC,IAAI,CAAC,CAAC;YAChE,GAAIT,KAAKU,UAAU,GAAG;gBAAEA,YAAYV,KAAKU,UAAU;YAAC,IAAI,CAAC,CAAC;QAC5D,CAAA,GAAI;AAEN;;;CAGC,GACD,OAAO,MAAMC,gCAAgC,CAC3CX,OAEAA,KAAKS,YAAY,GAAG,GAAGT,KAAKO,WAAW,CAAC,eAAe,CAAC,GAAGP,KAAKO,WAAW,CAAC"}
|
package/src/utils/init.js
CHANGED
|
@@ -4,9 +4,6 @@
|
|
|
4
4
|
*/ import { generateFiles, joinPathFragments, OverwriteStrategy, readNxJson, updateJson, updateNxJson } from "@nx/devkit";
|
|
5
5
|
import { initGenerator } from "@nx/js";
|
|
6
6
|
import yaml from "js-yaml";
|
|
7
|
-
import GeneratorsJson from "../../generators.json" with {
|
|
8
|
-
type: 'json'
|
|
9
|
-
};
|
|
10
7
|
import { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from "../ts/sync/generator.js";
|
|
11
8
|
import { BASE_TSCONFIG_COMPILER_OPTIONS } from "./base-tsconfig.js";
|
|
12
9
|
import { ensureAwsNxPluginConfig, updateAwsNxPluginConfig } from "./config/utils.js";
|
|
@@ -14,6 +11,7 @@ import { inferContainers } from "./containers.js";
|
|
|
14
11
|
import { forDependencies } from "./declared-dependencies.js";
|
|
15
12
|
import { addDependenciesToPackageJson, detectWorkspacePackageManager } from "./dependencies.js";
|
|
16
13
|
import { getDefaultBiomeConfig } from "./format.js";
|
|
14
|
+
import { describeGeneratorForCatalogue, generatorsJsonEntries } from "./generators.js";
|
|
17
15
|
import { configureMcpServers } from "./mcp.js";
|
|
18
16
|
import { getNpmScope } from "./npm-scope.js";
|
|
19
17
|
import { mergeTargetDefault, nxPluginMcpDependency, nxPluginSelfDependency } from "./nx.js";
|
|
@@ -279,9 +277,9 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
279
277
|
}
|
|
280
278
|
generateFiles(tree, joinPathFragments(import.meta.dirname, '..', 'preset', 'files'), '.', {
|
|
281
279
|
projectName: getNpmScope(tree),
|
|
282
|
-
generators: Object.entries(
|
|
283
|
-
name:
|
|
284
|
-
description:
|
|
280
|
+
generators: Object.entries(generatorsJsonEntries).filter(([, info])=>!info.hidden).map(([id, info])=>({
|
|
281
|
+
name: id,
|
|
282
|
+
description: describeGeneratorForCatalogue(info)
|
|
285
283
|
})),
|
|
286
284
|
...(()=>{
|
|
287
285
|
const cmds = getPackageManagerDisplayCommands();
|
package/src/utils/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/init.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readNxJson,\n type Tree,\n updateJson,\n updateNxJson,\n} from '@nx/devkit';\nimport { initGenerator } from '@nx/js';\nimport { readFileSync } from 'fs';\nimport yaml from 'js-yaml';\nimport GeneratorsJson from '../../generators.json' with { type: 'json' };\nimport { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from '../ts/sync/generator.js';\nimport { BASE_TSCONFIG_COMPILER_OPTIONS } from './base-tsconfig.js';\nimport {\n ensureAwsNxPluginConfig,\n updateAwsNxPluginConfig,\n} from './config/utils.js';\nimport { type Containers, inferContainers } from './containers.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from './declared-dependencies.js';\nimport {\n addDependenciesToPackageJson,\n detectWorkspacePackageManager,\n} from './dependencies.js';\nimport { getDefaultBiomeConfig } from './format.js';\nimport type { Iac } from './iac.js';\nimport { configureMcpServers } from './mcp.js';\nimport { getNpmScope } from './npm-scope.js';\nimport {\n mergeTargetDefault,\n nxPluginMcpDependency,\n nxPluginSelfDependency,\n} from './nx.js';\nimport { getPackageManagerDisplayCommands } from './pkg-manager.js';\nimport { workspaceGlobs } from './project-package-json.js';\nimport { type ITsDepVersion, withVersions } from './versions.js';\n\nconst WORKSPACES = ['packages/*'];\nconst NX_TYPESCRIPT_SYNC_GENERATOR = '@nx/js:typescript-sync';\n\nexport const DEFAULT_PARALLEL = 8;\n\n/** Dependencies a caller must declare to apply the workspace init. */\nexport const INIT_DEPENDENCIES = [\n { name: 'nx' },\n { name: '@nx/js' },\n { name: '@nx/workspace' },\n { name: 'typescript' },\n { name: '@biomejs/biome' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n// Built dependencies whose install scripts the generated workspace trusts.\n// `onlyBuiltDependencies` is the pnpm 10 key (silently ignored by pnpm 11);\n// pnpm 11 reads `allowBuilds` instead. Any dep NOT in this allowlist will\n// have its install scripts skipped with a warning — matching pnpm 10's\n// default behaviour. The user can opt-in later via `pnpm approve-builds`.\nexport const PNPM_BUILT_DEPENDENCIES = ['@swc/core', 'esbuild', 'nx', 'sharp'];\n\n/**\n * Options controlling how the workspace is initialised. These mirror the\n * preset schema so a workspace created via the preset and one initialised via\n * the `init` generator end up in the same shape.\n */\nexport interface ApplyWorkspaceInitOptions {\n /** The IaC provider to record in the plugin config. */\n readonly iac: Iac;\n /**\n * The container engine to record. `undefined`/`'infer'` picks docker when\n * installed, else finch.\n */\n readonly containers?: Containers | 'infer';\n /** Whether to configure MCP servers for coding agents. Defaults to true. */\n readonly mcp?: boolean;\n /**\n * How to treat the generated workspace README. The preset owns the README of\n * a greenfield workspace (`Overwrite`); the `init` generator must not clobber\n * an existing workspace's README (`KeepExisting`, the default).\n */\n readonly readmeOverwriteStrategy?: OverwriteStrategy;\n /**\n * Whether to overwrite root package.json scripts that already exist. The\n * preset owns a greenfield workspace's scripts (`true`); the `init`\n * generator must not clobber an existing workspace's scripts (`false`,\n * the default) — it only adds the convenience scripts that are absent.\n */\n readonly overwriteScripts?: boolean;\n /**\n * Whether generators use the package manager's dependency catalog. On pnpm\n * this also sets `catalogMode: strict` so `pnpm add` records new deps in the\n * catalog. Defaults to true.\n */\n readonly catalogs?: boolean;\n}\n\n/**\n * Add or repair the pnpm `allowBuilds` / `onlyBuiltDependencies` allowlist for\n * the workspace's `packages` globs, without clobbering any packages the user\n * has already declared.\n *\n * A workspace not created by the preset commonly has either no\n * `pnpm-workspace.yaml`, one missing the `packages` globs, or one carrying the\n * broken `set this to true or false` placeholder pnpm writes when it skips a\n * build script. This makes the file self-consistent so the first generator's\n * install doesn't fail with `ERR_PNPM_IGNORED_BUILDS`.\n */\nconst setUpPnpmWorkspace = (tree: Tree, catalogs: boolean) => {\n const existing = tree.exists('pnpm-workspace.yaml')\n ? ((yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {})\n : {};\n\n // Preserve any packages globs the user already has, ensuring ours are present.\n const packages = Array.from(\n new Set([...((existing.packages as string[]) ?? []), ...WORKSPACES]),\n );\n\n const allowBuilds = {\n ...(typeof existing.allowBuilds === 'object' && existing.allowBuilds\n ? (existing.allowBuilds as Record<string, unknown>)\n : {}),\n // Overwrite any non-boolean (e.g. the \"set this to true or false\"\n // placeholder) with an explicit true for the deps we trust.\n ...Object.fromEntries(PNPM_BUILT_DEPENDENCIES.map((dep) => [dep, true])),\n };\n\n // `strict` makes `pnpm add` record new deps in the catalog; it only gates\n // that flow, so pre-declared direct ranges (e.g. tslib) still install.\n // Preserve an explicit user choice.\n const catalogMode = catalogs\n ? (existing.catalogMode ?? 'strict')\n : existing.catalogMode;\n\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump(\n {\n ...existing,\n packages,\n allowBuilds,\n onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES,\n ...(catalogMode ? { catalogMode } : {}),\n },\n { quotingType: \"'\" },\n ),\n );\n};\n\n/**\n * Configure the workspace's package manager for a monorepo layout.\n *\n * pnpm workspaces are declared in `pnpm-workspace.yaml`; every other package\n * manager reads the `workspaces` field of the root `package.json`.\n */\nconst setUpWorkspaces = (tree: Tree, catalogs: boolean) => {\n if (detectWorkspacePackageManager(tree) === 'pnpm') {\n setUpPnpmWorkspace(tree, catalogs);\n } else {\n updateJson(tree, 'package.json', (json) => {\n // The `workspaces` field may be the object form ({ \"packages\": [...] })\n // accepted by yarn and bun — extend the globs while preserving the form.\n const globs = Array.from(\n new Set([...workspaceGlobs(json.workspaces), ...WORKSPACES]),\n );\n return {\n ...json,\n workspaces:\n json.workspaces !== undefined && !Array.isArray(json.workspaces)\n ? { ...json.workspaces, packages: globs }\n : globs,\n };\n });\n }\n};\n\n/**\n * Ensure the workspace has a `tsconfig.base.json`.\n *\n * `@nx/js` `initGenerator` (with `addTsPlugin`) normally creates this, but it\n * short-circuits when the workspace already has a root `tsconfig.json` — in\n * which case no base file is written and the next project generator fails with\n * `Cannot find tsconfig.base.json`. So we create a compatible one when it's\n * absent. An existing base is left untouched: the user may have tuned it, and\n * rewriting shared compiler options can break other projects (see the\n * \"add to an existing workspace\" guide).\n */\nconst ensureBaseTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.base.json')) {\n return;\n }\n tree.write(\n 'tsconfig.base.json',\n JSON.stringify(\n {\n compilerOptions: {\n ...BASE_TSCONFIG_COMPILER_OPTIONS,\n customConditions: [getNpmScope(tree)],\n },\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Ensure the workspace has a root `tsconfig.json`.\n *\n * Nx's `@nx/js:typescript-sync` generator hard-fails with\n * `Missing root \"tsconfig.json\"` when it's absent. The plugin's TypeScript\n * projects reference each other via this file, so we guarantee a minimal one\n * exists (sync populates its `references`).\n */\nconst ensureRootTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.json')) {\n return;\n }\n tree.write(\n 'tsconfig.json',\n JSON.stringify(\n {\n extends: './tsconfig.base.json',\n files: [],\n references: [],\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Transform an Nx workspace into one ready to run `@aws/nx-plugin` generators.\n *\n * This is the deterministic core shared by the workspace preset and the `init`\n * generator. It is safe to re-run: every step is idempotent (config merges,\n * keyed nx.json / package.json entries, create-if-missing files), so running\n * it against an already-initialised workspace is a no-op.\n *\n * It preserves the workspace's module format: the root package.json `type`\n * field is owned by the preset (written from its `--module` option) and left\n * untouched here. It does NOT rewrite an existing `tsconfig.base.json`'s\n * compiler options, migrate a workspace's package manager, or restructure\n * existing projects — those are decisions for the user (see the \"add to an\n * existing workspace\" guide).\n */\nexport const applyWorkspaceInit = async <const D extends DependencyDeclaration>(\n tree: Tree,\n {\n iac,\n containers,\n mcp,\n readmeOverwriteStrategy = OverwriteStrategy.KeepExisting,\n overwriteScripts = false,\n catalogs = true,\n }: ApplyWorkspaceInitOptions,\n declaration: D & MustDeclare<typeof INIT_DEPENDENCIES, D>,\n) => {\n const resolvedContainers =\n !containers || containers === 'infer' ? inferContainers() : containers;\n\n // The catalogs flag is written explicitly (even when true) so the workspace\n // records its dependency-management choice.\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, {\n iac: { provider: iac },\n containers: { engine: resolvedContainers },\n packageManager: { catalogs },\n });\n\n // Set up the TypeScript plugin, base tsconfig, formatter etc. `@nx/js`\n // creates `tsconfig.base.json` when absent, but skips it when a root\n // `tsconfig.json` already exists — so we ensure both explicitly below.\n await initGenerator(tree, {\n formatter: 'none',\n addTsPlugin: true,\n });\n\n ensureBaseTsConfig(tree);\n ensureRootTsConfig(tree);\n\n setUpWorkspaces(tree, catalogs);\n\n const nxJson = readNxJson(tree);\n updateNxJson(tree, {\n ...nxJson,\n // Preserve an explicit analytics choice in an existing workspace.\n analytics: (nxJson as { analytics?: boolean }).analytics ?? false,\n parallel: nxJson.parallel ?? DEFAULT_PARALLEL,\n targetDefaults: {\n ...nxJson.targetDefaults,\n compile: mergeTargetDefault(nxJson.targetDefaults?.compile, (base) => ({\n ...base,\n syncGenerators: [\n ...(base.syncGenerators ?? []).filter(\n (g) =>\n ![TS_SYNC_GENERATOR_NAME, NX_TYPESCRIPT_SYNC_GENERATOR].includes(\n g,\n ),\n ),\n NX_TYPESCRIPT_SYNC_GENERATOR,\n TS_SYNC_GENERATOR_NAME,\n ],\n })),\n },\n });\n\n const CONVENIENCE_SCRIPTS = {\n dev: 'nx run-many --target dev',\n build: 'nx run-many --target build',\n lint: 'nx run-many --target lint --configuration=fix',\n test: 'nx run-many --target test --all',\n // Trivy container image scanning is not part of `build` (its result\n // depends on the ever-changing vulnerability database); run it explicitly,\n // e.g. in CI.\n trivy: 'nx run-many --target trivy --all',\n 'build:skip-lint': 'nx run-many --target build --configuration=skip-lint',\n 'build:all': 'nx run-many --target build --all',\n 'affected:all': 'nx affected --target build',\n };\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n // The root `type` field is owned by the preset (written explicitly from\n // its `--module` option). `init` preserves an existing workspace's field\n // as-is: an ESM workspace already carries `type: \"module\"` (that is how\n // the format is inferred), and introducing a `type` into a CommonJS\n // workspace that lacks one changes behaviour for frameworks that parse it\n // (e.g. Next.js starts treating the app's ESM source as CJS).\n scripts: overwriteScripts\n ? { ...packageJson.scripts, ...CONVENIENCE_SCRIPTS }\n : { ...CONVENIENCE_SCRIPTS, ...packageJson.scripts },\n }));\n\n // Pin the workspace's `nx` to the version the plugin's @nx/* packages are\n // built against. A mismatched workspace nx (even a patch apart) hoists a\n // second nested nx under @nx/js, and the two instances deadlock `nx sync`.\n // `@nx/js` must be a root dependency for the `@nx/js:typescript-sync`\n // generator registered in nx.json to resolve (npm doesn't hoist the\n // plugin's own copy reliably).\n addDependenciesToPackageJson(\n tree,\n {},\n {\n ...withVersions(forDependencies<typeof INIT_DEPENDENCIES>(declaration), [\n 'nx',\n '@nx/js',\n '@nx/workspace',\n ]),\n ...withVersions(forDependencies<typeof INIT_DEPENDENCIES>(declaration), [\n 'typescript',\n '@biomejs/biome',\n ]),\n // Declare the plugin the generators are running from, plus the MCP server\n // package the vended config runs, so both are pinned in the workspace's\n // lockfile and upgrading them upgrades what the agents use.\n ...nxPluginSelfDependency(tree),\n ...nxPluginMcpDependency(tree),\n },\n );\n\n // Write biome.json for formatting and linting\n if (!tree.exists('biome.json')) {\n tree.write(\n 'biome.json',\n JSON.stringify(getDefaultBiomeConfig(tree), null, 2),\n );\n }\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, '..', 'preset', 'files'),\n '.',\n {\n projectName: getNpmScope(tree),\n generators: Object.entries(GeneratorsJson.generators)\n .filter(([_, v]) => !v['hidden'])\n .map(([k, v]) => ({ name: k, description: v.description })),\n ...(() => {\n const cmds = getPackageManagerDisplayCommands();\n return {\n pkgMgrCmd: cmds.exec,\n buildCmd: `${cmds.run} build`,\n lintCmd: `${cmds.run} lint`,\n };\n })(),\n },\n {\n overwriteStrategy: readmeOverwriteStrategy,\n },\n );\n\n if (mcp !== false) {\n configureMcpServers(tree);\n }\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readNxJson","updateJson","updateNxJson","initGenerator","yaml","GeneratorsJson","type","SYNC_GENERATOR_NAME","TS_SYNC_GENERATOR_NAME","BASE_TSCONFIG_COMPILER_OPTIONS","ensureAwsNxPluginConfig","updateAwsNxPluginConfig","inferContainers","forDependencies","addDependenciesToPackageJson","detectWorkspacePackageManager","getDefaultBiomeConfig","configureMcpServers","getNpmScope","mergeTargetDefault","nxPluginMcpDependency","nxPluginSelfDependency","getPackageManagerDisplayCommands","workspaceGlobs","withVersions","WORKSPACES","NX_TYPESCRIPT_SYNC_GENERATOR","DEFAULT_PARALLEL","INIT_DEPENDENCIES","name","PNPM_BUILT_DEPENDENCIES","setUpPnpmWorkspace","tree","catalogs","existing","exists","load","read","packages","Array","from","Set","allowBuilds","Object","fromEntries","map","dep","catalogMode","write","dump","onlyBuiltDependencies","quotingType","setUpWorkspaces","json","globs","workspaces","undefined","isArray","ensureBaseTsConfig","JSON","stringify","compilerOptions","customConditions","ensureRootTsConfig","extends","files","references","applyWorkspaceInit","iac","containers","mcp","readmeOverwriteStrategy","KeepExisting","overwriteScripts","declaration","resolvedContainers","provider","engine","packageManager","formatter","addTsPlugin","nxJson","analytics","parallel","targetDefaults","compile","base","syncGenerators","filter","g","includes","CONVENIENCE_SCRIPTS","dev","build","lint","test","trivy","packageJson","scripts","dirname","projectName","generators","entries","_","v","k","description","cmds","pkgMgrCmd","exec","buildCmd","run","lintCmd","overwriteStrategy"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EAEVC,UAAU,EACVC,YAAY,QACP,aAAa;AACpB,SAASC,aAAa,QAAQ,SAAS;AAEvC,OAAOC,UAAU,UAAU;AAC3B,OAAOC,oBAAoB,6BAA6B;IAAEC,MAAM;AAAO,EAAE;AACzE,SAASC,uBAAuBC,sBAAsB,QAAQ,0BAA0B;AACxF,SAASC,8BAA8B,QAAQ,qBAAqB;AACpE,SACEC,uBAAuB,EACvBC,uBAAuB,QAClB,oBAAoB;AAC3B,SAA0BC,eAAe,QAAQ,kBAAkB;AACnE,SAEEC,eAAe,QAEV,6BAA6B;AACpC,SACEC,4BAA4B,EAC5BC,6BAA6B,QACxB,oBAAoB;AAC3B,SAASC,qBAAqB,QAAQ,cAAc;AAEpD,SAASC,mBAAmB,QAAQ,WAAW;AAC/C,SAASC,WAAW,QAAQ,iBAAiB;AAC7C,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,sBAAsB,QACjB,UAAU;AACjB,SAASC,gCAAgC,QAAQ,mBAAmB;AACpE,SAASC,cAAc,QAAQ,4BAA4B;AAC3D,SAA6BC,YAAY,QAAQ,gBAAgB;AAEjE,MAAMC,aAAa;IAAC;CAAa;AACjC,MAAMC,+BAA+B;AAErC,OAAO,MAAMC,mBAAmB,EAAE;AAElC,oEAAoE,GACpE,OAAO,MAAMC,oBAAoB;IAC/B;QAAEC,MAAM;IAAK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\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readNxJson,\n type Tree,\n updateJson,\n updateNxJson,\n} from '@nx/devkit';\nimport { initGenerator } from '@nx/js';\nimport { readFileSync } from 'fs';\nimport yaml from 'js-yaml';\nimport { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from '../ts/sync/generator.js';\nimport { BASE_TSCONFIG_COMPILER_OPTIONS } from './base-tsconfig.js';\nimport {\n ensureAwsNxPluginConfig,\n updateAwsNxPluginConfig,\n} from './config/utils.js';\nimport { type Containers, inferContainers } from './containers.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from './declared-dependencies.js';\nimport {\n addDependenciesToPackageJson,\n detectWorkspacePackageManager,\n} from './dependencies.js';\nimport { getDefaultBiomeConfig } from './format.js';\nimport {\n describeGeneratorForCatalogue,\n generatorsJsonEntries,\n} from './generators.js';\nimport type { Iac } from './iac.js';\nimport { configureMcpServers } from './mcp.js';\nimport { getNpmScope } from './npm-scope.js';\nimport {\n mergeTargetDefault,\n nxPluginMcpDependency,\n nxPluginSelfDependency,\n} from './nx.js';\nimport { getPackageManagerDisplayCommands } from './pkg-manager.js';\nimport { workspaceGlobs } from './project-package-json.js';\nimport { type ITsDepVersion, withVersions } from './versions.js';\n\nconst WORKSPACES = ['packages/*'];\nconst NX_TYPESCRIPT_SYNC_GENERATOR = '@nx/js:typescript-sync';\n\nexport const DEFAULT_PARALLEL = 8;\n\n/** Dependencies a caller must declare to apply the workspace init. */\nexport const INIT_DEPENDENCIES = [\n { name: 'nx' },\n { name: '@nx/js' },\n { name: '@nx/workspace' },\n { name: 'typescript' },\n { name: '@biomejs/biome' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n// Built dependencies whose install scripts the generated workspace trusts.\n// `onlyBuiltDependencies` is the pnpm 10 key (silently ignored by pnpm 11);\n// pnpm 11 reads `allowBuilds` instead. Any dep NOT in this allowlist will\n// have its install scripts skipped with a warning — matching pnpm 10's\n// default behaviour. The user can opt-in later via `pnpm approve-builds`.\nexport const PNPM_BUILT_DEPENDENCIES = ['@swc/core', 'esbuild', 'nx', 'sharp'];\n\n/**\n * Options controlling how the workspace is initialised. These mirror the\n * preset schema so a workspace created via the preset and one initialised via\n * the `init` generator end up in the same shape.\n */\nexport interface ApplyWorkspaceInitOptions {\n /** The IaC provider to record in the plugin config. */\n readonly iac: Iac;\n /**\n * The container engine to record. `undefined`/`'infer'` picks docker when\n * installed, else finch.\n */\n readonly containers?: Containers | 'infer';\n /** Whether to configure MCP servers for coding agents. Defaults to true. */\n readonly mcp?: boolean;\n /**\n * How to treat the generated workspace README. The preset owns the README of\n * a greenfield workspace (`Overwrite`); the `init` generator must not clobber\n * an existing workspace's README (`KeepExisting`, the default).\n */\n readonly readmeOverwriteStrategy?: OverwriteStrategy;\n /**\n * Whether to overwrite root package.json scripts that already exist. The\n * preset owns a greenfield workspace's scripts (`true`); the `init`\n * generator must not clobber an existing workspace's scripts (`false`,\n * the default) — it only adds the convenience scripts that are absent.\n */\n readonly overwriteScripts?: boolean;\n /**\n * Whether generators use the package manager's dependency catalog. On pnpm\n * this also sets `catalogMode: strict` so `pnpm add` records new deps in the\n * catalog. Defaults to true.\n */\n readonly catalogs?: boolean;\n}\n\n/**\n * Add or repair the pnpm `allowBuilds` / `onlyBuiltDependencies` allowlist for\n * the workspace's `packages` globs, without clobbering any packages the user\n * has already declared.\n *\n * A workspace not created by the preset commonly has either no\n * `pnpm-workspace.yaml`, one missing the `packages` globs, or one carrying the\n * broken `set this to true or false` placeholder pnpm writes when it skips a\n * build script. This makes the file self-consistent so the first generator's\n * install doesn't fail with `ERR_PNPM_IGNORED_BUILDS`.\n */\nconst setUpPnpmWorkspace = (tree: Tree, catalogs: boolean) => {\n const existing = tree.exists('pnpm-workspace.yaml')\n ? ((yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {})\n : {};\n\n // Preserve any packages globs the user already has, ensuring ours are present.\n const packages = Array.from(\n new Set([...((existing.packages as string[]) ?? []), ...WORKSPACES]),\n );\n\n const allowBuilds = {\n ...(typeof existing.allowBuilds === 'object' && existing.allowBuilds\n ? (existing.allowBuilds as Record<string, unknown>)\n : {}),\n // Overwrite any non-boolean (e.g. the \"set this to true or false\"\n // placeholder) with an explicit true for the deps we trust.\n ...Object.fromEntries(PNPM_BUILT_DEPENDENCIES.map((dep) => [dep, true])),\n };\n\n // `strict` makes `pnpm add` record new deps in the catalog; it only gates\n // that flow, so pre-declared direct ranges (e.g. tslib) still install.\n // Preserve an explicit user choice.\n const catalogMode = catalogs\n ? (existing.catalogMode ?? 'strict')\n : existing.catalogMode;\n\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump(\n {\n ...existing,\n packages,\n allowBuilds,\n onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES,\n ...(catalogMode ? { catalogMode } : {}),\n },\n { quotingType: \"'\" },\n ),\n );\n};\n\n/**\n * Configure the workspace's package manager for a monorepo layout.\n *\n * pnpm workspaces are declared in `pnpm-workspace.yaml`; every other package\n * manager reads the `workspaces` field of the root `package.json`.\n */\nconst setUpWorkspaces = (tree: Tree, catalogs: boolean) => {\n if (detectWorkspacePackageManager(tree) === 'pnpm') {\n setUpPnpmWorkspace(tree, catalogs);\n } else {\n updateJson(tree, 'package.json', (json) => {\n // The `workspaces` field may be the object form ({ \"packages\": [...] })\n // accepted by yarn and bun — extend the globs while preserving the form.\n const globs = Array.from(\n new Set([...workspaceGlobs(json.workspaces), ...WORKSPACES]),\n );\n return {\n ...json,\n workspaces:\n json.workspaces !== undefined && !Array.isArray(json.workspaces)\n ? { ...json.workspaces, packages: globs }\n : globs,\n };\n });\n }\n};\n\n/**\n * Ensure the workspace has a `tsconfig.base.json`.\n *\n * `@nx/js` `initGenerator` (with `addTsPlugin`) normally creates this, but it\n * short-circuits when the workspace already has a root `tsconfig.json` — in\n * which case no base file is written and the next project generator fails with\n * `Cannot find tsconfig.base.json`. So we create a compatible one when it's\n * absent. An existing base is left untouched: the user may have tuned it, and\n * rewriting shared compiler options can break other projects (see the\n * \"add to an existing workspace\" guide).\n */\nconst ensureBaseTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.base.json')) {\n return;\n }\n tree.write(\n 'tsconfig.base.json',\n JSON.stringify(\n {\n compilerOptions: {\n ...BASE_TSCONFIG_COMPILER_OPTIONS,\n customConditions: [getNpmScope(tree)],\n },\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Ensure the workspace has a root `tsconfig.json`.\n *\n * Nx's `@nx/js:typescript-sync` generator hard-fails with\n * `Missing root \"tsconfig.json\"` when it's absent. The plugin's TypeScript\n * projects reference each other via this file, so we guarantee a minimal one\n * exists (sync populates its `references`).\n */\nconst ensureRootTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.json')) {\n return;\n }\n tree.write(\n 'tsconfig.json',\n JSON.stringify(\n {\n extends: './tsconfig.base.json',\n files: [],\n references: [],\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Transform an Nx workspace into one ready to run `@aws/nx-plugin` generators.\n *\n * This is the deterministic core shared by the workspace preset and the `init`\n * generator. It is safe to re-run: every step is idempotent (config merges,\n * keyed nx.json / package.json entries, create-if-missing files), so running\n * it against an already-initialised workspace is a no-op.\n *\n * It preserves the workspace's module format: the root package.json `type`\n * field is owned by the preset (written from its `--module` option) and left\n * untouched here. It does NOT rewrite an existing `tsconfig.base.json`'s\n * compiler options, migrate a workspace's package manager, or restructure\n * existing projects — those are decisions for the user (see the \"add to an\n * existing workspace\" guide).\n */\nexport const applyWorkspaceInit = async <const D extends DependencyDeclaration>(\n tree: Tree,\n {\n iac,\n containers,\n mcp,\n readmeOverwriteStrategy = OverwriteStrategy.KeepExisting,\n overwriteScripts = false,\n catalogs = true,\n }: ApplyWorkspaceInitOptions,\n declaration: D & MustDeclare<typeof INIT_DEPENDENCIES, D>,\n) => {\n const resolvedContainers =\n !containers || containers === 'infer' ? inferContainers() : containers;\n\n // The catalogs flag is written explicitly (even when true) so the workspace\n // records its dependency-management choice.\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, {\n iac: { provider: iac },\n containers: { engine: resolvedContainers },\n packageManager: { catalogs },\n });\n\n // Set up the TypeScript plugin, base tsconfig, formatter etc. `@nx/js`\n // creates `tsconfig.base.json` when absent, but skips it when a root\n // `tsconfig.json` already exists — so we ensure both explicitly below.\n await initGenerator(tree, {\n formatter: 'none',\n addTsPlugin: true,\n });\n\n ensureBaseTsConfig(tree);\n ensureRootTsConfig(tree);\n\n setUpWorkspaces(tree, catalogs);\n\n const nxJson = readNxJson(tree);\n updateNxJson(tree, {\n ...nxJson,\n // Preserve an explicit analytics choice in an existing workspace.\n analytics: (nxJson as { analytics?: boolean }).analytics ?? false,\n parallel: nxJson.parallel ?? DEFAULT_PARALLEL,\n targetDefaults: {\n ...nxJson.targetDefaults,\n compile: mergeTargetDefault(nxJson.targetDefaults?.compile, (base) => ({\n ...base,\n syncGenerators: [\n ...(base.syncGenerators ?? []).filter(\n (g) =>\n ![TS_SYNC_GENERATOR_NAME, NX_TYPESCRIPT_SYNC_GENERATOR].includes(\n g,\n ),\n ),\n NX_TYPESCRIPT_SYNC_GENERATOR,\n TS_SYNC_GENERATOR_NAME,\n ],\n })),\n },\n });\n\n const CONVENIENCE_SCRIPTS = {\n dev: 'nx run-many --target dev',\n build: 'nx run-many --target build',\n lint: 'nx run-many --target lint --configuration=fix',\n test: 'nx run-many --target test --all',\n // Trivy container image scanning is not part of `build` (its result\n // depends on the ever-changing vulnerability database); run it explicitly,\n // e.g. in CI.\n trivy: 'nx run-many --target trivy --all',\n 'build:skip-lint': 'nx run-many --target build --configuration=skip-lint',\n 'build:all': 'nx run-many --target build --all',\n 'affected:all': 'nx affected --target build',\n };\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n // The root `type` field is owned by the preset (written explicitly from\n // its `--module` option). `init` preserves an existing workspace's field\n // as-is: an ESM workspace already carries `type: \"module\"` (that is how\n // the format is inferred), and introducing a `type` into a CommonJS\n // workspace that lacks one changes behaviour for frameworks that parse it\n // (e.g. Next.js starts treating the app's ESM source as CJS).\n scripts: overwriteScripts\n ? { ...packageJson.scripts, ...CONVENIENCE_SCRIPTS }\n : { ...CONVENIENCE_SCRIPTS, ...packageJson.scripts },\n }));\n\n // Pin the workspace's `nx` to the version the plugin's @nx/* packages are\n // built against. A mismatched workspace nx (even a patch apart) hoists a\n // second nested nx under @nx/js, and the two instances deadlock `nx sync`.\n // `@nx/js` must be a root dependency for the `@nx/js:typescript-sync`\n // generator registered in nx.json to resolve (npm doesn't hoist the\n // plugin's own copy reliably).\n addDependenciesToPackageJson(\n tree,\n {},\n {\n ...withVersions(forDependencies<typeof INIT_DEPENDENCIES>(declaration), [\n 'nx',\n '@nx/js',\n '@nx/workspace',\n ]),\n ...withVersions(forDependencies<typeof INIT_DEPENDENCIES>(declaration), [\n 'typescript',\n '@biomejs/biome',\n ]),\n // Declare the plugin the generators are running from, plus the MCP server\n // package the vended config runs, so both are pinned in the workspace's\n // lockfile and upgrading them upgrades what the agents use.\n ...nxPluginSelfDependency(tree),\n ...nxPluginMcpDependency(tree),\n },\n );\n\n // Write biome.json for formatting and linting\n if (!tree.exists('biome.json')) {\n tree.write(\n 'biome.json',\n JSON.stringify(getDefaultBiomeConfig(tree), null, 2),\n );\n }\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, '..', 'preset', 'files'),\n '.',\n {\n projectName: getNpmScope(tree),\n generators: Object.entries(generatorsJsonEntries)\n .filter(([, info]) => !info.hidden)\n .map(([id, info]) => ({\n name: id,\n description: describeGeneratorForCatalogue(info),\n })),\n ...(() => {\n const cmds = getPackageManagerDisplayCommands();\n return {\n pkgMgrCmd: cmds.exec,\n buildCmd: `${cmds.run} build`,\n lintCmd: `${cmds.run} lint`,\n };\n })(),\n },\n {\n overwriteStrategy: readmeOverwriteStrategy,\n },\n );\n\n if (mcp !== false) {\n configureMcpServers(tree);\n }\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readNxJson","updateJson","updateNxJson","initGenerator","yaml","SYNC_GENERATOR_NAME","TS_SYNC_GENERATOR_NAME","BASE_TSCONFIG_COMPILER_OPTIONS","ensureAwsNxPluginConfig","updateAwsNxPluginConfig","inferContainers","forDependencies","addDependenciesToPackageJson","detectWorkspacePackageManager","getDefaultBiomeConfig","describeGeneratorForCatalogue","generatorsJsonEntries","configureMcpServers","getNpmScope","mergeTargetDefault","nxPluginMcpDependency","nxPluginSelfDependency","getPackageManagerDisplayCommands","workspaceGlobs","withVersions","WORKSPACES","NX_TYPESCRIPT_SYNC_GENERATOR","DEFAULT_PARALLEL","INIT_DEPENDENCIES","name","PNPM_BUILT_DEPENDENCIES","setUpPnpmWorkspace","tree","catalogs","existing","exists","load","read","packages","Array","from","Set","allowBuilds","Object","fromEntries","map","dep","catalogMode","write","dump","onlyBuiltDependencies","quotingType","setUpWorkspaces","json","globs","workspaces","undefined","isArray","ensureBaseTsConfig","JSON","stringify","compilerOptions","customConditions","ensureRootTsConfig","extends","files","references","applyWorkspaceInit","iac","containers","mcp","readmeOverwriteStrategy","KeepExisting","overwriteScripts","declaration","resolvedContainers","provider","engine","packageManager","formatter","addTsPlugin","nxJson","analytics","parallel","targetDefaults","compile","base","syncGenerators","filter","g","includes","CONVENIENCE_SCRIPTS","dev","build","lint","test","trivy","packageJson","scripts","dirname","projectName","generators","entries","info","hidden","id","description","cmds","pkgMgrCmd","exec","buildCmd","run","lintCmd","overwriteStrategy"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EAEVC,UAAU,EACVC,YAAY,QACP,aAAa;AACpB,SAASC,aAAa,QAAQ,SAAS;AAEvC,OAAOC,UAAU,UAAU;AAC3B,SAASC,uBAAuBC,sB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EmC,MACAlC,kBAAkB,YAAYqG,OAAO,EAAE,MAAM,UAAU,UACvD,KACA;QACEC,aAAalF,YAAYc;QACzBqE,YAAY1D,OAAO2D,OAAO,CAACtF,uBACxBwE,MAAM,CAAC,CAAC,GAAGe,KAAK,GAAK,CAACA,KAAKC,MAAM,EACjC3D,GAAG,CAAC,CAAC,CAAC4D,IAAIF,KAAK,GAAM,CAAA;gBACpB1E,MAAM4E;gBACNC,aAAa3F,8BAA8BwF;YAC7C,CAAA;QACF,GAAG,AAAC,CAAA;YACF,MAAMI,OAAOrF;YACb,OAAO;gBACLsF,WAAWD,KAAKE,IAAI;gBACpBC,UAAU,GAAGH,KAAKI,GAAG,CAAC,MAAM,CAAC;gBAC7BC,SAAS,GAAGL,KAAKI,GAAG,CAAC,KAAK,CAAC;YAC7B;QACF,CAAA,GAAI;IACN,GACA;QACEE,mBAAmB1C;IACrB;IAGF,IAAID,QAAQ,OAAO;QACjBrD,oBAAoBe;IACtB;AACF,EAAE"}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
*/ /**
|
|
5
|
-
* Mock
|
|
5
|
+
* Mock the project graph accessors to avoid expensive project graph building in
|
|
6
|
+
* tests, and to keep tests from reading this repository's own on-disk graph.
|
|
6
7
|
*
|
|
7
8
|
* This is the vitest equivalent of Nx's own internal testing utility:
|
|
8
9
|
* https://github.com/nrwl/nx/blob/master/packages/nx/src/internal-testing-utils/mock-project-graph.ts
|
|
@@ -15,9 +16,11 @@
|
|
|
15
16
|
*/ import { createRequire } from "module";
|
|
16
17
|
const _require = createRequire(import.meta.url);
|
|
17
18
|
const projectGraph = _require('nx/src/project-graph/project-graph');
|
|
18
|
-
|
|
19
|
+
const emptyGraph = ()=>({
|
|
19
20
|
nodes: {},
|
|
20
21
|
dependencies: {}
|
|
21
22
|
});
|
|
23
|
+
projectGraph.createProjectGraphAsync = async ()=>emptyGraph();
|
|
24
|
+
projectGraph.readCachedProjectGraph = ()=>emptyGraph();
|
|
22
25
|
|
|
23
26
|
//# sourceMappingURL=mock-project-graph.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/mock-project-graph.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Mock
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/mock-project-graph.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Mock the project graph accessors to avoid expensive project graph building in\n * tests, and to keep tests from reading this repository's own on-disk graph.\n *\n * This is the vitest equivalent of Nx's own internal testing utility:\n * https://github.com/nrwl/nx/blob/master/packages/nx/src/internal-testing-utils/mock-project-graph.ts\n *\n * We patch the underlying nx module directly because:\n * 1. vitest's vi.mock only affects ESM imports within the test file\n * 2. @nx/devkit's exports are wrapped with read-only getters by vitest\n * 3. The CJS module at nx/src/project-graph/project-graph.js is the actual\n * implementation that @nx/devkit re-exports\n */\nimport { createRequire } from 'module';\n\nconst _require = createRequire(import.meta.url);\nconst projectGraph = _require('nx/src/project-graph/project-graph');\nconst emptyGraph = () => ({ nodes: {}, dependencies: {} });\nprojectGraph.createProjectGraphAsync = async () => emptyGraph();\nprojectGraph.readCachedProjectGraph = () => emptyGraph();\n"],"names":["createRequire","_require","url","projectGraph","emptyGraph","nodes","dependencies","createProjectGraphAsync","readCachedProjectGraph"],"mappings":"AAAA;;;CAGC,GAED;;;;;;;;;;;;CAYC,GACD,SAASA,aAAa,QAAQ,SAAS;AAEvC,MAAMC,WAAWD,cAAc,YAAYE,GAAG;AAC9C,MAAMC,eAAeF,SAAS;AAC9B,MAAMG,aAAa,IAAO,CAAA;QAAEC,OAAO,CAAC;QAAGC,cAAc,CAAC;IAAE,CAAA;AACxDH,aAAaI,uBAAuB,GAAG,UAAYH;AACnDD,aAAaK,sBAAsB,GAAG,IAAMJ"}
|
package/src/utils/nx.d.ts
CHANGED
|
@@ -124,6 +124,25 @@ export declare const normalizeTargetKeyOrder: <T extends object>(target: T) => T
|
|
|
124
124
|
* using deep equality so re-running a generator does not grow `dependsOn`.
|
|
125
125
|
*/
|
|
126
126
|
export declare const addDependencyToTargetIfNotPresent: (project: ProjectConfiguration, target: string, dependency: TargetDependency) => void;
|
|
127
|
+
/**
|
|
128
|
+
* Register a dependency that produces a deployable artifact on both `build` and
|
|
129
|
+
* `assemble`.
|
|
130
|
+
*
|
|
131
|
+
* `build` is the everything target: artifacts plus the quality gates (lint,
|
|
132
|
+
* test, typecheck). `assemble` is its artifact-only sibling, which the deploy
|
|
133
|
+
* targets depend on so a deploy builds what it deploys and nothing else.
|
|
134
|
+
*/
|
|
135
|
+
export declare const addArtifactDependencyToTargets: (project: ProjectConfiguration, dependency: TargetDependency) => void;
|
|
136
|
+
/**
|
|
137
|
+
* Register another project whose artifacts this one consumes, on both `build`
|
|
138
|
+
* and `assemble`.
|
|
139
|
+
*
|
|
140
|
+
* The shared infrastructure project reads the artifacts of every project it
|
|
141
|
+
* deploys, and those cross-project edges are explicit because Nx's `^` operator
|
|
142
|
+
* only follows package dependencies. `assemble` mirrors the list against the
|
|
143
|
+
* consumed projects' own `assemble`, keeping the artifact-only chain closed.
|
|
144
|
+
*/
|
|
145
|
+
export declare const addArtifactProjectToTargets: (project: ProjectConfiguration, consumedProjectName: string) => void;
|
|
127
146
|
/**
|
|
128
147
|
* Register a component's `<name>-dev` target under the project-level `dev`
|
|
129
148
|
* target, so `nx run <project>:dev` starts every component in the project.
|
package/src/utils/nx.js
CHANGED
|
@@ -229,6 +229,29 @@ const NX_TARGET_KEY_ORDER = [
|
|
|
229
229
|
// Keep key order aligned with Nx's so first run matches subsequent runs.
|
|
230
230
|
project.targets[target] = normalizeTargetKeyOrder(project.targets[target]);
|
|
231
231
|
};
|
|
232
|
+
/**
|
|
233
|
+
* Register a dependency that produces a deployable artifact on both `build` and
|
|
234
|
+
* `assemble`.
|
|
235
|
+
*
|
|
236
|
+
* `build` is the everything target: artifacts plus the quality gates (lint,
|
|
237
|
+
* test, typecheck). `assemble` is its artifact-only sibling, which the deploy
|
|
238
|
+
* targets depend on so a deploy builds what it deploys and nothing else.
|
|
239
|
+
*/ export const addArtifactDependencyToTargets = (project, dependency)=>{
|
|
240
|
+
addDependencyToTargetIfNotPresent(project, 'build', dependency);
|
|
241
|
+
addDependencyToTargetIfNotPresent(project, 'assemble', dependency);
|
|
242
|
+
};
|
|
243
|
+
/**
|
|
244
|
+
* Register another project whose artifacts this one consumes, on both `build`
|
|
245
|
+
* and `assemble`.
|
|
246
|
+
*
|
|
247
|
+
* The shared infrastructure project reads the artifacts of every project it
|
|
248
|
+
* deploys, and those cross-project edges are explicit because Nx's `^` operator
|
|
249
|
+
* only follows package dependencies. `assemble` mirrors the list against the
|
|
250
|
+
* consumed projects' own `assemble`, keeping the artifact-only chain closed.
|
|
251
|
+
*/ export const addArtifactProjectToTargets = (project, consumedProjectName)=>{
|
|
252
|
+
addDependencyToTargetIfNotPresent(project, 'build', `${consumedProjectName}:build`);
|
|
253
|
+
addDependencyToTargetIfNotPresent(project, 'assemble', `${consumedProjectName}:assemble`);
|
|
254
|
+
};
|
|
232
255
|
/**
|
|
233
256
|
* Register a component's `<name>-dev` target under the project-level `dev`
|
|
234
257
|
* target, so `nx run <project>:dev` starts every component in the project.
|
package/src/utils/nx.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/nx.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n getProjects,\n type ProjectConfiguration,\n readJson,\n readProjectConfiguration,\n type TargetConfiguration,\n type TargetDefaultValue,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport * as path from 'path';\nimport PackageJson from '../../package.json' with { type: 'json' };\nimport { NX_PLUGIN_MCP_PACKAGE_NAME } from './mcp.js';\nimport { toSnakeCase } from './names.js';\nimport { getNpmScope, getNpmScopePrefix } from './npm-scope.js';\n\nexport type { GeneratorInfo, NxGeneratorInfo } from './generators.js';\nexport { buildGeneratorInfoList } from './generators.js';\n\nimport { buildGeneratorInfoList, type GeneratorInfo } from './generators.js';\n\nconst GENERATORS = buildGeneratorInfoList(\n path.resolve(import.meta.dirname, '..', '..'),\n);\n\n/**\n * List Nx Plugin for AWS generators\n * @param includeHidden include hidden generators (default false)\n */\nexport const listGenerators = (includeHidden = false) =>\n GENERATORS.filter((g) => includeHidden || !g.hidden);\n\n/**\n * Return generator information. Call this from a generator method with import.meta.filename\n */\nexport const getGeneratorInfo = (generatorFileName: string): GeneratorInfo => {\n const { dir, name } = path.parse(path.resolve(generatorFileName));\n const resolvedFactoryPath = path.join(dir, name);\n return GENERATORS.find(\n (generatorInfo) =>\n generatorInfo.resolvedFactoryPath === resolvedFactoryPath,\n );\n};\n\nexport const getPackageVersion = () => {\n return PackageJson.version;\n};\n\n/**\n * True inside the plugin's own monorepo, where the plugin is the source rather\n * than a dependency.\n */\nexport const isNxPluginForAwsWorkspace = (tree: Tree): boolean => {\n const rootPackageJson = tree.exists('package.json')\n ? readJson(tree, 'package.json')\n : undefined;\n return rootPackageJson?.name === '@aws/nx-plugin-source';\n};\n\n/**\n * The `@aws/nx-plugin` devDependency entry for a workspace the plugin generates\n * into, keyed to the version the running generators come from. Empty inside the\n * plugin's own monorepo.\n */\nexport const nxPluginSelfDependency = (tree: Tree): Record<string, string> =>\n isNxPluginForAwsWorkspace(tree)\n ? {}\n : { [PackageJson.name]: `^${PackageJson.version}` };\n\n/**\n * The `@aws/nx-plugin-mcp` devDependency entry, keyed to the running generators'\n * version — the two packages are released in lockstep. Declaring it pins the MCP\n * server the vended config runs in the workspace's lockfile, so upgrading it\n * upgrades the server. Empty inside the plugin's own monorepo.\n */\nexport const nxPluginMcpDependency = (tree: Tree): Record<string, string> =>\n isNxPluginForAwsWorkspace(tree)\n ? {}\n : { [NX_PLUGIN_MCP_PACKAGE_NAME]: `^${PackageJson.version}` };\n\n/**\n * Read a project configuration where the project name may not be fully qualified (ie may omit the scope prefix)\n */\nexport const readProjectConfigurationUnqualified = (\n tree: Tree,\n projectName: string,\n) => {\n try {\n return readProjectConfiguration(tree, projectName);\n } catch (e) {\n // Attempt to find the project without the scope\n const project = [...getProjects(tree).values()].find(\n (p) =>\n p.name &&\n (p.name === `${getNpmScopePrefix(tree)}${projectName}` || // TypeScript fully-qualified name\n p.name === `${toSnakeCase(getNpmScope(tree))}.${projectName}`), // Python fully-qualified name\n );\n if (project) {\n return project;\n }\n throw e;\n }\n};\n\n/**\n * Returns whether a project with the given name already exists in the workspace.\n * The project name may be unqualified (ie may omit the scope prefix).\n */\nexport const projectExists = (tree: Tree, projectName: string): boolean => {\n try {\n readProjectConfigurationUnqualified(tree, projectName);\n return true;\n } catch {\n return false;\n }\n};\n\n/**\n * Add metadata about the generator that generated the project to the project.json\n */\nexport const addGeneratorMetadata = (\n tree: Tree,\n projectName: string,\n info: { id: string },\n additionalMetadata?: { [key: string]: any },\n) => {\n const config = readProjectConfigurationUnqualified(tree, projectName);\n const metadata = {\n ...config?.metadata,\n generator: info.id,\n ...additionalMetadata,\n };\n // Skip the write when nothing changed so re-running doesn't reserialize\n // project.json. metadata is plain JSON built in a fixed key order, so a\n // stringify comparison is exact here.\n if (JSON.stringify(config?.metadata) === JSON.stringify(metadata)) {\n return;\n }\n // Place metadata immediately before targets so the serialized key order is\n // identical whether or not metadata already existed (matching the order Nx\n // normalizes a read config to), keeping the change a pure metadata insert.\n const { targets, ...rest } = config;\n updateProjectConfiguration(tree, config.name, {\n ...rest,\n metadata: metadata as any,\n ...(targets ? { targets } : {}),\n });\n};\n\n/**\n * Represents a component entry in project metadata\n */\nexport interface ComponentMetadata {\n readonly generator: string;\n readonly name?: string;\n /**\n * What this entry wires up. For a connection that is the target — the thing\n * being connected to — paired with `sourcePath` below.\n */\n readonly path?: string;\n /**\n * The component the connection is made *from*, when both ends are components\n * of a project rather than whole projects.\n *\n * A connection records the project it lives on and the target it reaches, which\n * alone can't tell which of several components on that project is wired up.\n * Recorded as a path for the same reason `path` is: it identifies a component\n * within its project without depending on a name that may repeat.\n */\n readonly sourcePath?: string;\n [key: string]: any;\n}\n\n/**\n * Add metadata about the generator that generated the component to the project.json\n *\n * A connection between two components passes the source's path as\n * `additionalMetadata.sourcePath`, so the pair is identifiable rather than just\n * the two projects.\n */\nexport const addComponentGeneratorMetadata = (\n tree: Tree,\n projectName: string,\n info: { id: string },\n componentPath: string,\n componentName?: string,\n additionalMetadata?: { [key: string]: any },\n) => {\n const config = readProjectConfigurationUnqualified(tree, projectName);\n\n const existingComponents = (config?.metadata as any)?.components ?? [];\n const alreadyAdded = existingComponents.filter(\n (c: any) => c.generator === info.id && c.name === componentName,\n );\n\n if (alreadyAdded.length === 0) {\n const componentMetadata: ComponentMetadata = {\n generator: info.id,\n path: componentPath,\n ...(componentName ? { name: componentName } : {}),\n ...additionalMetadata,\n };\n // Place metadata before targets for a stable serialized key order.\n const { targets, ...rest } = config;\n updateProjectConfiguration(tree, config.name, {\n ...rest,\n metadata: {\n ...config?.metadata,\n components: [...existingComponents, componentMetadata],\n } as any,\n ...(targets ? { targets } : {}),\n });\n }\n};\n\n/**\n * Merge a generator's own config into an `nx.json` `targetDefaults` value,\n * preserving whatever the workspace already had. `apply` receives the config to\n * layer onto and returns the merged config (e.g. `(base) => ({ cache: true,\n * ...base })`); it must be idempotent so re-running the generator is a no-op.\n *\n * Nx 23.1 widened each value to either a config object or an ordered array of\n * filtered entries. The plugin only contributes unfiltered (catch-all) config,\n * so the input's shape is preserved: an object (or unset) stays an object;\n * an array keeps the user's filtered entries and `apply` merges into its first\n * unfiltered entry, prepending one as the base if none exists (Nx layers later\n * matches on top, so our catch-all must stay first to not override a filter).\n */\nexport const mergeTargetDefault = (\n value: TargetDefaultValue | undefined,\n apply: (base: Partial<TargetConfiguration>) => Partial<TargetConfiguration>,\n): TargetDefaultValue => {\n if (!Array.isArray(value)) {\n return apply(value ?? {});\n }\n const catchAllIndex = value.findIndex((entry) => entry.filter === undefined);\n if (catchAllIndex === -1) {\n return [apply({}), ...value];\n }\n return value.map((entry, index) =>\n index === catchAllIndex ? apply(entry) : entry,\n );\n};\n\n/**\n * A single entry in an Nx `dependsOn` array.\n * Matches the shape accepted by Nx without requiring a devkit type import.\n */\nexport type TargetDependency =\n | string\n | {\n projects?: string | string[];\n target: string;\n params?: 'ignore' | 'forward';\n };\n\nconst targetDependencyEquals = (a: TargetDependency, b: TargetDependency) => {\n if (typeof a === 'string' || typeof b === 'string') {\n return a === b;\n }\n if (a.target !== b.target || a.params !== b.params) {\n return false;\n }\n const aProjects = Array.isArray(a.projects)\n ? a.projects\n : a.projects !== undefined\n ? [a.projects]\n : [];\n const bProjects = Array.isArray(b.projects)\n ? b.projects\n : b.projects !== undefined\n ? [b.projects]\n : [];\n if (aProjects.length !== bProjects.length) {\n return false;\n }\n return aProjects.every((p, i) => p === bProjects[i]);\n};\n\n// The order target properties are authored in. Nx preserves a target's\n// authored key order when it reads then rewrites an existing project.json,\n// except `options` and `configurations`, which it always moves to the end (in\n// that order). Keeping `options`/`configurations` last here therefore makes a\n// generator's first-run output byte-identical to subsequent runs (idempotency);\n// the remaining keys are ordered to read intuitively.\nconst NX_TARGET_KEY_ORDER = [\n 'executor',\n 'dependsOn',\n 'continuous',\n 'cache',\n 'inputs',\n 'outputs',\n 'metadata',\n 'defaultConfiguration',\n 'options',\n 'configurations',\n];\n\n/**\n * Reorder a target's keys to match Nx's own serialization order. Nx reorders\n * target properties when it rewrites an existing project.json, so applying the\n * same order when first authoring a target keeps generators idempotent.\n */\nexport const normalizeTargetKeyOrder = <T extends object>(target: T): T =>\n Object.fromEntries(\n Object.entries(target as Record<string, unknown>).sort(([a], [b]) => {\n const ai = NX_TARGET_KEY_ORDER.indexOf(a);\n const bi = NX_TARGET_KEY_ORDER.indexOf(b);\n return (\n (ai === -1 ? NX_TARGET_KEY_ORDER.length : ai) -\n (bi === -1 ? NX_TARGET_KEY_ORDER.length : bi)\n );\n }),\n ) as T;\n\n/**\n * Mutate the project to add the dependency to the target if not already present\n * Adds the target if not present.\n *\n * Accepts either a string target name (e.g. `'build'`) or a dependency config\n * object (e.g. `{ projects: ['foo'], target: 'dev' }`). Deduplicates\n * using deep equality so re-running a generator does not grow `dependsOn`.\n */\nexport const addDependencyToTargetIfNotPresent = (\n project: ProjectConfiguration,\n target: string,\n dependency: TargetDependency,\n) => {\n project.targets ??= {};\n project.targets[target] ??= {};\n project.targets[target].dependsOn ??= [];\n const dependsOn = project.targets[target].dependsOn;\n // Leave existing dependencies in place so re-running does not reorder them;\n // only append when the dependency is genuinely absent.\n if (!dependsOn.some((d) => targetDependencyEquals(d, dependency))) {\n dependsOn.push(dependency);\n }\n // Keep key order aligned with Nx's so first run matches subsequent runs.\n project.targets[target] = normalizeTargetKeyOrder(project.targets[target]);\n};\n\n/**\n * Register a component's `<name>-dev` target under the project-level `dev`\n * target, so `nx run <project>:dev` starts every component in the project.\n *\n * Component generators author their own continuous `<name>-dev` runner and call\n * this to aggregate it. Every component added to the project accumulates its\n * `<name>-dev` under `dev`. Nx keys tasks by `project:target`, so any\n * dependencies shared between components run exactly once.\n */\nexport const addComponentDevTarget = (\n targets: Record<string, ProjectConfiguration['targets'][string]>,\n componentDevTargetName: string,\n) => {\n targets['dev'] ??= { continuous: true, dependsOn: [] };\n const projectDev = targets['dev'];\n projectDev.continuous = true;\n projectDev.dependsOn ??= [];\n // Append in component-creation order; dedupe keeps re-runs idempotent.\n if (!projectDev.dependsOn.includes(componentDevTargetName)) {\n projectDev.dependsOn.push(componentDevTargetName);\n }\n targets['dev'] = normalizeTargetKeyOrder(projectDev);\n};\n"],"names":["getProjects","readJson","readProjectConfiguration","updateProjectConfiguration","path","PackageJson","type","NX_PLUGIN_MCP_PACKAGE_NAME","toSnakeCase","getNpmScope","getNpmScopePrefix","buildGeneratorInfoList","GENERATORS","resolve","dirname","listGenerators","includeHidden","filter","g","hidden","getGeneratorInfo","generatorFileName","dir","name","parse","resolvedFactoryPath","join","find","generatorInfo","getPackageVersion","version","isNxPluginForAwsWorkspace","tree","rootPackageJson","exists","undefined","nxPluginSelfDependency","nxPluginMcpDependency","readProjectConfigurationUnqualified","projectName","e","project","values","p","projectExists","addGeneratorMetadata","info","additionalMetadata","config","metadata","generator","id","JSON","stringify","targets","rest","addComponentGeneratorMetadata","componentPath","componentName","existingComponents","components","alreadyAdded","c","length","componentMetadata","mergeTargetDefault","value","apply","Array","isArray","catchAllIndex","findIndex","entry","map","index","targetDependencyEquals","a","b","target","params","aProjects","projects","bProjects","every","i","NX_TARGET_KEY_ORDER","normalizeTargetKeyOrder","Object","fromEntries","entries","sort","ai","indexOf","bi","addDependencyToTargetIfNotPresent","dependency","dependsOn","some","d","push","addComponentDevTarget","componentDevTargetName","continuous","projectDev","includes"],"mappings":"AAAA;;;CAGC,GACD,SACEA,WAAW,EAEXC,QAAQ,EACRC,wBAAwB,EAIxBC,0BAA0B,QACrB,aAAa;AACpB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,iBAAiB,0BAA0B;IAAEC,MAAM;AAAO,EAAE;AACnE,SAASC,0BAA0B,QAAQ,WAAW;AACtD,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,WAAW,EAAEC,iBAAiB,QAAQ,iBAAiB;AAGhE,SAASC,sBAAsB,QAAQ,kBAAkB;AAEzD,SAASA,sBAAsB,QAA4B,kBAAkB;AAE7E,MAAMC,aAAaD,uBACjBP,KAAKS,OAAO,CAAC,YAAYC,OAAO,EAAE,MAAM;AAG1C;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,CAACC,gBAAgB,KAAK,GAClDJ,WAAWK,MAAM,CAAC,CAACC,IAA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ACJ;IACjB;IACA,yEAAyE;IACzEtD,QAAQa,OAAO,CAACwB,OAAO,GAAGQ,wBAAwB7C,QAAQa,OAAO,CAACwB,OAAO;AAC3E,EAAE;AAEF;;;;;;;;CAQC,GACD,OAAO,MAAMsB,wBAAwB,CACnC9C,SACA+C;IAEA/C,OAAO,CAAC,MAAM,KAAK;QAAEgD,YAAY;QAAMN,WAAW,EAAE;IAAC;IACrD,MAAMO,aAAajD,OAAO,CAAC,MAAM;IACjCiD,WAAWD,UAAU,GAAG;IACxBC,WAAWP,SAAS,KAAK,EAAE;IAC3B,uEAAuE;IACvE,IAAI,CAACO,WAAWP,SAAS,CAACQ,QAAQ,CAACH,yBAAyB;QAC1DE,WAAWP,SAAS,CAACG,IAAI,CAACE;IAC5B;IACA/C,OAAO,CAAC,MAAM,GAAGgC,wBAAwBiB;AAC3C,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/nx.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n getProjects,\n type ProjectConfiguration,\n readJson,\n readProjectConfiguration,\n type TargetConfiguration,\n type TargetDefaultValue,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport * as path from 'path';\nimport PackageJson from '../../package.json' with { type: 'json' };\nimport { NX_PLUGIN_MCP_PACKAGE_NAME } from './mcp.js';\nimport { toSnakeCase } from './names.js';\nimport { getNpmScope, getNpmScopePrefix } from './npm-scope.js';\n\nexport type { GeneratorInfo, NxGeneratorInfo } from './generators.js';\nexport { buildGeneratorInfoList } from './generators.js';\n\nimport { buildGeneratorInfoList, type GeneratorInfo } from './generators.js';\n\nconst GENERATORS = buildGeneratorInfoList(\n path.resolve(import.meta.dirname, '..', '..'),\n);\n\n/**\n * List Nx Plugin for AWS generators\n * @param includeHidden include hidden generators (default false)\n */\nexport const listGenerators = (includeHidden = false) =>\n GENERATORS.filter((g) => includeHidden || !g.hidden);\n\n/**\n * Return generator information. Call this from a generator method with import.meta.filename\n */\nexport const getGeneratorInfo = (generatorFileName: string): GeneratorInfo => {\n const { dir, name } = path.parse(path.resolve(generatorFileName));\n const resolvedFactoryPath = path.join(dir, name);\n return GENERATORS.find(\n (generatorInfo) =>\n generatorInfo.resolvedFactoryPath === resolvedFactoryPath,\n );\n};\n\nexport const getPackageVersion = () => {\n return PackageJson.version;\n};\n\n/**\n * True inside the plugin's own monorepo, where the plugin is the source rather\n * than a dependency.\n */\nexport const isNxPluginForAwsWorkspace = (tree: Tree): boolean => {\n const rootPackageJson = tree.exists('package.json')\n ? readJson(tree, 'package.json')\n : undefined;\n return rootPackageJson?.name === '@aws/nx-plugin-source';\n};\n\n/**\n * The `@aws/nx-plugin` devDependency entry for a workspace the plugin generates\n * into, keyed to the version the running generators come from. Empty inside the\n * plugin's own monorepo.\n */\nexport const nxPluginSelfDependency = (tree: Tree): Record<string, string> =>\n isNxPluginForAwsWorkspace(tree)\n ? {}\n : { [PackageJson.name]: `^${PackageJson.version}` };\n\n/**\n * The `@aws/nx-plugin-mcp` devDependency entry, keyed to the running generators'\n * version — the two packages are released in lockstep. Declaring it pins the MCP\n * server the vended config runs in the workspace's lockfile, so upgrading it\n * upgrades the server. Empty inside the plugin's own monorepo.\n */\nexport const nxPluginMcpDependency = (tree: Tree): Record<string, string> =>\n isNxPluginForAwsWorkspace(tree)\n ? {}\n : { [NX_PLUGIN_MCP_PACKAGE_NAME]: `^${PackageJson.version}` };\n\n/**\n * Read a project configuration where the project name may not be fully qualified (ie may omit the scope prefix)\n */\nexport const readProjectConfigurationUnqualified = (\n tree: Tree,\n projectName: string,\n) => {\n try {\n return readProjectConfiguration(tree, projectName);\n } catch (e) {\n // Attempt to find the project without the scope\n const project = [...getProjects(tree).values()].find(\n (p) =>\n p.name &&\n (p.name === `${getNpmScopePrefix(tree)}${projectName}` || // TypeScript fully-qualified name\n p.name === `${toSnakeCase(getNpmScope(tree))}.${projectName}`), // Python fully-qualified name\n );\n if (project) {\n return project;\n }\n throw e;\n }\n};\n\n/**\n * Returns whether a project with the given name already exists in the workspace.\n * The project name may be unqualified (ie may omit the scope prefix).\n */\nexport const projectExists = (tree: Tree, projectName: string): boolean => {\n try {\n readProjectConfigurationUnqualified(tree, projectName);\n return true;\n } catch {\n return false;\n }\n};\n\n/**\n * Add metadata about the generator that generated the project to the project.json\n */\nexport const addGeneratorMetadata = (\n tree: Tree,\n projectName: string,\n info: { id: string },\n additionalMetadata?: { [key: string]: any },\n) => {\n const config = readProjectConfigurationUnqualified(tree, projectName);\n const metadata = {\n ...config?.metadata,\n generator: info.id,\n ...additionalMetadata,\n };\n // Skip the write when nothing changed so re-running doesn't reserialize\n // project.json. metadata is plain JSON built in a fixed key order, so a\n // stringify comparison is exact here.\n if (JSON.stringify(config?.metadata) === JSON.stringify(metadata)) {\n return;\n }\n // Place metadata immediately before targets so the serialized key order is\n // identical whether or not metadata already existed (matching the order Nx\n // normalizes a read config to), keeping the change a pure metadata insert.\n const { targets, ...rest } = config;\n updateProjectConfiguration(tree, config.name, {\n ...rest,\n metadata: metadata as any,\n ...(targets ? { targets } : {}),\n });\n};\n\n/**\n * Represents a component entry in project metadata\n */\nexport interface ComponentMetadata {\n readonly generator: string;\n readonly name?: string;\n /**\n * What this entry wires up. For a connection that is the target — the thing\n * being connected to — paired with `sourcePath` below.\n */\n readonly path?: string;\n /**\n * The component the connection is made *from*, when both ends are components\n * of a project rather than whole projects.\n *\n * A connection records the project it lives on and the target it reaches, which\n * alone can't tell which of several components on that project is wired up.\n * Recorded as a path for the same reason `path` is: it identifies a component\n * within its project without depending on a name that may repeat.\n */\n readonly sourcePath?: string;\n [key: string]: any;\n}\n\n/**\n * Add metadata about the generator that generated the component to the project.json\n *\n * A connection between two components passes the source's path as\n * `additionalMetadata.sourcePath`, so the pair is identifiable rather than just\n * the two projects.\n */\nexport const addComponentGeneratorMetadata = (\n tree: Tree,\n projectName: string,\n info: { id: string },\n componentPath: string,\n componentName?: string,\n additionalMetadata?: { [key: string]: any },\n) => {\n const config = readProjectConfigurationUnqualified(tree, projectName);\n\n const existingComponents = (config?.metadata as any)?.components ?? [];\n const alreadyAdded = existingComponents.filter(\n (c: any) => c.generator === info.id && c.name === componentName,\n );\n\n if (alreadyAdded.length === 0) {\n const componentMetadata: ComponentMetadata = {\n generator: info.id,\n path: componentPath,\n ...(componentName ? { name: componentName } : {}),\n ...additionalMetadata,\n };\n // Place metadata before targets for a stable serialized key order.\n const { targets, ...rest } = config;\n updateProjectConfiguration(tree, config.name, {\n ...rest,\n metadata: {\n ...config?.metadata,\n components: [...existingComponents, componentMetadata],\n } as any,\n ...(targets ? { targets } : {}),\n });\n }\n};\n\n/**\n * Merge a generator's own config into an `nx.json` `targetDefaults` value,\n * preserving whatever the workspace already had. `apply` receives the config to\n * layer onto and returns the merged config (e.g. `(base) => ({ cache: true,\n * ...base })`); it must be idempotent so re-running the generator is a no-op.\n *\n * Nx 23.1 widened each value to either a config object or an ordered array of\n * filtered entries. The plugin only contributes unfiltered (catch-all) config,\n * so the input's shape is preserved: an object (or unset) stays an object;\n * an array keeps the user's filtered entries and `apply` merges into its first\n * unfiltered entry, prepending one as the base if none exists (Nx layers later\n * matches on top, so our catch-all must stay first to not override a filter).\n */\nexport const mergeTargetDefault = (\n value: TargetDefaultValue | undefined,\n apply: (base: Partial<TargetConfiguration>) => Partial<TargetConfiguration>,\n): TargetDefaultValue => {\n if (!Array.isArray(value)) {\n return apply(value ?? {});\n }\n const catchAllIndex = value.findIndex((entry) => entry.filter === undefined);\n if (catchAllIndex === -1) {\n return [apply({}), ...value];\n }\n return value.map((entry, index) =>\n index === catchAllIndex ? apply(entry) : entry,\n );\n};\n\n/**\n * A single entry in an Nx `dependsOn` array.\n * Matches the shape accepted by Nx without requiring a devkit type import.\n */\nexport type TargetDependency =\n | string\n | {\n projects?: string | string[];\n target: string;\n params?: 'ignore' | 'forward';\n };\n\nconst targetDependencyEquals = (a: TargetDependency, b: TargetDependency) => {\n if (typeof a === 'string' || typeof b === 'string') {\n return a === b;\n }\n if (a.target !== b.target || a.params !== b.params) {\n return false;\n }\n const aProjects = Array.isArray(a.projects)\n ? a.projects\n : a.projects !== undefined\n ? [a.projects]\n : [];\n const bProjects = Array.isArray(b.projects)\n ? b.projects\n : b.projects !== undefined\n ? [b.projects]\n : [];\n if (aProjects.length !== bProjects.length) {\n return false;\n }\n return aProjects.every((p, i) => p === bProjects[i]);\n};\n\n// The order target properties are authored in. Nx preserves a target's\n// authored key order when it reads then rewrites an existing project.json,\n// except `options` and `configurations`, which it always moves to the end (in\n// that order). Keeping `options`/`configurations` last here therefore makes a\n// generator's first-run output byte-identical to subsequent runs (idempotency);\n// the remaining keys are ordered to read intuitively.\nconst NX_TARGET_KEY_ORDER = [\n 'executor',\n 'dependsOn',\n 'continuous',\n 'cache',\n 'inputs',\n 'outputs',\n 'metadata',\n 'defaultConfiguration',\n 'options',\n 'configurations',\n];\n\n/**\n * Reorder a target's keys to match Nx's own serialization order. Nx reorders\n * target properties when it rewrites an existing project.json, so applying the\n * same order when first authoring a target keeps generators idempotent.\n */\nexport const normalizeTargetKeyOrder = <T extends object>(target: T): T =>\n Object.fromEntries(\n Object.entries(target as Record<string, unknown>).sort(([a], [b]) => {\n const ai = NX_TARGET_KEY_ORDER.indexOf(a);\n const bi = NX_TARGET_KEY_ORDER.indexOf(b);\n return (\n (ai === -1 ? NX_TARGET_KEY_ORDER.length : ai) -\n (bi === -1 ? NX_TARGET_KEY_ORDER.length : bi)\n );\n }),\n ) as T;\n\n/**\n * Mutate the project to add the dependency to the target if not already present\n * Adds the target if not present.\n *\n * Accepts either a string target name (e.g. `'build'`) or a dependency config\n * object (e.g. `{ projects: ['foo'], target: 'dev' }`). Deduplicates\n * using deep equality so re-running a generator does not grow `dependsOn`.\n */\nexport const addDependencyToTargetIfNotPresent = (\n project: ProjectConfiguration,\n target: string,\n dependency: TargetDependency,\n) => {\n project.targets ??= {};\n project.targets[target] ??= {};\n project.targets[target].dependsOn ??= [];\n const dependsOn = project.targets[target].dependsOn;\n // Leave existing dependencies in place so re-running does not reorder them;\n // only append when the dependency is genuinely absent.\n if (!dependsOn.some((d) => targetDependencyEquals(d, dependency))) {\n dependsOn.push(dependency);\n }\n // Keep key order aligned with Nx's so first run matches subsequent runs.\n project.targets[target] = normalizeTargetKeyOrder(project.targets[target]);\n};\n\n/**\n * Register a dependency that produces a deployable artifact on both `build` and\n * `assemble`.\n *\n * `build` is the everything target: artifacts plus the quality gates (lint,\n * test, typecheck). `assemble` is its artifact-only sibling, which the deploy\n * targets depend on so a deploy builds what it deploys and nothing else.\n */\nexport const addArtifactDependencyToTargets = (\n project: ProjectConfiguration,\n dependency: TargetDependency,\n) => {\n addDependencyToTargetIfNotPresent(project, 'build', dependency);\n addDependencyToTargetIfNotPresent(project, 'assemble', dependency);\n};\n\n/**\n * Register another project whose artifacts this one consumes, on both `build`\n * and `assemble`.\n *\n * The shared infrastructure project reads the artifacts of every project it\n * deploys, and those cross-project edges are explicit because Nx's `^` operator\n * only follows package dependencies. `assemble` mirrors the list against the\n * consumed projects' own `assemble`, keeping the artifact-only chain closed.\n */\nexport const addArtifactProjectToTargets = (\n project: ProjectConfiguration,\n consumedProjectName: string,\n) => {\n addDependencyToTargetIfNotPresent(\n project,\n 'build',\n `${consumedProjectName}:build`,\n );\n addDependencyToTargetIfNotPresent(\n project,\n 'assemble',\n `${consumedProjectName}:assemble`,\n );\n};\n\n/**\n * Register a component's `<name>-dev` target under the project-level `dev`\n * target, so `nx run <project>:dev` starts every component in the project.\n *\n * Component generators author their own continuous `<name>-dev` runner and call\n * this to aggregate it. Every component added to the project accumulates its\n * `<name>-dev` under `dev`. Nx keys tasks by `project:target`, so any\n * dependencies shared between components run exactly once.\n */\nexport const addComponentDevTarget = (\n targets: Record<string, ProjectConfiguration['targets'][string]>,\n componentDevTargetName: string,\n) => {\n targets['dev'] ??= { continuous: true, dependsOn: [] };\n const projectDev = targets['dev'];\n projectDev.continuous = true;\n projectDev.dependsOn ??= [];\n // Append in component-creation order; dedupe keeps re-runs idempotent.\n if (!projectDev.dependsOn.includes(componentDevTargetName)) {\n projectDev.dependsOn.push(componentDevTargetName);\n }\n targets['dev'] = normalizeTargetKeyOrder(projectDev);\n};\n"],"names":["getProjects","readJson","readProjectConfiguration","updateProjectConfiguration","path","PackageJson","type","NX_PLUGIN_MCP_PACKAGE_NAME","toSnakeCase","getNpmScope","getNpmScopePrefix","buildGeneratorInfoList","GENERATORS","resolve","dirname","listGenerators","includeHidden","filter","g","hidden","getGeneratorInfo","generatorFileName","dir","name","parse","resolvedFactoryPath","join","find","generatorInfo","getPackageVersion","version","isNxPluginForAwsWorkspace","tree","rootPackageJson","exists","undefined","nxPluginSelfDependency","nxPluginMcpDependency","readProjectConfigurationUnqualified","projectName","e","project","values","p","projectExists","addGeneratorMetadata","info","additionalMetadata","config","metadata","generator","id","JSON","stringify","targets","rest","addComponentGeneratorMetadata","componentPath","componentName","existingComponents","components","alreadyAdded","c","length","componentMetadata","mergeTargetDefault","value","apply","Array","isArray","catchAllIndex","findIndex","entry","map","index","targetDependencyEquals","a","b","target","params","aProjects","projects","bProjects","every","i","NX_TARGET_KEY_ORDER","normalizeTargetKeyOrder","Object","fromEntries","entries","sort","ai","indexOf","bi","addDependencyToTargetIfNotPresent","dependency","dependsOn","some","d","push","addArtifactDependencyToTargets","addArtifactProjectToTargets","consumedProjectName","addComponentDevTarget","componentDevTargetName","continuous","projectDev","includes"],"mappings":"AAAA;;;CAGC,GACD,SACEA,WAAW,EAEXC,QAAQ,EACRC,wBAAwB,EAIxBC,0BAA0B,QACrB,aAAa;AACpB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,iBAAiB,0BAA0B;IAAEC,MAAM;AAAO,EAAE;AACnE,SAASC,0BAA0B,QAAQ,WAAW;AACtD,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,WAAW,EAAEC,iBAAiB,QAAQ,iBAAiB;AAGhE,SAASC,sBAAsB,QA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
|
+
import type { TargetConfiguration } from '@nx/devkit';
|
|
6
|
+
import type { OpenApiCodegenTarget } from '../open-api/codegen/executor-schema';
|
|
7
|
+
/** Executor generated OpenAPI codegen targets run. */
|
|
8
|
+
export declare const OPEN_API_CODEGEN_EXECUTOR = "@aws/nx-plugin:open-api-codegen";
|
|
9
|
+
export interface OpenApiCodegenTargetOptions {
|
|
10
|
+
/** Which code to generate from the specification. */
|
|
11
|
+
readonly generator: OpenApiCodegenTarget;
|
|
12
|
+
/** Path to the OpenAPI specification, from the workspace root. */
|
|
13
|
+
readonly openApiSpecPath: string;
|
|
14
|
+
/** Directory to generate into, from the workspace root. */
|
|
15
|
+
readonly outputPath: string;
|
|
16
|
+
/** Target which builds the OpenAPI specification. */
|
|
17
|
+
readonly specBuildTargetName: string;
|
|
18
|
+
/** Paths the target writes, in Nx `outputs` form. */
|
|
19
|
+
readonly outputs: string[];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A target which generates code from an OpenAPI specification.
|
|
23
|
+
*
|
|
24
|
+
* The executor runs the generator in the Nx process that is already running,
|
|
25
|
+
* rather than shelling out to `nx g`, which would pay a second full Nx
|
|
26
|
+
* bootstrap for every codegen step.
|
|
27
|
+
*/
|
|
28
|
+
export declare const openApiCodegenTarget: ({ generator, openApiSpecPath, outputPath, specBuildTargetName, outputs, }: OpenApiCodegenTargetOptions) => TargetConfiguration;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/ import { normalizeTargetKeyOrder } from "./nx.js";
|
|
5
|
+
/** Executor generated OpenAPI codegen targets run. */ export const OPEN_API_CODEGEN_EXECUTOR = '@aws/nx-plugin:open-api-codegen';
|
|
6
|
+
/**
|
|
7
|
+
* A target which generates code from an OpenAPI specification.
|
|
8
|
+
*
|
|
9
|
+
* The executor runs the generator in the Nx process that is already running,
|
|
10
|
+
* rather than shelling out to `nx g`, which would pay a second full Nx
|
|
11
|
+
* bootstrap for every codegen step.
|
|
12
|
+
*/ export const openApiCodegenTarget = ({ generator, openApiSpecPath, outputPath, specBuildTargetName, outputs })=>normalizeTargetKeyOrder({
|
|
13
|
+
executor: OPEN_API_CODEGEN_EXECUTOR,
|
|
14
|
+
dependsOn: [
|
|
15
|
+
specBuildTargetName
|
|
16
|
+
],
|
|
17
|
+
cache: true,
|
|
18
|
+
inputs: [
|
|
19
|
+
{
|
|
20
|
+
dependentTasksOutputFiles: '**/*.json'
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
outputs,
|
|
24
|
+
options: {
|
|
25
|
+
generator,
|
|
26
|
+
openApiSpecPath,
|
|
27
|
+
outputPath
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=open-api-codegen-target.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/open-api-codegen-target.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { TargetConfiguration } from '@nx/devkit';\nimport type { OpenApiCodegenTarget } from '../open-api/codegen/executor-schema';\nimport { normalizeTargetKeyOrder } from './nx.js';\n\n/** Executor generated OpenAPI codegen targets run. */\nexport const OPEN_API_CODEGEN_EXECUTOR = '@aws/nx-plugin:open-api-codegen';\n\nexport interface OpenApiCodegenTargetOptions {\n /** Which code to generate from the specification. */\n readonly generator: OpenApiCodegenTarget;\n /** Path to the OpenAPI specification, from the workspace root. */\n readonly openApiSpecPath: string;\n /** Directory to generate into, from the workspace root. */\n readonly outputPath: string;\n /** Target which builds the OpenAPI specification. */\n readonly specBuildTargetName: string;\n /** Paths the target writes, in Nx `outputs` form. */\n readonly outputs: string[];\n}\n\n/**\n * A target which generates code from an OpenAPI specification.\n *\n * The executor runs the generator in the Nx process that is already running,\n * rather than shelling out to `nx g`, which would pay a second full Nx\n * bootstrap for every codegen step.\n */\nexport const openApiCodegenTarget = ({\n generator,\n openApiSpecPath,\n outputPath,\n specBuildTargetName,\n outputs,\n}: OpenApiCodegenTargetOptions): TargetConfiguration =>\n normalizeTargetKeyOrder({\n executor: OPEN_API_CODEGEN_EXECUTOR,\n dependsOn: [specBuildTargetName],\n cache: true,\n inputs: [\n {\n dependentTasksOutputFiles: '**/*.json',\n },\n ],\n outputs,\n options: {\n generator,\n openApiSpecPath,\n outputPath,\n },\n });\n"],"names":["normalizeTargetKeyOrder","OPEN_API_CODEGEN_EXECUTOR","openApiCodegenTarget","generator","openApiSpecPath","outputPath","specBuildTargetName","outputs","executor","dependsOn","cache","inputs","dependentTasksOutputFiles","options"],"mappings":"AAAA;;;CAGC,GAGD,SAASA,uBAAuB,QAAQ,UAAU;AAElD,oDAAoD,GACpD,OAAO,MAAMC,4BAA4B,kCAAkC;AAe3E;;;;;;CAMC,GACD,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,SAAS,EACTC,eAAe,EACfC,UAAU,EACVC,mBAAmB,EACnBC,OAAO,EACqB,GAC5BP,wBAAwB;QACtBQ,UAAUP;QACVQ,WAAW;YAACH;SAAoB;QAChCI,OAAO;QACPC,QAAQ;YACN;gBACEC,2BAA2B;YAC7B;SACD;QACDL;QACAM,SAAS;YACPV;YACAC;YACAC;QACF;IACF,GAAG"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/ import { generateFiles, joinPathFragments, OverwriteStrategy, updateJson } from "@nx/devkit";
|
|
5
5
|
import { addStarExport } from "../ast.js";
|
|
6
6
|
import { esmVars } from "../module-format.js";
|
|
7
|
-
import {
|
|
7
|
+
import { addArtifactProjectToTargets } from "../nx.js";
|
|
8
8
|
import { PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, SHARED_TERRAFORM_DIR } from "../shared-constructs-constants.js";
|
|
9
9
|
import { cdkLambdaRuntimeVars, terraformLambdaRuntimeVars, terraformProviderVersions } from "../versions.js";
|
|
10
10
|
/**
|
|
@@ -34,7 +34,7 @@ export const addRdbInfra = async (tree, options)=>{
|
|
|
34
34
|
throw new Error(`Unsupported iac ${options.iac}`);
|
|
35
35
|
}
|
|
36
36
|
updateJson(tree, joinPathFragments(PACKAGES_DIR, options.iac === 'cdk' ? SHARED_CONSTRUCTS_DIR : SHARED_TERRAFORM_DIR, 'project.json'), (config)=>{
|
|
37
|
-
|
|
37
|
+
addArtifactProjectToTargets(config, options.projectName);
|
|
38
38
|
return config;
|
|
39
39
|
});
|
|
40
40
|
};
|