@aws/nx-plugin 1.0.0-rc.37 → 1.0.0-rc.38
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/generators.json +7 -0
- package/package.json +1 -1
- package/src/init/generator.d.ts +18 -0
- package/src/init/generator.js +35 -0
- package/src/init/generator.js.map +1 -0
- package/src/init/schema.d.js +6 -0
- package/src/init/schema.d.js.map +1 -0
- package/src/init/schema.d.ts +16 -0
- package/src/init/schema.json +35 -0
- package/src/mcp-server/generator-info.js +27 -13
- package/src/mcp-server/generator-info.js.map +1 -1
- package/src/mcp-server/guide-pipeline.js +16 -1
- package/src/mcp-server/guide-pipeline.js.map +1 -1
- package/src/mcp-server/server.js +2 -0
- package/src/mcp-server/server.js.map +1 -1
- package/src/mcp-server/tools/add-to-existing-project.d.ts +12 -0
- package/src/mcp-server/tools/add-to-existing-project.js +36 -0
- package/src/mcp-server/tools/add-to-existing-project.js.map +1 -0
- package/src/mcp-server/tools/general-guidance.d.ts +1 -1
- package/src/mcp-server/tools/general-guidance.js +1 -0
- package/src/mcp-server/tools/general-guidance.js.map +1 -1
- package/src/preset/__snapshots__/generator.spec.ts.snap +3 -0
- package/src/preset/generator.js +19 -129
- package/src/preset/generator.js.map +1 -1
- package/src/ts/lib/ts-project-utils.js +0 -7
- package/src/ts/lib/ts-project-utils.js.map +1 -1
- package/src/utils/base-tsconfig.d.ts +30 -0
- package/src/utils/base-tsconfig.js +32 -0
- package/src/utils/base-tsconfig.js.map +1 -0
- package/src/utils/commands.d.ts +9 -2
- package/src/utils/commands.js +19 -9
- package/src/utils/commands.js.map +1 -1
- package/src/utils/init.d.ts +53 -0
- package/src/utils/init.js +251 -0
- package/src/utils/init.js.map +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/mcp-server/tools/add-to-existing-project.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { NxGeneratorInfo } from '../../utils/generators';\nimport { fetchGuidePages } from '../generator-info';\nimport { PackageManagerSchema } from '../schema';\n\n/**\n * The guide page (under `get_started/`) that backs this tool, so the tool and\n * the published docs never drift.\n */\nconst EXISTING_PROJECT_GUIDE = 'existing-project';\n\n/**\n * Add a tool which guides an agent through adding @aws/nx-plugin to an\n * existing Nx or non-Nx workspace. Returns the `existing-project` docs page,\n * which includes the full adoption steps and troubleshooting reference.\n */\nexport const addToExistingProjectTool = (\n server: McpServer,\n generators: NxGeneratorInfo[],\n) => {\n server.registerTool(\n 'add-to-existing-project',\n {\n title: 'Add to Existing Project',\n description:\n 'Tool for adding the Nx Plugin for AWS to an existing Nx workspace or non-Nx monorepo. Use this when a user wants to adopt @aws/nx-plugin in a project that was not created with the plugin preset, or hits configuration errors when running generators in such a workspace.',\n inputSchema: {\n packageManager: PackageManagerSchema.optional(),\n },\n },\n async ({ packageManager }) => {\n const guide = await fetchGuidePages(\n [EXISTING_PROJECT_GUIDE],\n generators,\n packageManager,\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: guide,\n },\n ],\n };\n },\n );\n};\n"],"names":["fetchGuidePages","PackageManagerSchema","EXISTING_PROJECT_GUIDE","addToExistingProjectTool","server","generators","registerTool","title","description","inputSchema","packageManager","optional","guide","content","type","text"],"mappings":"AAAA;;;CAGC,GAGD,SAASA,eAAe,QAAQ,uBAAoB;AACpD,SAASC,oBAAoB,QAAQ,eAAY;AAEjD;;;CAGC,GACD,MAAMC,yBAAyB;AAE/B;;;;CAIC,GACD,OAAO,MAAMC,2BAA2B,CACtCC,QACAC;IAEAD,OAAOE,YAAY,CACjB,2BACA;QACEC,OAAO;QACPC,aACE;QACFC,aAAa;YACXC,gBAAgBT,qBAAqBU,QAAQ;QAC/C;IACF,GACA,OAAO,EAAED,cAAc,EAAE;QACvB,MAAME,QAAQ,MAAMZ,gBAClB;YAACE;SAAuB,EACxBG,YACAK;QAEF,OAAO;YACLG,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAMH;gBACR;aACD;QACH;IACF;AAEJ,EAAE"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
6
6
|
import type { NxGeneratorInfo } from '../../utils/generators';
|
|
7
|
-
export declare const TOOL_SELECTION_GUIDE = "## Tool Selection Guide\n\n- Use the `general-guidance` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.\n- Use the `create-workspace-command` tool to discover how to create a workspace to start a new project.\n- Use the `list-generators` tool to discover the available generators and how to run them.\n- Use the `generator-guide` tool to retrieve detailed information about a specific generator.";
|
|
7
|
+
export declare const TOOL_SELECTION_GUIDE = "## Tool Selection Guide\n\n- Use the `general-guidance` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.\n- Use the `create-workspace-command` tool to discover how to create a workspace to start a new project.\n- Use the `add-to-existing-project` tool when adding the plugin to an existing Nx workspace or non-Nx monorepo, or when troubleshooting configuration errors in such a workspace.\n- Use the `list-generators` tool to discover the available generators and how to run them.\n- Use the `generator-guide` tool to retrieve detailed information about a specific generator.";
|
|
8
8
|
/**
|
|
9
9
|
* Add a tool which provides general guidance for using Nx and the Nx Plugin for AWS
|
|
10
10
|
*/
|
|
@@ -8,6 +8,7 @@ export const TOOL_SELECTION_GUIDE = `## Tool Selection Guide
|
|
|
8
8
|
|
|
9
9
|
- Use the \`general-guidance\` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.
|
|
10
10
|
- Use the \`create-workspace-command\` tool to discover how to create a workspace to start a new project.
|
|
11
|
+
- Use the \`add-to-existing-project\` tool when adding the plugin to an existing Nx workspace or non-Nx monorepo, or when troubleshooting configuration errors in such a workspace.
|
|
11
12
|
- Use the \`list-generators\` tool to discover the available generators and how to run them.
|
|
12
13
|
- Use the \`generator-guide\` tool to retrieve detailed information about a specific generator.`;
|
|
13
14
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/mcp-server/tools/general-guidance.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { NxGeneratorInfo } from '../../utils/generators';\nimport { IAC_PROVIDERS } from '../../utils/iac-providers';\nimport { buildNxCommand, fetchGuidePages } from '../generator-info';\nimport { PACKAGE_MANAGERS } from '../schema';\n\nexport const TOOL_SELECTION_GUIDE = `## Tool Selection Guide\n\n- Use the \\`general-guidance\\` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.\n- Use the \\`create-workspace-command\\` tool to discover how to create a workspace to start a new project.\n- Use the \\`list-generators\\` tool to discover the available generators and how to run them.\n- Use the \\`generator-guide\\` tool to retrieve detailed information about a specific generator.`;\n\n/**\n * Add a tool which provides general guidance for using Nx and the Nx Plugin for AWS\n */\nexport const addGeneralGuidanceTool = (\n server: McpServer,\n generators: NxGeneratorInfo[],\n) => {\n server.registerTool(\n 'general-guidance',\n {\n title: 'General Guidance',\n description:\n 'Tool for guidance and best practices for working with Nx and the Nx Plugin for AWS',\n },\n async () => ({\n content: [\n {\n type: 'text' as const,\n text: `# Nx Plugin for AWS Guidance\n\n${TOOL_SELECTION_GUIDE}\n\n## Getting Started\n\n- Choose a package manager first. You can choose between ${PACKAGE_MANAGERS.join(', ')}. It's recommended to use \"pnpm\" if the user has no preference\n- Choose an infrastructure as code (IaC) provider next. You can choose between ${IAC_PROVIDERS.join(', ')}. It's recommended to use CDK if the user has no preference\n- Next, you must create an Nx workspace. Use the \\`create-workspace-command\\` tool for more details, and provide it with your chosen package manager\n- After this, you can start scaffolding the main components of your application using generators. Use the \\`list-generators\\` tool to discover available generators, and the \\`generator-guide\\` tool for more detailed information about a specific generator\n\n## Nx Primer\n\n- Prefix nx commands with the appropriate prefix for your package manager, for example:\n${PACKAGE_MANAGERS.map((pm) => buildNxCommand('<options>', pm)).join(' - \\n')}\n- Each project in your workspace has a file named \\`project.json\\` which contains important project information such as its name, and defines the \"targets\" which can be run for that project, for example building or testing the project\n- Use the command \\`nx reset\\` to reset the Nx daemon when unexpected issues arise\n- After adding dependencies between TypeScript projects, use \\`nx sync\\` to ensure project references are set up correctly\n\n## General Instructions\n\n- Workspaces contain a single \\`package.json\\` file at the root which defines the dependencies for all projects. Therefore when installing dependencies, you must add these to the root workspace using the appropriate command for your package manager:\n - pnpm add -w -D <package>\n - yarn add -D <package>\n - npm install --legacy-peer-deps -D <package>\n - bun install -D <package>\n - (Omit -D for production dependencies)\n- When specifying project names as arguments to generators, prefer the _fully qualified_ project name, for example \\`@workspace-name/project-name\\`. Check the \\`project.json\\` file for the specific package to find its fully qualified name\n- When no generator exists for a specific framework required, use the base \\`ts#project\\` and \\`py#project\\` generators and build on top.\n- Leave the \\`--infra\\` option at its default value unless the user has explicitly instructed otherwise. Generators choose a sensible default type of infrastructure to deploy the project with, so only override \\`--infra\\` when the user has specified a particular requirement.\n\n## Useful Commands\n\n- Fix lint issues with \\`nx run-many --target lint --configuration=fix --all --output-style=stream\\`\n- Build all projects with \\`nx run-many --target build --all --output-style=stream\\`\n- Prefer importing the CDK constructs vended by generators in \\`packages/common/constructs\\` over writing your own\n\n## Best Practices\n\n- After running a generator, use the \\`nx show projects\\` command to check which projects have been added (if any)\n- Carefully examine the files that have been generated and always refer back to the generator guide when working in a generated project\n- Generate all projects into the \\`packages/\\` directory\n- After making changes to your projects, fix linting issues, then run a full build\n- When it's time to start testing a project, suggest to the user that infrastructure is deployed to AWS. For websites, if a runtime-config.json is needed, use the load:runtime-config target after a deployment to point a local website at a sandbox stack.\n\n## Batching Generators\n\nWhen scaffolding several projects in one go, chain generators to avoid a slow dependency install after every generator:\n\n- **Chain generators** with \\`&&\\` in a single command. Pass \\`--prefer-install-dependencies=false\\` on each generator except the last so dependencies install once at the end, for example:\n\n${PACKAGE_MANAGERS.map(\n (pm) => ` \\`\\`\\`bash\n ${buildNxCommand('g @aws/nx-plugin:ts#trpc-api --no-interactive --name=my-app-api --auth=IAM --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:ts#react-website --no-interactive --name=my-app-website --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:connection --no-interactive --sourceProject=@my-app/my-app-website --targetProject=@my-app/my-app-api --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:ts#infra --no-interactive --name=infra', pm)} && \\\\\n ${buildNxCommand('sync', pm)}\n \\`\\`\\``,\n).join('\\n')}\n\n- **\\`--prefer-install-dependencies=false\\`** asks a generator to defer its dependency install so the batch installs once at the end (the final generator above omits the flag and installs everything).\n- **\\`nx sync\\`** is required before building — generators modify TypeScript project references.\n\n## Detailed Guides\n\nPlease refer to the below documentation for important details regarding workspaces and working with TypeScript or Python projects.\n\n${await fetchGuidePages(['workspace', 'typescript-project', 'python-project'], generators)}\n\n `,\n },\n ],\n }),\n );\n};\n"],"names":["IAC_PROVIDERS","buildNxCommand","fetchGuidePages","PACKAGE_MANAGERS","TOOL_SELECTION_GUIDE","addGeneralGuidanceTool","server","generators","registerTool","title","description","content","type","text","join","map","pm"],"mappings":"AAAA;;;CAGC,GAGD,SAASA,aAAa,QAAQ,+BAA4B;AAC1D,SAASC,cAAc,EAAEC,eAAe,QAAQ,uBAAoB;AACpE,SAASC,gBAAgB,QAAQ,eAAY;AAE7C,OAAO,MAAMC,uBAAuB,CAAC
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/mcp-server/tools/general-guidance.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { NxGeneratorInfo } from '../../utils/generators';\nimport { IAC_PROVIDERS } from '../../utils/iac-providers';\nimport { buildNxCommand, fetchGuidePages } from '../generator-info';\nimport { PACKAGE_MANAGERS } from '../schema';\n\nexport const TOOL_SELECTION_GUIDE = `## Tool Selection Guide\n\n- Use the \\`general-guidance\\` tool for guidance and best practices for working with Nx and the Nx Plugin for AWS.\n- Use the \\`create-workspace-command\\` tool to discover how to create a workspace to start a new project.\n- Use the \\`add-to-existing-project\\` tool when adding the plugin to an existing Nx workspace or non-Nx monorepo, or when troubleshooting configuration errors in such a workspace.\n- Use the \\`list-generators\\` tool to discover the available generators and how to run them.\n- Use the \\`generator-guide\\` tool to retrieve detailed information about a specific generator.`;\n\n/**\n * Add a tool which provides general guidance for using Nx and the Nx Plugin for AWS\n */\nexport const addGeneralGuidanceTool = (\n server: McpServer,\n generators: NxGeneratorInfo[],\n) => {\n server.registerTool(\n 'general-guidance',\n {\n title: 'General Guidance',\n description:\n 'Tool for guidance and best practices for working with Nx and the Nx Plugin for AWS',\n },\n async () => ({\n content: [\n {\n type: 'text' as const,\n text: `# Nx Plugin for AWS Guidance\n\n${TOOL_SELECTION_GUIDE}\n\n## Getting Started\n\n- Choose a package manager first. You can choose between ${PACKAGE_MANAGERS.join(', ')}. It's recommended to use \"pnpm\" if the user has no preference\n- Choose an infrastructure as code (IaC) provider next. You can choose between ${IAC_PROVIDERS.join(', ')}. It's recommended to use CDK if the user has no preference\n- Next, you must create an Nx workspace. Use the \\`create-workspace-command\\` tool for more details, and provide it with your chosen package manager\n- After this, you can start scaffolding the main components of your application using generators. Use the \\`list-generators\\` tool to discover available generators, and the \\`generator-guide\\` tool for more detailed information about a specific generator\n\n## Nx Primer\n\n- Prefix nx commands with the appropriate prefix for your package manager, for example:\n${PACKAGE_MANAGERS.map((pm) => buildNxCommand('<options>', pm)).join(' - \\n')}\n- Each project in your workspace has a file named \\`project.json\\` which contains important project information such as its name, and defines the \"targets\" which can be run for that project, for example building or testing the project\n- Use the command \\`nx reset\\` to reset the Nx daemon when unexpected issues arise\n- After adding dependencies between TypeScript projects, use \\`nx sync\\` to ensure project references are set up correctly\n\n## General Instructions\n\n- Workspaces contain a single \\`package.json\\` file at the root which defines the dependencies for all projects. Therefore when installing dependencies, you must add these to the root workspace using the appropriate command for your package manager:\n - pnpm add -w -D <package>\n - yarn add -D <package>\n - npm install --legacy-peer-deps -D <package>\n - bun install -D <package>\n - (Omit -D for production dependencies)\n- When specifying project names as arguments to generators, prefer the _fully qualified_ project name, for example \\`@workspace-name/project-name\\`. Check the \\`project.json\\` file for the specific package to find its fully qualified name\n- When no generator exists for a specific framework required, use the base \\`ts#project\\` and \\`py#project\\` generators and build on top.\n- Leave the \\`--infra\\` option at its default value unless the user has explicitly instructed otherwise. Generators choose a sensible default type of infrastructure to deploy the project with, so only override \\`--infra\\` when the user has specified a particular requirement.\n\n## Useful Commands\n\n- Fix lint issues with \\`nx run-many --target lint --configuration=fix --all --output-style=stream\\`\n- Build all projects with \\`nx run-many --target build --all --output-style=stream\\`\n- Prefer importing the CDK constructs vended by generators in \\`packages/common/constructs\\` over writing your own\n\n## Best Practices\n\n- After running a generator, use the \\`nx show projects\\` command to check which projects have been added (if any)\n- Carefully examine the files that have been generated and always refer back to the generator guide when working in a generated project\n- Generate all projects into the \\`packages/\\` directory\n- After making changes to your projects, fix linting issues, then run a full build\n- When it's time to start testing a project, suggest to the user that infrastructure is deployed to AWS. For websites, if a runtime-config.json is needed, use the load:runtime-config target after a deployment to point a local website at a sandbox stack.\n\n## Batching Generators\n\nWhen scaffolding several projects in one go, chain generators to avoid a slow dependency install after every generator:\n\n- **Chain generators** with \\`&&\\` in a single command. Pass \\`--prefer-install-dependencies=false\\` on each generator except the last so dependencies install once at the end, for example:\n\n${PACKAGE_MANAGERS.map(\n (pm) => ` \\`\\`\\`bash\n ${buildNxCommand('g @aws/nx-plugin:ts#trpc-api --no-interactive --name=my-app-api --auth=IAM --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:ts#react-website --no-interactive --name=my-app-website --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:connection --no-interactive --sourceProject=@my-app/my-app-website --targetProject=@my-app/my-app-api --prefer-install-dependencies=false', pm)} && \\\\\n ${buildNxCommand('g @aws/nx-plugin:ts#infra --no-interactive --name=infra', pm)} && \\\\\n ${buildNxCommand('sync', pm)}\n \\`\\`\\``,\n).join('\\n')}\n\n- **\\`--prefer-install-dependencies=false\\`** asks a generator to defer its dependency install so the batch installs once at the end (the final generator above omits the flag and installs everything).\n- **\\`nx sync\\`** is required before building — generators modify TypeScript project references.\n\n## Detailed Guides\n\nPlease refer to the below documentation for important details regarding workspaces and working with TypeScript or Python projects.\n\n${await fetchGuidePages(['workspace', 'typescript-project', 'python-project'], generators)}\n\n `,\n },\n ],\n }),\n );\n};\n"],"names":["IAC_PROVIDERS","buildNxCommand","fetchGuidePages","PACKAGE_MANAGERS","TOOL_SELECTION_GUIDE","addGeneralGuidanceTool","server","generators","registerTool","title","description","content","type","text","join","map","pm"],"mappings":"AAAA;;;CAGC,GAGD,SAASA,aAAa,QAAQ,+BAA4B;AAC1D,SAASC,cAAc,EAAEC,eAAe,QAAQ,uBAAoB;AACpE,SAASC,gBAAgB,QAAQ,eAAY;AAE7C,OAAO,MAAMC,uBAAuB,CAAC;;;;;;+FAM0D,CAAC,CAAC;AAEjG;;CAEC,GACD,OAAO,MAAMC,yBAAyB,CACpCC,QACAC;IAEAD,OAAOE,YAAY,CACjB,oBACA;QACEC,OAAO;QACPC,aACE;IACJ,GACA,UAAa,CAAA;YACXC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC;;AAEjB,EAAET,qBAAqB;;;;yDAIkC,EAAED,iBAAiBW,IAAI,CAAC,MAAM;+EACR,EAAEd,cAAcc,IAAI,CAAC,MAAM;;;;;;;AAO1G,EAAEX,iBAAiBY,GAAG,CAAC,CAACC,KAAOf,eAAe,aAAae,KAAKF,IAAI,CAAC,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqC9E,EAAEX,iBAAiBY,GAAG,CACpB,CAACC,KAAO,CAAC;EACT,EAAEf,eAAe,kHAAkHe,IAAI;IACrI,EAAEf,eAAe,gHAAgHe,IAAI;IACrI,EAAEf,eAAe,8JAA8Je,IAAI;IACnL,EAAEf,eAAe,2DAA2De,IAAI;IAChF,EAAEf,eAAe,QAAQe,IAAI;QACzB,CAAC,EACPF,IAAI,CAAC,MAAM;;;;;;;;;AASb,EAAE,MAAMZ,gBAAgB;wBAAC;wBAAa;wBAAsB;qBAAiB,EAAEK,YAAY;;IAEvF,CAAC;gBACG;aACD;QACH,CAAA;AAEJ,EAAE"}
|
|
@@ -90,6 +90,8 @@ Nx Console is an editor extension that enriches your developer experience. It le
|
|
|
90
90
|
The following list of generators are what is currently available in the \`@aws/nx-plugin\`:
|
|
91
91
|
|
|
92
92
|
|
|
93
|
+
- **init**: Configure an existing Nx workspace to use the @aws/nx-plugin
|
|
94
|
+
|
|
93
95
|
- **agentcore-gateway**: Generate an AgentCore Gateway project
|
|
94
96
|
|
|
95
97
|
- **connection**: Integrates a source project with a target project
|
|
@@ -340,6 +342,7 @@ exports[`preset generator > should run successfully > package.json 1`] = `
|
|
|
340
342
|
"@nx/js": "23.0.2",
|
|
341
343
|
"@nx/workspace": "23.0.2",
|
|
342
344
|
"@swc/helpers": "~0.5.18",
|
|
345
|
+
"nx": "23.0.2",
|
|
343
346
|
"typescript": "6.0.3"
|
|
344
347
|
},
|
|
345
348
|
"type": "module",
|
package/src/preset/generator.js
CHANGED
|
@@ -1,61 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
*/ import { addDependenciesToPackageJson,
|
|
5
|
-
import { initGenerator } from "@nx/js";
|
|
4
|
+
*/ import { addDependenciesToPackageJson, joinPathFragments, OverwriteStrategy, updateJson } from "@nx/devkit";
|
|
6
5
|
import { execSync } from "child_process";
|
|
7
6
|
import enquirer from "enquirer";
|
|
8
7
|
import { readFileSync } from "fs";
|
|
9
|
-
import yaml from "js-yaml";
|
|
10
|
-
import { readModulePackageJson } from "nx/src/utils/package-json";
|
|
11
|
-
import GeneratorsJson from "../../generators.json" with {
|
|
12
|
-
type: 'json'
|
|
13
|
-
};
|
|
14
|
-
import { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from "../ts/sync/generator.js";
|
|
15
8
|
import { ensureAwsNxPluginConfig, updateAwsNxPluginConfig } from "../utils/config/utils.js";
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
9
|
+
import { formatFilesInSubtree } from "../utils/format.js";
|
|
10
|
+
import { applyWorkspaceInit } from "../utils/init.js";
|
|
18
11
|
import { installDependencies } from "../utils/install.js";
|
|
19
|
-
import { configureMcpServers } from "../utils/mcp.js";
|
|
20
|
-
import { getNpmScope } from "../utils/npm-scope.js";
|
|
21
12
|
import { getGeneratorInfo } from "../utils/nx.js";
|
|
22
|
-
import { getPackageManagerDisplayCommands } from "../utils/pkg-manager.js";
|
|
23
13
|
import { withVersions } from "../utils/versions.js";
|
|
24
|
-
const WORKSPACES = [
|
|
25
|
-
'packages/*'
|
|
26
|
-
];
|
|
27
|
-
const NX_TYPESCRIPT_SYNC_GENERATOR = '@nx/js:typescript-sync';
|
|
28
|
-
// Built dependencies whose install scripts the generated workspace trusts.
|
|
29
|
-
// `onlyBuiltDependencies` is the pnpm 10 key (silently ignored by pnpm 11);
|
|
30
|
-
// pnpm 11 reads `allowBuilds` instead. Any dep NOT in this allowlist will
|
|
31
|
-
// have its install scripts skipped with a warning — matching pnpm 10's
|
|
32
|
-
// default behaviour. The user can opt-in later via `pnpm approve-builds`.
|
|
33
|
-
const PNPM_BUILT_DEPENDENCIES = [
|
|
34
|
-
'@swc/core',
|
|
35
|
-
'esbuild',
|
|
36
|
-
'nx',
|
|
37
|
-
'sharp'
|
|
38
|
-
];
|
|
39
14
|
export const PRESET_GENERATOR_INFO = getGeneratorInfo(import.meta.filename);
|
|
40
|
-
const setUpWorkspaces = (tree)=>{
|
|
41
|
-
if (detectPackageManager() === 'pnpm') {
|
|
42
|
-
tree.write('pnpm-workspace.yaml', yaml.dump({
|
|
43
|
-
packages: WORKSPACES,
|
|
44
|
-
allowBuilds: Object.fromEntries(PNPM_BUILT_DEPENDENCIES.map((dep)=>[
|
|
45
|
-
dep,
|
|
46
|
-
true
|
|
47
|
-
])),
|
|
48
|
-
onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES
|
|
49
|
-
}, {
|
|
50
|
-
quotingType: "'"
|
|
51
|
-
}));
|
|
52
|
-
} else {
|
|
53
|
-
updateJson(tree, 'package.json', (json)=>{
|
|
54
|
-
json.workspaces = WORKSPACES;
|
|
55
|
-
return json;
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
15
|
/**
|
|
60
16
|
* Determines if the current user is an Amazon employee based on their git configuration.
|
|
61
17
|
*
|
|
@@ -120,8 +76,6 @@ const setUpGitSecrets = (tree)=>{
|
|
|
120
76
|
]));
|
|
121
77
|
};
|
|
122
78
|
export const presetGenerator = async (tree, { iac, gitSecrets, mcp, containers, module, preferInstallDependencies })=>{
|
|
123
|
-
const resolvedContainers = !containers || containers === 'infer' ? inferContainers() : containers;
|
|
124
|
-
const esm = (module ?? 'esm') === 'esm';
|
|
125
79
|
if (isAmazonian() && !process.env.VITEST && !process.env.CI && process.env.NX_DRY_RUN !== 'true' && process.env.NX_INTERACTIVE !== 'false') {
|
|
126
80
|
const { engagementId } = await enquirer.prompt([
|
|
127
81
|
{
|
|
@@ -140,93 +94,29 @@ export const presetGenerator = async (tree, { iac, gitSecrets, mcp, containers,
|
|
|
140
94
|
});
|
|
141
95
|
}
|
|
142
96
|
}
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
provider: iac
|
|
148
|
-
},
|
|
149
|
-
containers: {
|
|
150
|
-
engine: resolvedContainers
|
|
151
|
-
}
|
|
152
|
-
});
|
|
153
|
-
await initGenerator(tree, {
|
|
154
|
-
formatter: 'none',
|
|
155
|
-
addTsPlugin: true
|
|
156
|
-
});
|
|
157
|
-
tree.delete('apps/.gitkeep');
|
|
158
|
-
tree.delete('libs/.gitkeep');
|
|
159
|
-
tree.write('packages/.gitkeep', '');
|
|
160
|
-
setUpWorkspaces(tree);
|
|
161
|
-
const nxJson = readNxJson(tree);
|
|
162
|
-
updateNxJson(tree, {
|
|
163
|
-
...nxJson,
|
|
164
|
-
analytics: false,
|
|
165
|
-
targetDefaults: {
|
|
166
|
-
...nxJson.targetDefaults,
|
|
167
|
-
compile: {
|
|
168
|
-
...nxJson.targetDefaults?.compile,
|
|
169
|
-
syncGenerators: [
|
|
170
|
-
...(nxJson.targetDefaults?.compile?.syncGenerators ?? []).filter((g)=>![
|
|
171
|
-
TS_SYNC_GENERATOR_NAME,
|
|
172
|
-
NX_TYPESCRIPT_SYNC_GENERATOR
|
|
173
|
-
].includes(g)),
|
|
174
|
-
NX_TYPESCRIPT_SYNC_GENERATOR,
|
|
175
|
-
TS_SYNC_GENERATOR_NAME
|
|
176
|
-
]
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
});
|
|
97
|
+
// The preset owns the greenfield workspace's module format: write the root
|
|
98
|
+
// `type` explicitly from the chosen `--module` so later generators can
|
|
99
|
+
// infer it. The `init` generator never touches an existing workspace's
|
|
100
|
+
// `type` field.
|
|
180
101
|
updateJson(tree, 'package.json', (packageJson)=>({
|
|
181
102
|
...packageJson,
|
|
182
|
-
|
|
183
|
-
// format from the root `type`.
|
|
184
|
-
type: esm ? 'module' : 'commonjs',
|
|
185
|
-
scripts: {
|
|
186
|
-
...packageJson.scripts,
|
|
187
|
-
dev: 'nx run-many --target dev',
|
|
188
|
-
build: 'nx run-many --target build',
|
|
189
|
-
lint: 'nx run-many --target lint --configuration=fix',
|
|
190
|
-
test: 'nx run-many --target test --all',
|
|
191
|
-
'build:skip-lint': 'nx run-many --target build --configuration=skip-lint',
|
|
192
|
-
'build:all': 'nx run-many --target build --all',
|
|
193
|
-
'affected:all': 'nx affected --target build'
|
|
194
|
-
}
|
|
103
|
+
type: (module ?? 'esm') === 'esm' ? 'module' : 'commonjs'
|
|
195
104
|
}));
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (!tree.exists('biome.json')) {
|
|
205
|
-
tree.write('biome.json', JSON.stringify(DEFAULT_BIOME_CONFIG, null, 2));
|
|
206
|
-
}
|
|
207
|
-
generateFiles(tree, joinPathFragments(import.meta.dirname, 'files'), '.', {
|
|
208
|
-
projectName: getNpmScope(tree),
|
|
209
|
-
generators: Object.entries(GeneratorsJson.generators).filter(([_, v])=>!v['hidden']).map(([k, v])=>({
|
|
210
|
-
name: k,
|
|
211
|
-
description: v.description
|
|
212
|
-
})),
|
|
213
|
-
...(()=>{
|
|
214
|
-
const cmds = getPackageManagerDisplayCommands();
|
|
215
|
-
return {
|
|
216
|
-
pkgMgrCmd: cmds.exec,
|
|
217
|
-
buildCmd: `${cmds.run} build`,
|
|
218
|
-
lintCmd: `${cmds.run} lint`
|
|
219
|
-
};
|
|
220
|
-
})()
|
|
221
|
-
}, {
|
|
222
|
-
overwriteStrategy: OverwriteStrategy.Overwrite
|
|
105
|
+
// Apply the deterministic workspace configuration shared with the `init`
|
|
106
|
+
// generator. The preset owns the README of a greenfield workspace.
|
|
107
|
+
await applyWorkspaceInit(tree, {
|
|
108
|
+
iac,
|
|
109
|
+
containers,
|
|
110
|
+
mcp,
|
|
111
|
+
readmeOverwriteStrategy: OverwriteStrategy.Overwrite,
|
|
112
|
+
overwriteScripts: true
|
|
223
113
|
});
|
|
114
|
+
tree.delete('apps/.gitkeep');
|
|
115
|
+
tree.delete('libs/.gitkeep');
|
|
116
|
+
tree.write('packages/.gitkeep', '');
|
|
224
117
|
if (gitSecrets !== false) {
|
|
225
118
|
setUpGitSecrets(tree);
|
|
226
119
|
}
|
|
227
|
-
if (mcp !== false) {
|
|
228
|
-
configureMcpServers(tree);
|
|
229
|
-
}
|
|
230
120
|
await formatFilesInSubtree(tree);
|
|
231
121
|
return ()=>installDependencies(tree, preferInstallDependencies, {
|
|
232
122
|
languages: [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/preset/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n addDependenciesToPackageJson,\n detectPackageManager,\n type GeneratorCallback,\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 { execSync } from 'child_process';\nimport enquirer from 'enquirer';\nimport { readFileSync } from 'fs';\nimport yaml from 'js-yaml';\nimport { readModulePackageJson } from 'nx/src/utils/package-json';\nimport GeneratorsJson from '../../generators.json' with { type: 'json' };\nimport { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from '../ts/sync/generator';\nimport {\n ensureAwsNxPluginConfig,\n updateAwsNxPluginConfig,\n} from '../utils/config/utils';\nimport { inferContainers } from '../utils/containers';\nimport { DEFAULT_BIOME_CONFIG, formatFilesInSubtree } from '../utils/format';\nimport { installDependencies } from '../utils/install';\nimport { configureMcpServers } from '../utils/mcp';\nimport { addGeneratorMetricsIfApplicable } from '../utils/metrics';\nimport { getNpmScope } from '../utils/npm-scope';\nimport { getGeneratorInfo, type NxGeneratorInfo } from '../utils/nx';\nimport { getPackageManagerDisplayCommands } from '../utils/pkg-manager';\nimport { withVersions } from '../utils/versions';\nimport type { PresetGeneratorSchema } from './schema';\n\nconst WORKSPACES = ['packages/*'];\nconst NX_TYPESCRIPT_SYNC_GENERATOR = '@nx/js:typescript-sync';\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`.\nconst PNPM_BUILT_DEPENDENCIES = ['@swc/core', 'esbuild', 'nx', 'sharp'];\n\nexport const PRESET_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nconst setUpWorkspaces = (tree: Tree) => {\n if (detectPackageManager() === 'pnpm') {\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump(\n {\n packages: WORKSPACES,\n allowBuilds: Object.fromEntries(\n PNPM_BUILT_DEPENDENCIES.map((dep) => [dep, true]),\n ),\n onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES,\n },\n { quotingType: \"'\" },\n ),\n );\n } else {\n updateJson(tree, 'package.json', (json) => {\n json.workspaces = WORKSPACES;\n return json;\n });\n }\n};\n\n/**\n * Determines if the current user is an Amazon employee based on their git configuration.\n *\n * This function checks the git user email configuration to identify Amazon employees\n * by looking for email addresses with Amazon domains (e.g., @amazon.com, @amazon.co.uk).\n *\n * @returns {boolean} True if the user's git email has an Amazon domain, false otherwise\n *\n * @example\n * // Returns true for Amazon employee emails\n * // git config user.email = \"john.doe@amazon.com\"\n * isAmazonian(); // true\n *\n * @example\n * // Returns false for non-Amazon emails\n * // git config user.email = \"user@example.com\"\n * isAmazonian(); // false\n *\n * @example\n * // Returns false when git config is not available or throws an error\n * isAmazonian(); // false\n */\nexport function isAmazonian(): boolean {\n try {\n // Execute git command to retrieve the user's configured email address\n const gitEmail = execSync('git config user.email', {\n encoding: 'utf8',\n }).trim();\n\n // Return false if no email is configured\n if (!gitEmail) {\n return false;\n }\n\n // Split email address to extract domain part\n const emailParts = gitEmail.split('@');\n if (emailParts.length < 2) {\n return false;\n }\n\n // Extract domain and normalize to lowercase for comparison\n const domain = emailParts[1].toLowerCase();\n\n // Check if domain starts with 'amazon.' (covers amazon.com, amazon.co.uk, etc.)\n return domain.startsWith('amazon.');\n } catch (error) {\n // Return false if git command fails or any other error occurs\n // This handles cases where git is not installed or configured\n return false;\n }\n}\n\nconst setUpGitSecrets = (tree: Tree) => {\n const gitSecretsDir = joinPathFragments(\n import.meta.dirname,\n 'git-secrets-files',\n 'git-secrets-dir',\n );\n const huskyDir = joinPathFragments(\n import.meta.dirname,\n 'git-secrets-files',\n 'husky-dir',\n );\n\n tree.write(\n '.git-secrets/git-secrets',\n readFileSync(joinPathFragments(gitSecretsDir, 'git-secrets'), 'utf-8'),\n );\n tree.write(\n '.husky/pre-commit',\n readFileSync(joinPathFragments(huskyDir, 'pre-commit'), 'utf-8'),\n );\n tree.write('.gitallowed', '\\\\.git-secrets/git-secrets:\\n');\n\n updateJson(tree, 'package.json', (json) => ({\n ...json,\n scripts: {\n ...json.scripts,\n prepare: 'husky',\n },\n }));\n\n addDependenciesToPackageJson(tree, {}, withVersions(['husky']));\n};\n\nexport const presetGenerator = async (\n tree: Tree,\n {\n iac,\n gitSecrets,\n mcp,\n containers,\n module,\n preferInstallDependencies,\n }: PresetGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const resolvedContainers =\n !containers || containers === 'infer' ? inferContainers() : containers;\n const esm = (module ?? 'esm') === 'esm';\n if (\n isAmazonian() &&\n !process.env.VITEST &&\n !process.env.CI &&\n process.env.NX_DRY_RUN !== 'true' &&\n process.env.NX_INTERACTIVE !== 'false'\n ) {\n const { engagementId } = await enquirer.prompt<{ engagementId?: string }>([\n {\n name: 'engagementId',\n message: 'Please enter your engagementId (if known)',\n type: 'input',\n initial: 'None',\n },\n ]);\n\n if (engagementId != 'None') {\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, { tags: [engagementId] });\n }\n }\n\n // Write IaC provider and container engine to plugin config\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, {\n iac: { provider: iac },\n containers: { engine: resolvedContainers },\n });\n\n await initGenerator(tree, {\n formatter: 'none',\n addTsPlugin: true,\n });\n\n tree.delete('apps/.gitkeep');\n tree.delete('libs/.gitkeep');\n tree.write('packages/.gitkeep', '');\n\n setUpWorkspaces(tree);\n\n const nxJson = readNxJson(tree);\n updateNxJson(tree, {\n ...nxJson,\n analytics: false,\n targetDefaults: {\n ...nxJson.targetDefaults,\n compile: {\n ...nxJson.targetDefaults?.compile,\n syncGenerators: [\n ...(nxJson.targetDefaults?.compile?.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 updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n // Written explicitly so later generators can infer the workspace's module\n // format from the root `type`.\n type: esm ? 'module' : 'commonjs',\n scripts: {\n ...packageJson.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 '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 }));\n\n addDependenciesToPackageJson(\n tree,\n {},\n {\n '@nx/workspace': readModulePackageJson('@nx/js').packageJson.version,\n ...withVersions(['typescript', '@biomejs/biome']),\n },\n );\n\n // Write biome.json for formatting and linting\n if (!tree.exists('biome.json')) {\n tree.write('biome.json', JSON.stringify(DEFAULT_BIOME_CONFIG, null, 2));\n }\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, '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: OverwriteStrategy.Overwrite,\n },\n );\n\n if (gitSecrets !== false) {\n setUpGitSecrets(tree);\n }\n\n if (mcp !== false) {\n configureMcpServers(tree);\n }\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default presetGenerator;\n"],"names":["addDependenciesToPackageJson","detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readNxJson","updateJson","updateNxJson","initGenerator","execSync","enquirer","readFileSync","yaml","readModulePackageJson","GeneratorsJson","type","SYNC_GENERATOR_NAME","TS_SYNC_GENERATOR_NAME","ensureAwsNxPluginConfig","updateAwsNxPluginConfig","inferContainers","DEFAULT_BIOME_CONFIG","formatFilesInSubtree","installDependencies","configureMcpServers","getNpmScope","getGeneratorInfo","getPackageManagerDisplayCommands","withVersions","WORKSPACES","NX_TYPESCRIPT_SYNC_GENERATOR","PNPM_BUILT_DEPENDENCIES","PRESET_GENERATOR_INFO","filename","setUpWorkspaces","tree","write","dump","packages","allowBuilds","Object","fromEntries","map","dep","onlyBuiltDependencies","quotingType","json","workspaces","isAmazonian","gitEmail","encoding","trim","emailParts","split","length","domain","toLowerCase","startsWith","error","setUpGitSecrets","gitSecretsDir","dirname","huskyDir","scripts","prepare","presetGenerator","iac","gitSecrets","mcp","containers","module","preferInstallDependencies","resolvedContainers","esm","process","env","VITEST","CI","NX_DRY_RUN","NX_INTERACTIVE","engagementId","prompt","name","message","initial","tags","provider","engine","formatter","addTsPlugin","delete","nxJson","analytics","targetDefaults","compile","syncGenerators","filter","g","includes","packageJson","dev","build","lint","test","version","exists","JSON","stringify","projectName","generators","entries","_","v","k","description","cmds","pkgMgrCmd","exec","buildCmd","run","lintCmd","overwriteStrategy","Overwrite","languages"],"mappings":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AAmBrH,kBAAkBsH,SAAS;IAChD;IAGF,IAAIvD,eAAe,OAAO;QACxBR,gBAAgBxB;IAClB;IAEA,IAAIiC,QAAQ,OAAO;QACjB5C,oBAAoBW;IACtB;IAEA,MAAMb,qBAAqBa;IAC3B,OAAO,IACLZ,oBAAoBY,MAAMoC,2BAA2B;YACnDoD,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AAEF,eAAe1D,gBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/preset/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n addDependenciesToPackageJson,\n type GeneratorCallback,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { execSync } from 'child_process';\nimport enquirer from 'enquirer';\nimport { readFileSync } from 'fs';\nimport {\n ensureAwsNxPluginConfig,\n updateAwsNxPluginConfig,\n} from '../utils/config/utils';\nimport { formatFilesInSubtree } from '../utils/format';\nimport { applyWorkspaceInit } from '../utils/init';\nimport { installDependencies } from '../utils/install';\nimport { getGeneratorInfo, type NxGeneratorInfo } from '../utils/nx';\nimport { withVersions } from '../utils/versions';\nimport type { PresetGeneratorSchema } from './schema';\n\nexport const PRESET_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\n/**\n * Determines if the current user is an Amazon employee based on their git configuration.\n *\n * This function checks the git user email configuration to identify Amazon employees\n * by looking for email addresses with Amazon domains (e.g., @amazon.com, @amazon.co.uk).\n *\n * @returns {boolean} True if the user's git email has an Amazon domain, false otherwise\n *\n * @example\n * // Returns true for Amazon employee emails\n * // git config user.email = \"john.doe@amazon.com\"\n * isAmazonian(); // true\n *\n * @example\n * // Returns false for non-Amazon emails\n * // git config user.email = \"user@example.com\"\n * isAmazonian(); // false\n *\n * @example\n * // Returns false when git config is not available or throws an error\n * isAmazonian(); // false\n */\nexport function isAmazonian(): boolean {\n try {\n // Execute git command to retrieve the user's configured email address\n const gitEmail = execSync('git config user.email', {\n encoding: 'utf8',\n }).trim();\n\n // Return false if no email is configured\n if (!gitEmail) {\n return false;\n }\n\n // Split email address to extract domain part\n const emailParts = gitEmail.split('@');\n if (emailParts.length < 2) {\n return false;\n }\n\n // Extract domain and normalize to lowercase for comparison\n const domain = emailParts[1].toLowerCase();\n\n // Check if domain starts with 'amazon.' (covers amazon.com, amazon.co.uk, etc.)\n return domain.startsWith('amazon.');\n } catch (error) {\n // Return false if git command fails or any other error occurs\n // This handles cases where git is not installed or configured\n return false;\n }\n}\n\nconst setUpGitSecrets = (tree: Tree) => {\n const gitSecretsDir = joinPathFragments(\n import.meta.dirname,\n 'git-secrets-files',\n 'git-secrets-dir',\n );\n const huskyDir = joinPathFragments(\n import.meta.dirname,\n 'git-secrets-files',\n 'husky-dir',\n );\n\n tree.write(\n '.git-secrets/git-secrets',\n readFileSync(joinPathFragments(gitSecretsDir, 'git-secrets'), 'utf-8'),\n );\n tree.write(\n '.husky/pre-commit',\n readFileSync(joinPathFragments(huskyDir, 'pre-commit'), 'utf-8'),\n );\n tree.write('.gitallowed', '\\\\.git-secrets/git-secrets:\\n');\n\n updateJson(tree, 'package.json', (json) => ({\n ...json,\n scripts: {\n ...json.scripts,\n prepare: 'husky',\n },\n }));\n\n addDependenciesToPackageJson(tree, {}, withVersions(['husky']));\n};\n\nexport const presetGenerator = async (\n tree: Tree,\n {\n iac,\n gitSecrets,\n mcp,\n containers,\n module,\n preferInstallDependencies,\n }: PresetGeneratorSchema,\n): Promise<GeneratorCallback> => {\n if (\n isAmazonian() &&\n !process.env.VITEST &&\n !process.env.CI &&\n process.env.NX_DRY_RUN !== 'true' &&\n process.env.NX_INTERACTIVE !== 'false'\n ) {\n const { engagementId } = await enquirer.prompt<{ engagementId?: string }>([\n {\n name: 'engagementId',\n message: 'Please enter your engagementId (if known)',\n type: 'input',\n initial: 'None',\n },\n ]);\n\n if (engagementId != 'None') {\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, { tags: [engagementId] });\n }\n }\n\n // The preset owns the greenfield workspace's module format: write the root\n // `type` explicitly from the chosen `--module` so later generators can\n // infer it. The `init` generator never touches an existing workspace's\n // `type` field.\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n type: (module ?? 'esm') === 'esm' ? 'module' : 'commonjs',\n }));\n\n // Apply the deterministic workspace configuration shared with the `init`\n // generator. The preset owns the README of a greenfield workspace.\n await applyWorkspaceInit(tree, {\n iac,\n containers,\n mcp,\n readmeOverwriteStrategy: OverwriteStrategy.Overwrite,\n overwriteScripts: true,\n });\n\n tree.delete('apps/.gitkeep');\n tree.delete('libs/.gitkeep');\n tree.write('packages/.gitkeep', '');\n\n if (gitSecrets !== false) {\n setUpGitSecrets(tree);\n }\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default presetGenerator;\n"],"names":["addDependenciesToPackageJson","joinPathFragments","OverwriteStrategy","updateJson","execSync","enquirer","readFileSync","ensureAwsNxPluginConfig","updateAwsNxPluginConfig","formatFilesInSubtree","applyWorkspaceInit","installDependencies","getGeneratorInfo","withVersions","PRESET_GENERATOR_INFO","filename","isAmazonian","gitEmail","encoding","trim","emailParts","split","length","domain","toLowerCase","startsWith","error","setUpGitSecrets","tree","gitSecretsDir","dirname","huskyDir","write","json","scripts","prepare","presetGenerator","iac","gitSecrets","mcp","containers","module","preferInstallDependencies","process","env","VITEST","CI","NX_DRY_RUN","NX_INTERACTIVE","engagementId","prompt","name","message","type","initial","tags","packageJson","readmeOverwriteStrategy","Overwrite","overwriteScripts","delete","languages"],"mappings":"AAAA;;;CAGC,GACD,SACEA,4BAA4B,EAE5BC,iBAAiB,EACjBC,iBAAiB,EAEjBC,UAAU,QACL,aAAa;AACpB,SAASC,QAAQ,QAAQ,gBAAgB;AACzC,OAAOC,cAAc,WAAW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Aa;QAC3B;AACJ,EAAE;AAEF,eAAezB,gBAAgB"}
|
|
@@ -92,13 +92,6 @@ import { configureVitest } from "./vitest.js";
|
|
|
92
92
|
])
|
|
93
93
|
}));
|
|
94
94
|
}
|
|
95
|
-
// Update the root package.json. ESM projects require `type: module`; for
|
|
96
|
-
// CommonJS we write an explicit `type: commonjs` marker (which Node treats
|
|
97
|
-
// identically to an absent `type`).
|
|
98
|
-
updateJson(tree, 'package.json', (packageJson)=>({
|
|
99
|
-
...packageJson,
|
|
100
|
-
type: esm ? 'module' : 'commonjs'
|
|
101
|
-
}));
|
|
102
95
|
// Remove package.json if it exists
|
|
103
96
|
if (tree.exists(join(options.dir, 'package.json'))) {
|
|
104
97
|
tree.delete(join(options.dir, 'package.json'));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/ts-project-utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, type Tree, updateJson } from '@nx/devkit';\nimport { join, relative } from 'path';\nimport { addLicenseCheckToLintTarget } from '../../license/config';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport { toScopeAlias } from '../../utils/npm-scope';\nimport { configureBiomeLint } from './biome';\nimport type { ConfigureProjectOptions } from './types';\nimport { configureVitest } from './vitest';\n\ninterface TsConfigReference {\n path: string;\n}\n\n/**\n * Merges new TypeScript project references into existing ones, deduplicating by\n * path and preserving the order of existing references so re-running a\n * generator neither duplicates nor reorders references.\n */\nexport const mergeTsReferences = (\n existing: TsConfigReference[] | undefined,\n toAdd: TsConfigReference[],\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const existingPaths = new Set(references.map((ref) => ref.path));\n for (const ref of toAdd) {\n if (!existingPaths.has(ref.path)) {\n references.push(ref);\n existingPaths.add(ref.path);\n }\n }\n return references;\n};\n\n/**\n * Updates typescript projects\n */\nexport const configureTsProject = async (\n tree: Tree,\n options: ConfigureProjectOptions,\n) => {\n // When the caller doesn't specify a module format, infer it from the\n // workspace root package.json (defaulting to ESM for a fresh workspace).\n const esm = options.esm ?? isEsmWorkspace(tree);\n\n // Remove a conflicting `module: commonjs` from the project tsconfig.json\n // (CommonJS is configured on tsconfig.lib.json below when needed).\n updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n module:\n tsConfig.compilerOptions?.module === 'commonjs'\n ? undefined\n : tsConfig.compilerOptions?.module,\n },\n }));\n const outDirToRootRelativePath = relative(\n join(tree.root, options.dir),\n tree.root,\n );\n const distDir = join(outDirToRootRelativePath, 'dist', options.dir, 'tsc');\n // Remove baseUrl and rootDir from the tsconfig.lib.json\n if (tree.exists(join(options.dir, 'tsconfig.lib.json'))) {\n updateJson(tree, join(options.dir, 'tsconfig.lib.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n baseUrl: undefined,\n rootDir: '.',\n outDir: distDir,\n tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),\n // @nx/js configures the lib for ESM (module `nodenext`). CommonJS\n // projects use `node16`, which honours the workspace's\n // `type: commonjs`, emits CommonJS and resolves extensionless relative\n // imports. (Plain `commonjs`/`node` is deprecated in TypeScript 6.)\n ...(esm ? {} : { module: 'node16', moduleResolution: 'node16' }),\n },\n }));\n }\n // Update root project tsconfig\n updateJson(tree, 'tsconfig.base.json', (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n // baseUrl is deprecated in TypeScript 6 — use ./ prefix in paths instead\n baseUrl: undefined,\n rootDir: '.',\n paths: {\n // Remove any path aliases for this project with the npm scope prefix (eg remove @foo/bar)\n ...Object.fromEntries(\n Object.entries(tsConfig.compilerOptions?.paths ?? {}).filter(\n ([k]) => k !== options.fullyQualifiedName,\n ),\n ),\n // Add aliases which begin with colon (eg :foo/bar) to avoid sniping attacks\n [toScopeAlias(options.fullyQualifiedName)]: [\n `./${joinPathFragments(options.dir, 'src', 'index.ts')}`,\n ],\n },\n },\n }));\n if (tree.exists('tsconfig.json')) {\n updateJson(tree, 'tsconfig.json', (tsConfig) => ({\n ...tsConfig,\n // Add project references, deduplicating and preserving existing order\n references: mergeTsReferences(tsConfig.references, [\n { path: `./${options.dir}` },\n ]),\n }));\n }\n //
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/ts-project-utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, type Tree, updateJson } from '@nx/devkit';\nimport { join, relative } from 'path';\nimport { addLicenseCheckToLintTarget } from '../../license/config';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport { toScopeAlias } from '../../utils/npm-scope';\nimport { configureBiomeLint } from './biome';\nimport type { ConfigureProjectOptions } from './types';\nimport { configureVitest } from './vitest';\n\ninterface TsConfigReference {\n path: string;\n}\n\n/**\n * Merges new TypeScript project references into existing ones, deduplicating by\n * path and preserving the order of existing references so re-running a\n * generator neither duplicates nor reorders references.\n */\nexport const mergeTsReferences = (\n existing: TsConfigReference[] | undefined,\n toAdd: TsConfigReference[],\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const existingPaths = new Set(references.map((ref) => ref.path));\n for (const ref of toAdd) {\n if (!existingPaths.has(ref.path)) {\n references.push(ref);\n existingPaths.add(ref.path);\n }\n }\n return references;\n};\n\n/**\n * Updates typescript projects\n */\nexport const configureTsProject = async (\n tree: Tree,\n options: ConfigureProjectOptions,\n) => {\n // When the caller doesn't specify a module format, infer it from the\n // workspace root package.json (defaulting to ESM for a fresh workspace).\n const esm = options.esm ?? isEsmWorkspace(tree);\n\n // Remove a conflicting `module: commonjs` from the project tsconfig.json\n // (CommonJS is configured on tsconfig.lib.json below when needed).\n updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n module:\n tsConfig.compilerOptions?.module === 'commonjs'\n ? undefined\n : tsConfig.compilerOptions?.module,\n },\n }));\n const outDirToRootRelativePath = relative(\n join(tree.root, options.dir),\n tree.root,\n );\n const distDir = join(outDirToRootRelativePath, 'dist', options.dir, 'tsc');\n // Remove baseUrl and rootDir from the tsconfig.lib.json\n if (tree.exists(join(options.dir, 'tsconfig.lib.json'))) {\n updateJson(tree, join(options.dir, 'tsconfig.lib.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n baseUrl: undefined,\n rootDir: '.',\n outDir: distDir,\n tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),\n // @nx/js configures the lib for ESM (module `nodenext`). CommonJS\n // projects use `node16`, which honours the workspace's\n // `type: commonjs`, emits CommonJS and resolves extensionless relative\n // imports. (Plain `commonjs`/`node` is deprecated in TypeScript 6.)\n ...(esm ? {} : { module: 'node16', moduleResolution: 'node16' }),\n },\n }));\n }\n // Update root project tsconfig\n updateJson(tree, 'tsconfig.base.json', (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n // baseUrl is deprecated in TypeScript 6 — use ./ prefix in paths instead\n baseUrl: undefined,\n rootDir: '.',\n paths: {\n // Remove any path aliases for this project with the npm scope prefix (eg remove @foo/bar)\n ...Object.fromEntries(\n Object.entries(tsConfig.compilerOptions?.paths ?? {}).filter(\n ([k]) => k !== options.fullyQualifiedName,\n ),\n ),\n // Add aliases which begin with colon (eg :foo/bar) to avoid sniping attacks\n [toScopeAlias(options.fullyQualifiedName)]: [\n `./${joinPathFragments(options.dir, 'src', 'index.ts')}`,\n ],\n },\n },\n }));\n if (tree.exists('tsconfig.json')) {\n updateJson(tree, 'tsconfig.json', (tsConfig) => ({\n ...tsConfig,\n // Add project references, deduplicating and preserving existing order\n references: mergeTsReferences(tsConfig.references, [\n { path: `./${options.dir}` },\n ]),\n }));\n }\n // Remove package.json if it exists\n if (tree.exists(join(options.dir, 'package.json'))) {\n tree.delete(join(options.dir, 'package.json'));\n }\n\n await configureBiomeLint(tree, options);\n await configureVitest(tree, options);\n\n // If license checking is configured, make this project's lint target depend\n // on the root license-check target. No-op if there's no license-check target\n // (i.e. the license generator hasn't run); the license generator wires up\n // existing projects itself, so this works regardless of generator order.\n addLicenseCheckToLintTarget(tree, options.fullyQualifiedName);\n};\n"],"names":["joinPathFragments","updateJson","join","relative","addLicenseCheckToLintTarget","isEsmWorkspace","toScopeAlias","configureBiomeLint","configureVitest","mergeTsReferences","existing","toAdd","references","existingPaths","Set","map","ref","path","has","push","add","configureTsProject","tree","options","esm","dir","tsConfig","compilerOptions","module","undefined","outDirToRootRelativePath","root","distDir","exists","baseUrl","rootDir","outDir","tsBuildInfoFile","moduleResolution","paths","Object","fromEntries","entries","filter","k","fullyQualifiedName","delete"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EAAaC,UAAU,QAAQ,aAAa;AACtE,SAASC,IAAI,EAAEC,QAAQ,QAAQ,OAAO;AACtC,SAASC,2BAA2B,QAAQ,0BAAuB;AACnE,SAASC,cAAc,QAAQ,+BAA4B;AAC3D,SAASC,YAAY,QAAQ,2BAAwB;AACrD,SAASC,kBAAkB,QAAQ,aAAU;AAE7C,SAASC,eAAe,QAAQ,cAAW;AAM3C;;;;CAIC,GACD,OAAO,MAAMC,oBAAoB,CAC/BC,UACAC;IAEA,MAAMC,aAAa;WAAKF,YAAY,EAAE;KAAE;IACxC,MAAMG,gBAAgB,IAAIC,IAAIF,WAAWG,GAAG,CAAC,CAACC,MAAQA,IAAIC,IAAI;IAC9D,KAAK,MAAMD,OAAOL,MAAO;QACvB,IAAI,CAACE,cAAcK,GAAG,CAACF,IAAIC,IAAI,GAAG;YAChCL,WAAWO,IAAI,CAACH;YAChBH,cAAcO,GAAG,CAACJ,IAAIC,IAAI;Q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oBACL,0FAA0F;oBAC1F,GAAGC,OAAOC,WAAW,CACnBD,OAAOE,OAAO,CAAChB,SAASC,eAAe,EAAEY,SAAS,CAAC,GAAGI,MAAM,CAC1D,CAAC,CAACC,EAAE,GAAKA,MAAMrB,QAAQsB,kBAAkB,EAE5C;oBACD,4EAA4E;oBAC5E,CAACvC,aAAaiB,QAAQsB,kBAAkB,EAAE,EAAE;wBAC1C,CAAC,EAAE,EAAE7C,kBAAkBuB,QAAQE,GAAG,EAAE,OAAO,aAAa;qBACzD;gBACH;YACF;QACF,CAAA;IACA,IAAIH,KAAKW,MAAM,CAAC,kBAAkB;QAChChC,WAAWqB,MAAM,iBAAiB,CAACI,WAAc,CAAA;gBAC/C,GAAGA,QAAQ;gBACX,sEAAsE;gBACtEd,YAAYH,kBAAkBiB,SAASd,UAAU,EAAE;oBACjD;wBAAEK,MAAM,CAAC,EAAE,EAAEM,QAAQE,GAAG,EAAE;oBAAC;iBAC5B;YACH,CAAA;IACF;IACA,mCAAmC;IACnC,IAAIH,KAAKW,MAAM,CAAC/B,KAAKqB,QAAQE,GAAG,EAAE,kBAAkB;QAClDH,KAAKwB,MAAM,CAAC5C,KAAKqB,QAAQE,GAAG,EAAE;IAChC;IAEA,MAAMlB,mBAAmBe,MAAMC;IAC/B,MAAMf,gBAAgBc,MAAMC;IAE5B,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,yEAAyE;IACzEnB,4BAA4BkB,MAAMC,QAAQsB,kBAAkB;AAC9D,EAAE"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The `tsconfig.base.json` compiler options the plugin's TypeScript projects
|
|
7
|
+
* rely on (project references, ESM, emit-less typecheck). Mirrors what
|
|
8
|
+
* `@nx/js` `initGenerator` produces for a fresh TS-solution workspace.
|
|
9
|
+
*
|
|
10
|
+
* Kept dependency-free so the docs site can import it directly and render the
|
|
11
|
+
* options without them drifting from what the generator writes.
|
|
12
|
+
*/
|
|
13
|
+
export declare const BASE_TSCONFIG_COMPILER_OPTIONS: {
|
|
14
|
+
composite: boolean;
|
|
15
|
+
declarationMap: boolean;
|
|
16
|
+
emitDeclarationOnly: boolean;
|
|
17
|
+
importHelpers: boolean;
|
|
18
|
+
isolatedModules: boolean;
|
|
19
|
+
lib: string[];
|
|
20
|
+
module: string;
|
|
21
|
+
moduleResolution: string;
|
|
22
|
+
noEmitOnError: boolean;
|
|
23
|
+
noFallthroughCasesInSwitch: boolean;
|
|
24
|
+
noImplicitOverride: boolean;
|
|
25
|
+
noImplicitReturns: boolean;
|
|
26
|
+
noUnusedLocals: boolean;
|
|
27
|
+
skipLibCheck: boolean;
|
|
28
|
+
strict: boolean;
|
|
29
|
+
target: string;
|
|
30
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/ /**
|
|
5
|
+
* The `tsconfig.base.json` compiler options the plugin's TypeScript projects
|
|
6
|
+
* rely on (project references, ESM, emit-less typecheck). Mirrors what
|
|
7
|
+
* `@nx/js` `initGenerator` produces for a fresh TS-solution workspace.
|
|
8
|
+
*
|
|
9
|
+
* Kept dependency-free so the docs site can import it directly and render the
|
|
10
|
+
* options without them drifting from what the generator writes.
|
|
11
|
+
*/ export const BASE_TSCONFIG_COMPILER_OPTIONS = {
|
|
12
|
+
composite: true,
|
|
13
|
+
declarationMap: true,
|
|
14
|
+
emitDeclarationOnly: true,
|
|
15
|
+
importHelpers: true,
|
|
16
|
+
isolatedModules: true,
|
|
17
|
+
lib: [
|
|
18
|
+
'es2022'
|
|
19
|
+
],
|
|
20
|
+
module: 'nodenext',
|
|
21
|
+
moduleResolution: 'nodenext',
|
|
22
|
+
noEmitOnError: true,
|
|
23
|
+
noFallthroughCasesInSwitch: true,
|
|
24
|
+
noImplicitOverride: true,
|
|
25
|
+
noImplicitReturns: true,
|
|
26
|
+
noUnusedLocals: true,
|
|
27
|
+
skipLibCheck: true,
|
|
28
|
+
strict: true,
|
|
29
|
+
target: 'es2022'
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=base-tsconfig.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/base-tsconfig.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * The `tsconfig.base.json` compiler options the plugin's TypeScript projects\n * rely on (project references, ESM, emit-less typecheck). Mirrors what\n * `@nx/js` `initGenerator` produces for a fresh TS-solution workspace.\n *\n * Kept dependency-free so the docs site can import it directly and render the\n * options without them drifting from what the generator writes.\n */\nexport const BASE_TSCONFIG_COMPILER_OPTIONS = {\n composite: true,\n declarationMap: true,\n emitDeclarationOnly: true,\n importHelpers: true,\n isolatedModules: true,\n lib: ['es2022'],\n module: 'nodenext',\n moduleResolution: 'nodenext',\n noEmitOnError: true,\n noFallthroughCasesInSwitch: true,\n noImplicitOverride: true,\n noImplicitReturns: true,\n noUnusedLocals: true,\n skipLibCheck: true,\n strict: true,\n target: 'es2022',\n};\n"],"names":["BASE_TSCONFIG_COMPILER_OPTIONS","composite","declarationMap","emitDeclarationOnly","importHelpers","isolatedModules","lib","module","moduleResolution","noEmitOnError","noFallthroughCasesInSwitch","noImplicitOverride","noImplicitReturns","noUnusedLocals","skipLibCheck","strict","target"],"mappings":"AAAA;;;CAGC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMA,iCAAiC;IAC5CC,WAAW;IACXC,gBAAgB;IAChBC,qBAAqB;IACrBC,eAAe;IACfC,iBAAiB;IACjBC,KAAK;QAAC;KAAS;IACfC,QAAQ;IACRC,kBAAkB;IAClBC,eAAe;IACfC,4BAA4B;IAC5BC,oBAAoB;IACpBC,mBAAmB;IACnBC,gBAAgB;IAChBC,cAAc;IACdC,QAAQ;IACRC,QAAQ;AACV,EAAE"}
|
package/src/utils/commands.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* The nx version the plugin is built against. Commands that download nx
|
|
3
|
+
* (e.g. `nx init`) pin to this version so the workspace's nx matches the
|
|
4
|
+
* plugin's `@nx/*` packages — a mismatch deadlocks `nx sync`.
|
|
4
5
|
*/
|
|
6
|
+
export declare const NX_VERSION: "23.0.2";
|
|
5
7
|
/**
|
|
6
8
|
* Display-friendly command prefixes for each package manager.
|
|
7
9
|
*
|
|
@@ -32,6 +34,11 @@ export declare const buildPackageManagerShortCommand: (pm: string, command: stri
|
|
|
32
34
|
* Build an install command for a given package manager
|
|
33
35
|
*/
|
|
34
36
|
export declare const buildInstallCommand: (pm: string, pkg: string, dev: boolean) => string;
|
|
37
|
+
/**
|
|
38
|
+
* Build the command that adds Nx to a non-Nx project, pinned to the nx
|
|
39
|
+
* version the plugin is built against.
|
|
40
|
+
*/
|
|
41
|
+
export declare const buildNxInitCommand: (pm: string) => string;
|
|
35
42
|
/**
|
|
36
43
|
* Build a command to create a new workspace using @aws/create-nx-workspace.
|
|
37
44
|
*
|
package/src/utils/commands.js
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
* @see docs/src/components/package-manager-short-command.astro
|
|
12
|
-
*/ export const PACKAGE_MANAGER_COMMANDS = {
|
|
4
|
+
*/ import { TS_VERSIONS } from "./versions.js";
|
|
5
|
+
/**
|
|
6
|
+
* The nx version the plugin is built against. Commands that download nx
|
|
7
|
+
* (e.g. `nx init`) pin to this version so the workspace's nx matches the
|
|
8
|
+
* plugin's `@nx/*` packages — a mismatch deadlocks `nx sync`.
|
|
9
|
+
*/ export const NX_VERSION = TS_VERSIONS['@nx/devkit'];
|
|
10
|
+
export const PACKAGE_MANAGER_COMMANDS = {
|
|
13
11
|
npm: {
|
|
14
12
|
exec: 'npx',
|
|
15
13
|
run: 'npm run',
|
|
@@ -59,6 +57,18 @@
|
|
|
59
57
|
return `${pm} install ${dev ? '-D ' : ''}${pkg}`;
|
|
60
58
|
}
|
|
61
59
|
};
|
|
60
|
+
/**
|
|
61
|
+
* Build the command that adds Nx to a non-Nx project, pinned to the nx
|
|
62
|
+
* version the plugin is built against.
|
|
63
|
+
*/ export const buildNxInitCommand = (pm)=>{
|
|
64
|
+
const dlxPrefix = {
|
|
65
|
+
npm: 'npx',
|
|
66
|
+
pnpm: 'pnpm dlx',
|
|
67
|
+
yarn: 'yarn dlx',
|
|
68
|
+
bun: 'bunx'
|
|
69
|
+
}[pm] ?? 'npx';
|
|
70
|
+
return `${dlxPrefix} nx@${NX_VERSION} init`;
|
|
71
|
+
};
|
|
62
72
|
/**
|
|
63
73
|
* Build a command to create a new workspace using @aws/create-nx-workspace.
|
|
64
74
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/commands.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * Display-friendly command prefixes for each package manager.\n *\n * - `exec`: prefix for running local binaries (e.g. `npx nx`, `pnpm nx`, `bunx nx`)\n * - `run`: prefix for running package.json scripts (e.g. `npm run build`, `pnpm build`)\n *\n * @see docs/src/components/package-manager-exec-command.astro\n * @see docs/src/components/package-manager-short-command.astro\n */\nexport interface PackageManagerDisplayCommands {\n /** Prefix for running local binaries: npx, pnpm, yarn, bunx */\n exec: string;\n /** Prefix for running package.json scripts: `npm run`, pnpm, yarn, bun */\n run: string;\n /** Prefix for `create` commands: `npm create`, `pnpm create`, etc. */\n create: string;\n}\n\nexport const PACKAGE_MANAGER_COMMANDS: Record<\n string,\n PackageManagerDisplayCommands\n> = {\n npm: { exec: 'npx', run: 'npm run', create: 'npm create' },\n pnpm: { exec: 'pnpm', run: 'pnpm', create: 'pnpm create' },\n yarn: { exec: 'yarn', run: 'yarn', create: 'yarn create' },\n bun: { exec: 'bunx', run: 'bun', create: 'bun create' },\n};\n\n/**\n * Build a package manager exec command (e.g. pnpm cmd, npx cmd, bunx cmd)\n */\nexport const buildPackageManagerExecCommand = (pm: string, command: string) => {\n const prefix = PACKAGE_MANAGER_COMMANDS[pm]?.exec ?? pm;\n return `${prefix} ${command}`;\n};\n\n/**\n * Build a short package manager command (e.g. pnpm build, npm run build)\n */\nexport const buildPackageManagerShortCommand = (\n pm: string,\n command: string,\n) => {\n const prefix = PACKAGE_MANAGER_COMMANDS[pm]?.run ?? pm;\n return `${prefix} ${command}`;\n};\n\n/**\n * Build an install command for a given package manager\n */\nexport const buildInstallCommand = (pm: string, pkg: string, dev: boolean) => {\n switch (pm) {\n case 'pnpm':\n return `pnpm add ${dev ? '-D' : '-'}w ${pkg}`;\n case 'yarn':\n return `yarn add ${dev ? '-D ' : ''}${pkg}`;\n case 'npm':\n return `npm install --legacy-peer-deps ${dev ? '-D ' : ''}${pkg}`;\n case 'bun':\n return `bun install ${dev ? '-D ' : ''}${pkg}`;\n default:\n return `${pm} install ${dev ? '-D ' : ''}${pkg}`;\n }\n};\n\n/**\n * Build a command to create a new workspace using @aws/create-nx-workspace.\n *\n * Uses the `create` shorthand for each package manager:\n * npm create @aws/nx-workspace my-project\n * pnpm create @aws/nx-workspace my-project\n * yarn create @aws/nx-workspace my-project\n * bun create @aws/nx-workspace my-project\n *\n * The package manager is auto-detected by @aws/create-nx-workspace from the\n * invoking command, so --pm is not needed.\n */\nexport const buildCreateNxWorkspaceCommand = (\n pm: string,\n workspace: string,\n iac?: 'cdk' | 'terraform',\n tag?: string,\n module?: 'esm' | 'cjs',\n) => {\n const createPrefix = PACKAGE_MANAGER_COMMANDS[pm]?.create ?? `${pm} create`;\n const pkgName = tag ? `@aws/nx-workspace@${tag}` : '@aws/nx-workspace';\n const parts = [\n createPrefix,\n pkgName,\n // npm requires '--' to stop interpreting subsequent flags as npm config\n ...(pm === 'npm' ? ['--'] : []),\n workspace,\n ...(iac ? [`--iac=${iac}`] : []),\n ...(module ? [`--module=${module}`] : []),\n ];\n return parts.join(' ');\n};\n"],"names":["PACKAGE_MANAGER_COMMANDS","npm","exec","run","create","pnpm","yarn","bun","buildPackageManagerExecCommand","pm","command","prefix","buildPackageManagerShortCommand","buildInstallCommand","pkg","dev","buildCreateNxWorkspaceCommand","workspace","iac","tag","module","createPrefix","pkgName","parts","join"],"mappings":"AAAA;;;CAGC,GACD
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/commands.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { TS_VERSIONS } from './versions';\n\n/**\n * The nx version the plugin is built against. Commands that download nx\n * (e.g. `nx init`) pin to this version so the workspace's nx matches the\n * plugin's `@nx/*` packages — a mismatch deadlocks `nx sync`.\n */\nexport const NX_VERSION = TS_VERSIONS['@nx/devkit'];\n\n/**\n * Display-friendly command prefixes for each package manager.\n *\n * - `exec`: prefix for running local binaries (e.g. `npx nx`, `pnpm nx`, `bunx nx`)\n * - `run`: prefix for running package.json scripts (e.g. `npm run build`, `pnpm build`)\n *\n * @see docs/src/components/package-manager-exec-command.astro\n * @see docs/src/components/package-manager-short-command.astro\n */\nexport interface PackageManagerDisplayCommands {\n /** Prefix for running local binaries: npx, pnpm, yarn, bunx */\n exec: string;\n /** Prefix for running package.json scripts: `npm run`, pnpm, yarn, bun */\n run: string;\n /** Prefix for `create` commands: `npm create`, `pnpm create`, etc. */\n create: string;\n}\n\nexport const PACKAGE_MANAGER_COMMANDS: Record<\n string,\n PackageManagerDisplayCommands\n> = {\n npm: { exec: 'npx', run: 'npm run', create: 'npm create' },\n pnpm: { exec: 'pnpm', run: 'pnpm', create: 'pnpm create' },\n yarn: { exec: 'yarn', run: 'yarn', create: 'yarn create' },\n bun: { exec: 'bunx', run: 'bun', create: 'bun create' },\n};\n\n/**\n * Build a package manager exec command (e.g. pnpm cmd, npx cmd, bunx cmd)\n */\nexport const buildPackageManagerExecCommand = (pm: string, command: string) => {\n const prefix = PACKAGE_MANAGER_COMMANDS[pm]?.exec ?? pm;\n return `${prefix} ${command}`;\n};\n\n/**\n * Build a short package manager command (e.g. pnpm build, npm run build)\n */\nexport const buildPackageManagerShortCommand = (\n pm: string,\n command: string,\n) => {\n const prefix = PACKAGE_MANAGER_COMMANDS[pm]?.run ?? pm;\n return `${prefix} ${command}`;\n};\n\n/**\n * Build an install command for a given package manager\n */\nexport const buildInstallCommand = (pm: string, pkg: string, dev: boolean) => {\n switch (pm) {\n case 'pnpm':\n return `pnpm add ${dev ? '-D' : '-'}w ${pkg}`;\n case 'yarn':\n return `yarn add ${dev ? '-D ' : ''}${pkg}`;\n case 'npm':\n return `npm install --legacy-peer-deps ${dev ? '-D ' : ''}${pkg}`;\n case 'bun':\n return `bun install ${dev ? '-D ' : ''}${pkg}`;\n default:\n return `${pm} install ${dev ? '-D ' : ''}${pkg}`;\n }\n};\n\n/**\n * Build the command that adds Nx to a non-Nx project, pinned to the nx\n * version the plugin is built against.\n */\nexport const buildNxInitCommand = (pm: string) => {\n const dlxPrefix =\n { npm: 'npx', pnpm: 'pnpm dlx', yarn: 'yarn dlx', bun: 'bunx' }[pm] ??\n 'npx';\n return `${dlxPrefix} nx@${NX_VERSION} init`;\n};\n\n/**\n * Build a command to create a new workspace using @aws/create-nx-workspace.\n *\n * Uses the `create` shorthand for each package manager:\n * npm create @aws/nx-workspace my-project\n * pnpm create @aws/nx-workspace my-project\n * yarn create @aws/nx-workspace my-project\n * bun create @aws/nx-workspace my-project\n *\n * The package manager is auto-detected by @aws/create-nx-workspace from the\n * invoking command, so --pm is not needed.\n */\nexport const buildCreateNxWorkspaceCommand = (\n pm: string,\n workspace: string,\n iac?: 'cdk' | 'terraform',\n tag?: string,\n module?: 'esm' | 'cjs',\n) => {\n const createPrefix = PACKAGE_MANAGER_COMMANDS[pm]?.create ?? `${pm} create`;\n const pkgName = tag ? `@aws/nx-workspace@${tag}` : '@aws/nx-workspace';\n const parts = [\n createPrefix,\n pkgName,\n // npm requires '--' to stop interpreting subsequent flags as npm config\n ...(pm === 'npm' ? ['--'] : []),\n workspace,\n ...(iac ? [`--iac=${iac}`] : []),\n ...(module ? [`--module=${module}`] : []),\n ];\n return parts.join(' ');\n};\n"],"names":["TS_VERSIONS","NX_VERSION","PACKAGE_MANAGER_COMMANDS","npm","exec","run","create","pnpm","yarn","bun","buildPackageManagerExecCommand","pm","command","prefix","buildPackageManagerShortCommand","buildInstallCommand","pkg","dev","buildNxInitCommand","dlxPrefix","buildCreateNxWorkspaceCommand","workspace","iac","tag","module","createPrefix","pkgName","parts","join"],"mappings":"AAAA;;;CAGC,GACD,SAASA,WAAW,QAAQ,gBAAa;AAEzC;;;;CAIC,GACD,OAAO,MAAMC,aAAaD,WAAW,CAAC,aAAa,CAAC;AAoBpD,OAAO,MAAME,2BAGT;IACFC,KAAK;QAAEC,MAAM;QAAOC,KAAK;QAAWC,QAAQ;IAAa;IACzDC,MAAM;QAAEH,MAAM;QAAQC,KAAK;QAAQC,QAAQ;IAAc;IACzDE,MAAM;QAAEJ,MAAM;QAAQC,KAAK;QAAQC,QAAQ;IAAc;IACzDG,KAAK;QAAEL,MAAM;QAAQC,KAAK;QAAOC,QAAQ;IAAa;AACxD,EAAE;AAEF;;CAEC,GACD,OAAO,MAAMI,iCAAiC,CAACC,IAAYC;IACzD,MAA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SAAK,GAAG,EAAE;QAC9BU;WACIC,MAAM;YAAC,CAAC,MAAM,EAAEA,KAAK;SAAC,GAAG,EAAE;WAC3BE,SAAS;YAAC,CAAC,SAAS,EAAEA,QAAQ;SAAC,GAAG,EAAE;KACzC;IACD,OAAOG,MAAMC,IAAI,CAAC;AACpB,EAAE"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
import { OverwriteStrategy, type Tree } from '@nx/devkit';
|
|
6
|
+
import { type Containers } from './containers';
|
|
7
|
+
import type { Iac } from './iac';
|
|
8
|
+
export declare const PNPM_BUILT_DEPENDENCIES: string[];
|
|
9
|
+
/**
|
|
10
|
+
* Options controlling how the workspace is initialised. These mirror the
|
|
11
|
+
* preset schema so a workspace created via the preset and one initialised via
|
|
12
|
+
* the `init` generator end up in the same shape.
|
|
13
|
+
*/
|
|
14
|
+
export interface ApplyWorkspaceInitOptions {
|
|
15
|
+
/** The IaC provider to record in the plugin config. */
|
|
16
|
+
readonly iac: Iac;
|
|
17
|
+
/**
|
|
18
|
+
* The container engine to record. `undefined`/`'infer'` picks docker when
|
|
19
|
+
* installed, else finch.
|
|
20
|
+
*/
|
|
21
|
+
readonly containers?: Containers | 'infer';
|
|
22
|
+
/** Whether to configure MCP servers for coding agents. Defaults to true. */
|
|
23
|
+
readonly mcp?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* How to treat the generated workspace README. The preset owns the README of
|
|
26
|
+
* a greenfield workspace (`Overwrite`); the `init` generator must not clobber
|
|
27
|
+
* an existing workspace's README (`KeepExisting`, the default).
|
|
28
|
+
*/
|
|
29
|
+
readonly readmeOverwriteStrategy?: OverwriteStrategy;
|
|
30
|
+
/**
|
|
31
|
+
* Whether to overwrite root package.json scripts that already exist. The
|
|
32
|
+
* preset owns a greenfield workspace's scripts (`true`); the `init`
|
|
33
|
+
* generator must not clobber an existing workspace's scripts (`false`,
|
|
34
|
+
* the default) — it only adds the convenience scripts that are absent.
|
|
35
|
+
*/
|
|
36
|
+
readonly overwriteScripts?: boolean;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Transform an Nx workspace into one ready to run `@aws/nx-plugin` generators.
|
|
40
|
+
*
|
|
41
|
+
* This is the deterministic core shared by the workspace preset and the `init`
|
|
42
|
+
* generator. It is safe to re-run: every step is idempotent (config merges,
|
|
43
|
+
* keyed nx.json / package.json entries, create-if-missing files), so running
|
|
44
|
+
* it against an already-initialised workspace is a no-op.
|
|
45
|
+
*
|
|
46
|
+
* It preserves the workspace's module format: the root package.json `type`
|
|
47
|
+
* field is owned by the preset (written from its `--module` option) and left
|
|
48
|
+
* untouched here. It does NOT rewrite an existing `tsconfig.base.json`'s
|
|
49
|
+
* compiler options, migrate a workspace's package manager, or restructure
|
|
50
|
+
* existing projects — those are decisions for the user (see the "add to an
|
|
51
|
+
* existing workspace" guide).
|
|
52
|
+
*/
|
|
53
|
+
export declare const applyWorkspaceInit: (tree: Tree, { iac, containers, mcp, readmeOverwriteStrategy, overwriteScripts, }: ApplyWorkspaceInitOptions) => Promise<void>;
|