@aws/nx-plugin 1.0.0-rc.95 → 1.0.0-rc.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/LICENSE-THIRD-PARTY +234 -38
  2. package/migrations.json +65 -2
  3. package/package.json +6 -6
  4. package/src/agentcore-gateway/__snapshots__/generator.spec.ts.snap +1 -1
  5. package/src/agentcore-gateway/generator.js +6 -0
  6. package/src/agentcore-gateway/generator.js.map +1 -1
  7. package/src/agentcore-gateway/react-connection/__snapshots__/generator.spec.ts.snap +4 -1
  8. package/src/agentcore-harness/__snapshots__/generator.spec.ts.snap +68 -4
  9. package/src/agentcore-harness/generator.js +6 -0
  10. package/src/agentcore-harness/generator.js.map +1 -1
  11. package/src/connection/gateway-runtime-config.js +1 -1
  12. package/src/connection/gateway-runtime-config.js.map +1 -1
  13. package/src/infra/app/__snapshots__/generator.spec.ts.snap +10 -16
  14. package/src/infra/app/generator.js +34 -7
  15. package/src/infra/app/generator.js.map +1 -1
  16. package/src/init/generator.d.ts +1 -1
  17. package/src/init/generator.js +8 -6
  18. package/src/init/generator.js.map +1 -1
  19. package/src/init/schema.d.js.map +1 -1
  20. package/src/init/schema.d.ts +1 -0
  21. package/src/init/schema.json +5 -0
  22. package/src/mcp-server/server.js +2 -0
  23. package/src/mcp-server/server.js.map +1 -1
  24. package/src/mcp-server/tools/best-practices.d.ts +28 -0
  25. package/src/mcp-server/tools/best-practices.js +43 -0
  26. package/src/mcp-server/tools/best-practices.js.map +1 -0
  27. package/src/mcp-server/tools/general-guidance.d.ts +1 -1
  28. package/src/mcp-server/tools/general-guidance.js +13 -4
  29. package/src/mcp-server/tools/general-guidance.js.map +1 -1
  30. package/src/migrations/latest/checkov-scan-cache-inputs/metadata.json +3 -0
  31. package/src/migrations/latest/checkov-scan-cache-inputs/migration.d.ts +6 -0
  32. package/src/migrations/latest/checkov-scan-cache-inputs/migration.js +58 -0
  33. package/src/migrations/latest/checkov-scan-cache-inputs/migration.js.map +1 -0
  34. package/src/migrations/latest/gateway-url-accessor/__snapshots__/migration.spec.ts.snap +84 -0
  35. package/src/migrations/latest/gateway-url-accessor/metadata.json +3 -0
  36. package/src/migrations/latest/gateway-url-accessor/migration.d.ts +6 -0
  37. package/src/migrations/latest/gateway-url-accessor/migration.js +94 -0
  38. package/src/migrations/latest/gateway-url-accessor/migration.js.map +1 -0
  39. package/src/migrations/latest/infra-deploy-express-mode/metadata.json +1 -1
  40. package/src/migrations/latest/infra-deploy-express-mode/migration.js +26 -28
  41. package/src/migrations/latest/infra-deploy-express-mode/migration.js.map +1 -1
  42. package/src/migrations/latest/py-lambda-powertools-context/metadata.json +3 -0
  43. package/src/migrations/latest/py-lambda-powertools-context/migration.d.ts +6 -0
  44. package/src/migrations/latest/py-lambda-powertools-context/migration.js +58 -0
  45. package/src/migrations/latest/py-lambda-powertools-context/migration.js.map +1 -0
  46. package/src/migrations/latest/script-project-quality-gates/metadata.json +3 -0
  47. package/src/migrations/latest/script-project-quality-gates/migration.d.ts +6 -0
  48. package/src/migrations/latest/script-project-quality-gates/migration.js +53 -0
  49. package/src/migrations/latest/script-project-quality-gates/migration.js.map +1 -0
  50. package/src/migrations/latest/smithy-extension-trait-aliases/__snapshots__/migration.spec.ts.snap +25 -0
  51. package/src/migrations/latest/smithy-extension-trait-aliases/metadata.json +3 -0
  52. package/src/migrations/latest/smithy-extension-trait-aliases/migration.d.ts +28 -0
  53. package/src/migrations/latest/smithy-extension-trait-aliases/migration.js +75 -0
  54. package/src/migrations/latest/smithy-extension-trait-aliases/migration.js.map +1 -0
  55. package/src/migrations/latest/terraform-validate-without-backend/metadata.json +3 -0
  56. package/src/migrations/latest/terraform-validate-without-backend/migration.d.ts +6 -0
  57. package/src/migrations/latest/terraform-validate-without-backend/migration.js +84 -0
  58. package/src/migrations/latest/terraform-validate-without-backend/migration.js.map +1 -0
  59. package/src/preset/__snapshots__/generator.spec.ts.snap +3 -5
  60. package/src/preset/generator.js +4 -25
  61. package/src/preset/generator.js.map +1 -1
  62. package/src/py/agent/a2a-connection/generator.d.ts +1 -1
  63. package/src/py/agent/gateway-connection/generator.d.ts +1 -1
  64. package/src/py/agent/mcp-connection/generator.d.ts +1 -1
  65. package/src/py/agent/react-connection/__snapshots__/generator.spec.ts.snap +4 -1
  66. package/src/py/agent/react-connection/generator.d.ts +29 -0
  67. package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +8 -10
  68. package/src/py/dynamodb/generator.js +34 -7
  69. package/src/py/dynamodb/generator.js.map +1 -1
  70. package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -1
  71. package/src/py/lambda-function/files/handler/__lambdaFunctionSnakeCase__.py.template +2 -1
  72. package/src/py/project/schema.json +3 -1
  73. package/src/py/rdb/__snapshots__/generator.spec.ts.snap +28 -12
  74. package/src/py/rdb/files/Dockerfile.create-db-user.template +7 -3
  75. package/src/py/rdb/files/Dockerfile.migration.template +7 -3
  76. package/src/py/rdb/generator.js +29 -28
  77. package/src/py/rdb/generator.js.map +1 -1
  78. package/src/smithy/react-connection/files/model/extensions.smithy.template +3 -3
  79. package/src/smithy/ts/api/generator.js +7 -2
  80. package/src/smithy/ts/api/generator.js.map +1 -1
  81. package/src/terraform/project/generator.js +34 -10
  82. package/src/terraform/project/generator.js.map +1 -1
  83. package/src/trpc/backend/generator.js +7 -1
  84. package/src/trpc/backend/generator.js.map +1 -1
  85. package/src/trpc/react/generator.js +6 -0
  86. package/src/trpc/react/generator.js.map +1 -1
  87. package/src/ts/agent/generator.js +3 -3
  88. package/src/ts/agent/generator.js.map +1 -1
  89. package/src/ts/agent/react-connection/generator.d.ts +37 -0
  90. package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +2 -0
  91. package/src/ts/dynamodb/generator.js +30 -6
  92. package/src/ts/dynamodb/generator.js.map +1 -1
  93. package/src/ts/lib/biome.d.ts +15 -1
  94. package/src/ts/lib/biome.js +79 -63
  95. package/src/ts/lib/biome.js.map +1 -1
  96. package/src/ts/lib/generator.d.ts +13 -0
  97. package/src/ts/lib/generator.js +14 -9
  98. package/src/ts/lib/generator.js.map +1 -1
  99. package/src/ts/lib/ts-project-utils.d.ts +31 -1
  100. package/src/ts/lib/ts-project-utils.js +53 -0
  101. package/src/ts/lib/ts-project-utils.js.map +1 -1
  102. package/src/ts/lib/vitest.d.ts +6 -0
  103. package/src/ts/lib/vitest.js +16 -1
  104. package/src/ts/lib/vitest.js.map +1 -1
  105. package/src/ts/mcp-server/generator.js +3 -3
  106. package/src/ts/mcp-server/generator.js.map +1 -1
  107. package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +5 -0
  108. package/src/ts/rdb/files/Dockerfile.template +5 -0
  109. package/src/ts/rdb/generator.d.ts +8 -0
  110. package/src/ts/rdb/generator.js +28 -24
  111. package/src/ts/rdb/generator.js.map +1 -1
  112. package/src/ts/rdb/trpc-connection/__snapshots__/generator.spec.ts.snap +39 -0
  113. package/src/ts/rdb/trpc-connection/generator.js +13 -0
  114. package/src/ts/rdb/trpc-connection/generator.js.map +1 -1
  115. package/src/ts/react-website/agui/files/common/src/components/__agentNameKebabCase__-chat.tsx.template +9 -0
  116. package/src/ts/react-website/agui/files/common/src/hooks/useAgui__agentNameClassName__.tsx.template +4 -1
  117. package/src/ts/react-website/agui/generator.d.ts +21 -0
  118. package/src/ts/react-website/agui/generator.js +6 -2
  119. package/src/ts/react-website/agui/generator.js.map +1 -1
  120. package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +26 -22
  121. package/src/ts/react-website/app/generator.d.ts +42 -0
  122. package/src/ts/react-website/app/generator.js +4 -8
  123. package/src/ts/react-website/app/generator.js.map +1 -1
  124. package/src/utils/agent-connection/agent-connection.d.ts +2 -1
  125. package/src/utils/agent-connection/agent-connection.js +6 -1
  126. package/src/utils/agent-connection/agent-connection.js.map +1 -1
  127. package/src/utils/agent-core-constructs/files/cdk/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.ts.template +11 -7
  128. package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +14 -6
  129. package/src/utils/agent-core-packaging.js +5 -5
  130. package/src/utils/agent-core-packaging.js.map +1 -1
  131. package/src/utils/api-constructs/api-constructs.d.ts +5 -0
  132. package/src/utils/api-constructs/api-constructs.js +8 -0
  133. package/src/utils/api-constructs/api-constructs.js.map +1 -1
  134. package/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template +4 -2
  135. package/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template +4 -2
  136. package/src/utils/ast.d.ts +10 -0
  137. package/src/utils/ast.js +33 -0
  138. package/src/utils/ast.js.map +1 -1
  139. package/src/utils/dependencies.js +1 -10
  140. package/src/utils/dependencies.js.map +1 -1
  141. package/src/utils/docker.d.ts +11 -0
  142. package/src/utils/docker.js +16 -3
  143. package/src/utils/docker.js.map +1 -1
  144. package/src/utils/dynamodb-config.d.ts +48 -0
  145. package/src/utils/dynamodb-config.js +44 -0
  146. package/src/utils/dynamodb-config.js.map +1 -0
  147. package/src/utils/dynamodb-constructs/files/cdk/app/dynamodb/__nameKebabCase__.ts.template +8 -4
  148. package/src/utils/git-secrets.d.ts +28 -0
  149. package/src/utils/git-secrets.js +66 -0
  150. package/src/utils/git-secrets.js.map +1 -0
  151. package/src/utils/init.js +7 -6
  152. package/src/utils/init.js.map +1 -1
  153. package/src/utils/local-project-dependency.d.ts +28 -0
  154. package/src/utils/local-project-dependency.js +40 -0
  155. package/src/utils/local-project-dependency.js.map +1 -0
  156. package/src/utils/nx.d.ts +14 -0
  157. package/src/utils/nx.js +30 -0
  158. package/src/utils/nx.js.map +1 -1
  159. package/src/utils/rdb-constructs/files/cdk/app/dbs/__nameKebabCase__.ts.template +11 -6
  160. package/src/utils/script-project-targets.d.ts +26 -0
  161. package/src/utils/script-project-targets.js +75 -0
  162. package/src/utils/script-project-targets.js.map +1 -0
  163. package/src/utils/shared-shadcn.d.ts +13 -0
  164. package/src/utils/shared-shadcn.js +3 -2
  165. package/src/utils/shared-shadcn.js.map +1 -1
  166. package/src/utils/test.js +15 -0
  167. package/src/utils/test.js.map +1 -1
  168. package/src/utils/version-upgrade-migration/sync-vended-versions.js +4 -4
  169. package/src/utils/version-upgrade-migration/sync-vended-versions.js.map +1 -1
  170. package/src/utils/versions.d.ts +13 -9
  171. package/src/utils/versions.js +17 -8
  172. package/src/utils/versions.js.map +1 -1
  173. package/src/utils/website-constructs/files/cdk/app/static-websites/__websiteNameKebabCase__.ts.template +8 -4
  174. package/src/py/dynamodb/files/__name__/__init__.py.template +0 -6
  175. package/src/py/dynamodb/files/__name__/entities/__init__.py.template +0 -4
  176. package/src/py/dynamodb/files/config.json.template +0 -24
  177. package/src/ts/dynamodb/files/config.json.template +0 -24
  178. package/src/ts/dynamodb/files/src/entities/index.ts.template +0 -1
  179. package/src/ts/dynamodb/files/src/index.ts.template +0 -2
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */ import { joinPathFragments, logger, updateJson } from "@nx/devkit";
5
+ import { readFileSync } from "fs";
6
+ import { forDependencies } from "./declared-dependencies.js";
7
+ import { addDependenciesToPackageJson } from "./dependencies.js";
8
+ import { withVersions } from "./versions.js";
9
+ /** Dependencies a caller must declare to set up git-secrets. */ export const GIT_SECRETS_DEPENDENCIES = [
10
+ {
11
+ name: 'husky'
12
+ }
13
+ ];
14
+ /** The vended script, which the husky pre-commit hook runs. */ export const GIT_SECRETS_SCRIPT = '.git-secrets/git-secrets';
15
+ const HUSKY_PRE_COMMIT = '.husky/pre-commit';
16
+ /**
17
+ * Patterns allowed so a generated workspace commits cleanly, matched against
18
+ * `<path>:<line>:<content>`. Only the vended script, whose body contains the
19
+ * patterns it registers.
20
+ */ export const GIT_SECRETS_ALLOWED = [
21
+ '\\.git-secrets/git-secrets:'
22
+ ];
23
+ /**
24
+ * Vend the git-secrets pre-commit hook: the script itself, the husky hook that
25
+ * runs it, and the allowlist.
26
+ *
27
+ * Re-runnable. The vendored script is always rewritten so an upgrade picks up a
28
+ * newer copy, while everything a user owns is preserved: `.gitallowed` only
29
+ * gains the entries a generated workspace needs, and an existing `pre-commit`
30
+ * hook or `prepare` script is left alone and reported rather than replaced.
31
+ */ export const setUpGitSecrets = (tree, declaration)=>{
32
+ const filesDir = joinPathFragments(import.meta.dirname, '..', 'preset', 'git-secrets-files');
33
+ tree.write(GIT_SECRETS_SCRIPT, readFileSync(joinPathFragments(filesDir, 'git-secrets-dir', 'git-secrets'), 'utf-8'));
34
+ const hook = readFileSync(joinPathFragments(filesDir, 'husky-dir', 'pre-commit'), 'utf-8');
35
+ const existingHook = tree.read(HUSKY_PRE_COMMIT, 'utf-8');
36
+ if (existingHook === null) {
37
+ tree.write(HUSKY_PRE_COMMIT, hook);
38
+ } else if (!existingHook.includes(GIT_SECRETS_SCRIPT)) {
39
+ logger.warn(`Your ${HUSKY_PRE_COMMIT} was left as-is. To scan staged files for AWS credentials, add:\n\n${hook}`);
40
+ }
41
+ // Preserve any entries the user has added, appending only the ones missing.
42
+ const existingAllowed = tree.read('.gitallowed', 'utf-8')?.split('\n').map((line)=>line.trimEnd()).filter((line)=>line !== '') ?? [];
43
+ const allowed = [
44
+ ...existingAllowed,
45
+ ...GIT_SECRETS_ALLOWED.filter((pattern)=>!existingAllowed.includes(pattern))
46
+ ];
47
+ tree.write('.gitallowed', `${allowed.join('\n')}\n`);
48
+ updateJson(tree, 'package.json', (json)=>{
49
+ const prepare = json.scripts?.prepare;
50
+ if (prepare !== undefined && !prepare.includes('husky')) {
51
+ logger.warn(`Your \`prepare\` script was left as-is. Git hooks are installed by husky, so add \`husky\` to it for the pre-commit hook to run.`);
52
+ }
53
+ return {
54
+ ...json,
55
+ scripts: {
56
+ ...json.scripts,
57
+ prepare: prepare ?? 'husky'
58
+ }
59
+ };
60
+ });
61
+ addDependenciesToPackageJson(tree, {}, withVersions(forDependencies(declaration), [
62
+ 'husky'
63
+ ]));
64
+ };
65
+
66
+ //# sourceMappingURL=git-secrets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/git-secrets.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, logger, type Tree, updateJson } from '@nx/devkit';\nimport { readFileSync } from 'fs';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from './declared-dependencies.js';\nimport { addDependenciesToPackageJson } from './dependencies.js';\nimport { type ITsDepVersion, withVersions } from './versions.js';\n\n/** Dependencies a caller must declare to set up git-secrets. */\nexport const GIT_SECRETS_DEPENDENCIES = [\n { name: 'husky' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** The vended script, which the husky pre-commit hook runs. */\nexport const GIT_SECRETS_SCRIPT = '.git-secrets/git-secrets';\n\nconst HUSKY_PRE_COMMIT = '.husky/pre-commit';\n\n/**\n * Patterns allowed so a generated workspace commits cleanly, matched against\n * `<path>:<line>:<content>`. Only the vended script, whose body contains the\n * patterns it registers.\n */\nexport const GIT_SECRETS_ALLOWED = ['\\\\.git-secrets/git-secrets:'];\n\n/**\n * Vend the git-secrets pre-commit hook: the script itself, the husky hook that\n * runs it, and the allowlist.\n *\n * Re-runnable. The vendored script is always rewritten so an upgrade picks up a\n * newer copy, while everything a user owns is preserved: `.gitallowed` only\n * gains the entries a generated workspace needs, and an existing `pre-commit`\n * hook or `prepare` script is left alone and reported rather than replaced.\n */\nexport const setUpGitSecrets = <const D extends DependencyDeclaration>(\n tree: Tree,\n declaration: D & MustDeclare<typeof GIT_SECRETS_DEPENDENCIES, D>,\n) => {\n const filesDir = joinPathFragments(\n import.meta.dirname,\n '..',\n 'preset',\n 'git-secrets-files',\n );\n\n tree.write(\n GIT_SECRETS_SCRIPT,\n readFileSync(\n joinPathFragments(filesDir, 'git-secrets-dir', 'git-secrets'),\n 'utf-8',\n ),\n );\n\n const hook = readFileSync(\n joinPathFragments(filesDir, 'husky-dir', 'pre-commit'),\n 'utf-8',\n );\n const existingHook = tree.read(HUSKY_PRE_COMMIT, 'utf-8');\n if (existingHook === null) {\n tree.write(HUSKY_PRE_COMMIT, hook);\n } else if (!existingHook.includes(GIT_SECRETS_SCRIPT)) {\n logger.warn(\n `Your ${HUSKY_PRE_COMMIT} was left as-is. To scan staged files for AWS credentials, add:\\n\\n${hook}`,\n );\n }\n\n // Preserve any entries the user has added, appending only the ones missing.\n const existingAllowed =\n tree\n .read('.gitallowed', 'utf-8')\n ?.split('\\n')\n .map((line) => line.trimEnd())\n .filter((line) => line !== '') ?? [];\n const allowed = [\n ...existingAllowed,\n ...GIT_SECRETS_ALLOWED.filter(\n (pattern) => !existingAllowed.includes(pattern),\n ),\n ];\n tree.write('.gitallowed', `${allowed.join('\\n')}\\n`);\n\n updateJson(tree, 'package.json', (json) => {\n const prepare: string | undefined = json.scripts?.prepare;\n if (prepare !== undefined && !prepare.includes('husky')) {\n logger.warn(\n `Your \\`prepare\\` script was left as-is. Git hooks are installed by husky, so add \\`husky\\` to it for the pre-commit hook to run.`,\n );\n }\n return {\n ...json,\n scripts: { ...json.scripts, prepare: prepare ?? 'husky' },\n };\n });\n\n addDependenciesToPackageJson(\n tree,\n {},\n withVersions(\n forDependencies<typeof GIT_SECRETS_DEPENDENCIES>(declaration),\n ['husky'],\n ),\n );\n};\n"],"names":["joinPathFragments","logger","updateJson","readFileSync","forDependencies","addDependenciesToPackageJson","withVersions","GIT_SECRETS_DEPENDENCIES","name","GIT_SECRETS_SCRIPT","HUSKY_PRE_COMMIT","GIT_SECRETS_ALLOWED","setUpGitSecrets","tree","declaration","filesDir","dirname","write","hook","existingHook","read","includes","warn","existingAllowed","split","map","line","trimEnd","filter","allowed","pattern","join","json","prepare","scripts","undefined"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EAAEC,MAA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B,WAAWW,MAAM,gBAAgB,CAACmB;QAChC,MAAMC,UAA8BD,KAAKE,OAAO,EAAED;QAClD,IAAIA,YAAYE,aAAa,CAACF,QAAQZ,QAAQ,CAAC,UAAU;YACvDpB,OAAOqB,IAAI,CACT,CAAC,gIAAgI,CAAC;QAEtI;QACA,OAAO;YACL,GAAGU,IAAI;YACPE,SAAS;gBAAE,GAAGF,KAAKE,OAAO;gBAAED,SAASA,WAAW;YAAQ;QAC1D;IACF;IAEA5B,6BACEQ,MACA,CAAC,GACDP,aACEF,gBAAiDU,cACjD;QAAC;KAAQ;AAGf,EAAE"}
package/src/utils/init.js CHANGED
@@ -256,12 +256,13 @@ export const PNPM_BUILT_DEPENDENCIES = [
256
256
  ...packageJson.scripts
257
257
  }
258
258
  }));
259
- // Pin the workspace's `nx` to the version the plugin's @nx/* packages are
260
- // built against. A mismatched workspace nx (even a patch apart) hoists a
261
- // second nested nx under @nx/js, and the two instances deadlock `nx sync`.
262
- // `@nx/js` must be a root dependency for the `@nx/js:typescript-sync`
263
- // generator registered in nx.json to resolve (npm doesn't hoist the
264
- // plugin's own copy reliably).
259
+ // Declare the `nx` version the plugin's @nx/* packages are built against. A
260
+ // mismatched workspace nx (even a patch apart) hoists a second nested nx
261
+ // under @nx/js, and the two instances deadlock `nx sync` — but a workspace
262
+ // already on a newer nx keeps it, since devkit never downgrades an existing
263
+ // range. `@nx/js` must be a root dependency for the
264
+ // `@nx/js:typescript-sync` generator registered in nx.json to resolve (npm
265
+ // doesn't hoist the plugin's own copy reliably).
265
266
  addDependenciesToPackageJson(tree, {}, {
266
267
  ...withVersions(forDependencies(declaration), [
267
268
  'nx',
@@ -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 { 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 { updateGitIgnore } from './git.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 from pnpm 11\n// onwards); pnpm 11 and above read `allowBuilds` instead. Any dep NOT in this\n// allowlist will have its install scripts skipped with a warning — matching\n// pnpm 10's default behaviour. The user can opt-in later via\n// `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 // pnpm creates these at the workspace root while it materialises packages.\n updateGitIgnore(tree, '.', (patterns) => [...patterns, '_tmp_*']);\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","updateGitIgnore","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","patterns","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,sBAAsB,QAAQ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MAAM,CAAC,eAAe;QAC9BH,KAAKgB,KAAK,CACR,cACAY,KAAKC,SAAS,CAAChD,sBAAsBmB,OAAO,MAAM;IAEtD;IAEApC,cACEoC,MACAnC,kBAAkB,YAAYuG,OAAO,EAAE,MAAM,UAAU,UACvD,KACA;QACEC,aAAanF,YAAYc;QACzBsE,YAAY3D,OAAO4D,OAAO,CAACxF,uBACxB0E,MAAM,CAAC,CAAC,GAAGe,KAAK,GAAK,CAACA,KAAKC,MAAM,EACjC5D,GAAG,CAAC,CAAC,CAAC6D,IAAIF,KAAK,GAAM,CAAA;gBACpB3E,MAAM6E;gBACNC,aAAa7F,8BAA8B0F;YAC7C,CAAA;QACF,GAAG,AAAC,CAAA;YACF,MAAMI,OAAOtF;YACb,OAAO;gBACLuF,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;QACjBtD,oBAAoBe;IACtB;AACF,EAAE"}
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 { 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 { updateGitIgnore } from './git.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 from pnpm 11\n// onwards); pnpm 11 and above read `allowBuilds` instead. Any dep NOT in this\n// allowlist will have its install scripts skipped with a warning — matching\n// pnpm 10's default behaviour. The user can opt-in later via\n// `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 // pnpm creates these at the workspace root while it materialises packages.\n updateGitIgnore(tree, '.', (patterns) => [...patterns, '_tmp_*']);\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 // Declare the `nx` version the plugin's @nx/* packages are built against. A\n // mismatched workspace nx (even a patch apart) hoists a second nested nx\n // under @nx/js, and the two instances deadlock `nx sync` — but a workspace\n // already on a newer nx keeps it, since devkit never downgrades an existing\n // range. `@nx/js` must be a root dependency for the\n // `@nx/js:typescript-sync` generator registered in nx.json to resolve (npm\n // doesn't hoist the 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","updateGitIgnore","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","patterns","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,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;AACpD,SACEC,6BAA6B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AC,GAAGe,KAAK,GAAK,CAACA,KAAKC,MAAM,EACjC5D,GAAG,CAAC,CAAC,CAAC6D,IAAIF,KAAK,GAAM,CAAA;gBACpB3E,MAAM6E;gBACNC,aAAa7F,8BAA8B0F;YAC7C,CAAA;QACF,GAAG,AAAC,CAAA;YACF,MAAMI,OAAOtF;YACb,OAAO;gBACLuF,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;QACjBtD,oBAAoBe;IACtB;AACF,EAAE"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ import { type Tree } from '@nx/devkit';
6
+ /** A cross-project import a generator emits. */
7
+ export interface LocalProjectDependency {
8
+ /** Root of the project whose generated source contains the import. */
9
+ readonly consumerRoot: string;
10
+ /** Root of the project being imported. */
11
+ readonly dependencyRoot: string;
12
+ }
13
+ /**
14
+ * Declare a generated cross-project import in the importing project's own
15
+ * `package.json`, so a freshly generated workspace passes `lint`.
16
+ *
17
+ * `noUndeclaredDependencies` fails a project whose source imports a package its
18
+ * manifest doesn't declare. The `ts#sync` generator derives that from the
19
+ * project graph, but only runs as part of a task run — so a workspace that has
20
+ * never built fails `lint` before it has had the chance to, on generated code
21
+ * the user never touched.
22
+ *
23
+ * The specifier matches what `ts#sync` writes, so the two agree and re-running
24
+ * either is a no-op. TypeScript project references are left to
25
+ * `@nx/js:typescript-sync`, which owns resolving them. Sync stays the safety
26
+ * net for imports the user adds themselves.
27
+ */
28
+ export declare const addLocalProjectDependency: (tree: Tree, { consumerRoot, dependencyRoot }: LocalProjectDependency) => void;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */ import { joinPathFragments, readJson } from "@nx/devkit";
5
+ import { addDependenciesToPackageJson, getLocalDependencySpecifier } from "./dependencies.js";
6
+ /**
7
+ * Declare a generated cross-project import in the importing project's own
8
+ * `package.json`, so a freshly generated workspace passes `lint`.
9
+ *
10
+ * `noUndeclaredDependencies` fails a project whose source imports a package its
11
+ * manifest doesn't declare. The `ts#sync` generator derives that from the
12
+ * project graph, but only runs as part of a task run — so a workspace that has
13
+ * never built fails `lint` before it has had the chance to, on generated code
14
+ * the user never touched.
15
+ *
16
+ * The specifier matches what `ts#sync` writes, so the two agree and re-running
17
+ * either is a no-op. TypeScript project references are left to
18
+ * `@nx/js:typescript-sync`, which owns resolving them. Sync stays the safety
19
+ * net for imports the user adds themselves.
20
+ */ export const addLocalProjectDependency = (tree, { consumerRoot, dependencyRoot })=>{
21
+ const dependencyManifest = joinPathFragments(dependencyRoot, 'package.json');
22
+ const consumerManifest = joinPathFragments(consumerRoot, 'package.json');
23
+ if (!tree.exists(dependencyManifest) || !tree.exists(consumerManifest)) {
24
+ return;
25
+ }
26
+ const packageName = readJson(tree, dependencyManifest).name;
27
+ if (!packageName) {
28
+ return;
29
+ }
30
+ const { dependencies = {}, devDependencies = {} } = readJson(tree, consumerManifest);
31
+ // Declared in either list already — leave the user's choice alone.
32
+ if (dependencies[packageName] || devDependencies[packageName]) {
33
+ return;
34
+ }
35
+ addDependenciesToPackageJson(tree, {
36
+ [packageName]: getLocalDependencySpecifier(tree)
37
+ }, {}, consumerManifest);
38
+ };
39
+
40
+ //# sourceMappingURL=local-project-dependency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/local-project-dependency.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, readJson, type Tree } from '@nx/devkit';\nimport {\n addDependenciesToPackageJson,\n getLocalDependencySpecifier,\n} from './dependencies.js';\n\n/** A cross-project import a generator emits. */\nexport interface LocalProjectDependency {\n /** Root of the project whose generated source contains the import. */\n readonly consumerRoot: string;\n /** Root of the project being imported. */\n readonly dependencyRoot: string;\n}\n\n/**\n * Declare a generated cross-project import in the importing project's own\n * `package.json`, so a freshly generated workspace passes `lint`.\n *\n * `noUndeclaredDependencies` fails a project whose source imports a package its\n * manifest doesn't declare. The `ts#sync` generator derives that from the\n * project graph, but only runs as part of a task run — so a workspace that has\n * never built fails `lint` before it has had the chance to, on generated code\n * the user never touched.\n *\n * The specifier matches what `ts#sync` writes, so the two agree and re-running\n * either is a no-op. TypeScript project references are left to\n * `@nx/js:typescript-sync`, which owns resolving them. Sync stays the safety\n * net for imports the user adds themselves.\n */\nexport const addLocalProjectDependency = (\n tree: Tree,\n { consumerRoot, dependencyRoot }: LocalProjectDependency,\n): void => {\n const dependencyManifest = joinPathFragments(dependencyRoot, 'package.json');\n const consumerManifest = joinPathFragments(consumerRoot, 'package.json');\n if (!tree.exists(dependencyManifest) || !tree.exists(consumerManifest)) {\n return;\n }\n const packageName = readJson<{ name?: string }>(\n tree,\n dependencyManifest,\n ).name;\n if (!packageName) {\n return;\n }\n const { dependencies = {}, devDependencies = {} } = readJson<{\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n }>(tree, consumerManifest);\n // Declared in either list already — leave the user's choice alone.\n if (dependencies[packageName] || devDependencies[packageName]) {\n return;\n }\n addDependenciesToPackageJson(\n tree,\n { [packageName]: getLocalDependencySpecifier(tree) },\n {},\n consumerManifest,\n );\n};\n"],"names":["joinPathFragments","readJson","addDependenciesToPackageJson","getLocalDependencySpecifier","addLocalProjectDependency","tree","consumerRoot","dependencyRoot","dependencyManifest","consumerManifest","exists","packageName","name","dependencies","devDependencies"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EAAEC,QAAQ,QAAmB,aAAa;AACpE,SACEC,4BAA4B,EAC5BC,2BAA2B,QACtB,oBAAoB;AAU3B;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,4BAA4B,CACvCC,MACA,EAAEC,YAAY,EAAEC,cAAc,EAA0B;IAExD,MAAMC,qBAAqBR,kBAAkBO,gBAAgB;IAC7D,MAAME,mBAAmBT,kBAAkBM,cAAc;IACzD,IAAI,CAACD,KAAKK,MAAM,CAACF,uBAAuB,CAACH,KAAKK,MAAM,CAACD,mBAAmB;QACtE;IACF;IACA,MAAME,cAAcV,SAClBI,MACAG,oBACAI,IAAI;IACN,IAAI,CAACD,aAAa;QAChB;IACF;IACA,MAAM,EAAEE,eAAe,CAAC,CAAC,EAAEC,kBAAkB,CAAC,CAAC,EAAE,GAAGb,SAGjDI,MAAMI;IACT,mEAAmE;IACnE,IAAII,YAAY,CAACF,YAAY,IAAIG,eAAe,CAACH,YAAY,EAAE;QAC7D;IACF;IACAT,6BACEG,MACA;QAAE,CAACM,YAAY,EAAER,4BAA4BE;IAAM,GACnD,CAAC,GACDI;AAEJ,EAAE"}
package/src/utils/nx.d.ts CHANGED
@@ -115,6 +115,20 @@ export type TargetDependency = string | {
115
115
  * same order when first authoring a target keeps generators idempotent.
116
116
  */
117
117
  export declare const normalizeTargetKeyOrder: <T extends object>(target: T) => T;
118
+ /**
119
+ * Merge the configuration a generator owns into a project's existing target, so
120
+ * re-running converges that configuration without discarding what other
121
+ * generators (or the user) contributed to the same target.
122
+ *
123
+ * `dependsOn` is unioned: existing entries keep their order and the desired ones
124
+ * are appended only when absent, so a re-run neither drops an entry (e.g. the
125
+ * `bundle` a lambda function adds to `build`) nor duplicates one. Every other
126
+ * key the caller passes wins, since those are the ones the generator owns.
127
+ *
128
+ * The result carries Nx's own key order, so a target authored on the first run
129
+ * serializes identically to the same target merged into on a re-run.
130
+ */
131
+ export declare const mergeTarget: (existing: TargetConfiguration | undefined, desired: TargetConfiguration) => TargetConfiguration;
118
132
  /**
119
133
  * Mutate the project to add the dependency to the target if not already present
120
134
  * Adds the target if not present.
package/src/utils/nx.js CHANGED
@@ -209,6 +209,36 @@ const NX_TARGET_KEY_ORDER = [
209
209
  const bi = NX_TARGET_KEY_ORDER.indexOf(b);
210
210
  return (ai === -1 ? NX_TARGET_KEY_ORDER.length : ai) - (bi === -1 ? NX_TARGET_KEY_ORDER.length : bi);
211
211
  }));
212
+ /**
213
+ * Merge the configuration a generator owns into a project's existing target, so
214
+ * re-running converges that configuration without discarding what other
215
+ * generators (or the user) contributed to the same target.
216
+ *
217
+ * `dependsOn` is unioned: existing entries keep their order and the desired ones
218
+ * are appended only when absent, so a re-run neither drops an entry (e.g. the
219
+ * `bundle` a lambda function adds to `build`) nor duplicates one. Every other
220
+ * key the caller passes wins, since those are the ones the generator owns.
221
+ *
222
+ * The result carries Nx's own key order, so a target authored on the first run
223
+ * serializes identically to the same target merged into on a re-run.
224
+ */ export const mergeTarget = (existing, desired)=>{
225
+ const merged = {
226
+ ...existing,
227
+ ...desired
228
+ };
229
+ const dependsOn = [
230
+ ...existing?.dependsOn ?? []
231
+ ];
232
+ for (const dependency of desired.dependsOn ?? []){
233
+ if (!dependsOn.some((d)=>targetDependencyEquals(d, dependency))) {
234
+ dependsOn.push(dependency);
235
+ }
236
+ }
237
+ if (dependsOn.length > 0) {
238
+ merged.dependsOn = dependsOn;
239
+ }
240
+ return normalizeTargetKeyOrder(merged);
241
+ };
212
242
  /**
213
243
  * Mutate the project to add the dependency to the target if not already present
214
244
  * Adds the target if not present.
@@ -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 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,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,IAAMF,iBAAiB,CAACE,EAAEC,MAAM,EAAE;AAEvD;;CAEC,GACD,OAAO,MAAMC,mBAAmB,CAACC;IAC/B,MAAM,EAAEC,GAAG,EAAEC,IAAI,EAAE,GAAGnB,KAAKoB,KAAK,CAACpB,KAAKS,OAAO,CAACQ;IAC9C,MAAMI,sBAAsBrB,KAAKsB,IAAI,CAACJ,KAAKC;IAC3C,OAAOX,WAAWe,IAAI,CACpB,CAACC,gBACCA,cAAcH,mBAAmB,KAAKA;AAE5C,EAAE;AAEF,OAAO,MAAMI,oBAAoB;IAC/B,OAAOxB,YAAYyB,OAAO;AAC5B,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMC,4BAA4B,CAACC;IACxC,MAAMC,kBAAkBD,KAAKE,MAAM,CAAC,kBAChCjC,SAAS+B,MAAM,kBACfG;IACJ,OAAOF,iBAAiBV,SAAS;AACnC,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAMa,yBAAyB,CAACJ,OACrCD,0BAA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;IACjCoD,WAAWD,UAAU,GAAG;IACxBC,WAAWV,SAAS,KAAK,EAAE;IAC3B,uEAAuE;IACvE,IAAI,CAACU,WAAWV,SAAS,CAACW,QAAQ,CAACH,yBAAyB;QAC1DE,WAAWV,SAAS,CAACG,IAAI,CAACK;IAC5B;IACAlD,OAAO,CAAC,MAAM,GAAGgC,wBAAwBoB;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 * Merge the configuration a generator owns into a project's existing target, so\n * re-running converges that configuration without discarding what other\n * generators (or the user) contributed to the same target.\n *\n * `dependsOn` is unioned: existing entries keep their order and the desired ones\n * are appended only when absent, so a re-run neither drops an entry (e.g. the\n * `bundle` a lambda function adds to `build`) nor duplicates one. Every other\n * key the caller passes wins, since those are the ones the generator owns.\n *\n * The result carries Nx's own key order, so a target authored on the first run\n * serializes identically to the same target merged into on a re-run.\n */\nexport const mergeTarget = (\n existing: TargetConfiguration | undefined,\n desired: TargetConfiguration,\n): TargetConfiguration => {\n const merged: TargetConfiguration = { ...existing, ...desired };\n const dependsOn = [...(existing?.dependsOn ?? [])];\n for (const dependency of desired.dependsOn ?? []) {\n if (!dependsOn.some((d) => targetDependencyEquals(d, dependency))) {\n dependsOn.push(dependency);\n }\n }\n if (dependsOn.length > 0) {\n merged.dependsOn = dependsOn;\n }\n return normalizeTargetKeyOrder(merged);\n};\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","mergeTarget","existing","desired","merged","dependsOn","dependency","some","d","push","addDependencyToTargetIfNotPresent","addArtifactDependencyToTargets","addArtifactProjectToTargets","consumedProjectName","addComponentDevTarget","componentDevTargetName","continuous","projectDev","includes"],"mappings":"AAAA;;;CAG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AE;AAEF;;;;;;;;CAQC,GACD,OAAO,MAAMM,8BAA8B,CACzChE,SACAiE;IAEAH,kCACE9D,SACA,SACA,GAAGiE,oBAAoB,MAAM,CAAC;IAEhCH,kCACE9D,SACA,YACA,GAAGiE,oBAAoB,SAAS,CAAC;AAErC,EAAE;AAEF;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAwB,CACnCrD,SACAsD;IAEAtD,OAAO,CAAC,MAAM,KAAK;QAAEuD,YAAY;QAAMX,WAAW,EAAE;IAAC;IACrD,MAAMY,aAAaxD,OAAO,CAAC,MAAM;IACjCwD,WAAWD,UAAU,GAAG;IACxBC,WAAWZ,SAAS,KAAK,EAAE;IAC3B,uEAAuE;IACvE,IAAI,CAACY,WAAWZ,SAAS,CAACa,QAAQ,CAACH,yBAAyB;QAC1DE,WAAWZ,SAAS,CAACI,IAAI,CAACM;IAC5B;IACAtD,OAAO,CAAC,MAAM,GAAGgC,wBAAwBwB;AAC3C,EAAE"}
@@ -15,10 +15,15 @@ import {
15
15
  Runtime,
16
16
  <%_ } _%>
17
17
  } from 'aws-cdk-lib/aws-lambda';
18
+ <%_ /* Alias the core imports only when this database's name would shadow them. */ _%>
19
+ <%_ const collides = ['AuroraDatabase', 'AuroraDatabaseEngines', 'AuroraDatabaseProps'].includes(nameClassName); _%>
20
+ <%_ const coreDb = collides ? 'CoreAuroraDatabase' : 'AuroraDatabase'; _%>
21
+ <%_ const coreDbEngines = collides ? 'CoreAuroraDatabaseEngines' : 'AuroraDatabaseEngines'; _%>
22
+ <%_ const coreDbProps = collides ? 'CoreAuroraDatabaseProps' : 'AuroraDatabaseProps'; _%>
18
23
  import {
19
- AuroraDatabase,
20
- AuroraDatabaseEngines,
21
- AuroraDatabaseProps,
24
+ AuroraDatabase<% if (collides) { %> as <%= coreDb %><% } %>,
25
+ AuroraDatabaseEngines<% if (collides) { %> as <%= coreDbEngines %><% } %>,
26
+ AuroraDatabaseProps<% if (collides) { %> as <%= coreDbProps %><% } %>,
22
27
  } from '../../core/rdb/aurora<% if (esm) { %>.js<% } %>';
23
28
  import { findWorkspaceRoot } from '../../core/workspace<% if (esm) { %>.js<% } %>';
24
29
 
@@ -43,21 +48,21 @@ const createDbUserBundleDir = path.join(
43
48
  );
44
49
 
45
50
  export type <%= nameClassName %>Props = Omit<
46
- AuroraDatabaseProps,
51
+ <%= coreDbProps %>,
47
52
  'databaseName' | 'adminUser' | 'runtimeConfigKey' | 'engine'
48
53
  >;
49
54
 
50
55
  /**
51
56
  * CDK construct that provisions an Aurora Serverless v2 cluster.
52
57
  */
53
- export class <%= nameClassName %> extends AuroraDatabase {
58
+ export class <%= nameClassName %> extends <%= coreDb %> {
54
59
  constructor(scope: Construct, id: string, props: <%= nameClassName %>Props) {
55
60
  super(scope, id, {
56
61
  ...props,
57
62
  databaseName: '<%= databaseName %>',
58
63
  adminUser: '<%= adminUser %>',
59
64
  runtimeConfigKey,
60
- engine: AuroraDatabaseEngines.<%= engine %>({}),
65
+ engine: <%= coreDbEngines %>.<%= engine %>({}),
61
66
  });
62
67
  }
63
68
 
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ import { type ProjectConfiguration, type Tree } from '@nx/devkit';
6
+ export interface AddScriptProjectTargetsOptions {
7
+ /** Project configuration to add the targets to (mutated in place). */
8
+ readonly project: ProjectConfiguration;
9
+ /** Additional `tsconfig.json` `types` entries beyond `node`. */
10
+ readonly types?: readonly string[];
11
+ }
12
+ /**
13
+ * Give a script-only TypeScript project the same targets a `ts#project` gets,
14
+ * so its vended TypeScript is covered by `nx run-many --target build --all`.
15
+ *
16
+ * Writes a `noEmit` `tsconfig.json` (kept if the user already has one) and adds
17
+ * `typecheck` alongside the shared Biome `lint`/`format` targets and a `build`
18
+ * that runs them. `compile` is deliberately absent: these projects run through
19
+ * `tsx`, so there is no build artifact to produce.
20
+ *
21
+ * The tsconfig is not registered as a workspace project reference — a `noEmit`
22
+ * project produces no declarations for another project to consume, and Nx's
23
+ * `@nx/js/typescript` plugin disables an inferred `typecheck` for any project
24
+ * reachable from one.
25
+ */
26
+ export declare const addScriptProjectTargets: (tree: Tree, options: AddScriptProjectTargetsOptions) => void;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */ import { joinPathFragments, writeJson } from "@nx/devkit";
5
+ import { biomeTargets, registerBiomeNamedInput } from "../ts/lib/biome.js";
6
+ import { normalizeTargetKeyOrder } from "./nx.js";
7
+ import { sortObjectKeys } from "./object.js";
8
+ import { getRelativePathToRootByDirectory } from "./paths.js";
9
+ /**
10
+ * Config a script-only project is type-checked against. It runs through `tsx`
11
+ * and emits nothing, so it opts out of the emit options the workspace's
12
+ * `tsconfig.base.json` sets for project references.
13
+ */ const SCRIPT_TSCONFIG_FILE_NAME = 'tsconfig.json';
14
+ /**
15
+ * Give a script-only TypeScript project the same targets a `ts#project` gets,
16
+ * so its vended TypeScript is covered by `nx run-many --target build --all`.
17
+ *
18
+ * Writes a `noEmit` `tsconfig.json` (kept if the user already has one) and adds
19
+ * `typecheck` alongside the shared Biome `lint`/`format` targets and a `build`
20
+ * that runs them. `compile` is deliberately absent: these projects run through
21
+ * `tsx`, so there is no build artifact to produce.
22
+ *
23
+ * The tsconfig is not registered as a workspace project reference — a `noEmit`
24
+ * project produces no declarations for another project to consume, and Nx's
25
+ * `@nx/js/typescript` plugin disables an inferred `typecheck` for any project
26
+ * reachable from one.
27
+ */ export const addScriptProjectTargets = (tree, options)=>{
28
+ const { project, types = [] } = options;
29
+ const tsConfigPath = joinPathFragments(project.root, SCRIPT_TSCONFIG_FILE_NAME);
30
+ if (!tree.exists(tsConfigPath)) {
31
+ writeJson(tree, tsConfigPath, {
32
+ extends: joinPathFragments(getRelativePathToRootByDirectory(project.root), 'tsconfig.base.json'),
33
+ compilerOptions: {
34
+ composite: false,
35
+ declarationMap: false,
36
+ emitDeclarationOnly: false,
37
+ noEmit: true,
38
+ types: [
39
+ 'node',
40
+ ...types
41
+ ]
42
+ },
43
+ include: [
44
+ '**/*.ts'
45
+ ]
46
+ });
47
+ }
48
+ project.targets ??= {};
49
+ project.targets = sortObjectKeys({
50
+ ...project.targets,
51
+ ...biomeTargets(tree),
52
+ typecheck: normalizeTargetKeyOrder({
53
+ executor: 'nx:run-commands',
54
+ cache: true,
55
+ inputs: [
56
+ 'default',
57
+ '^default'
58
+ ],
59
+ options: {
60
+ command: `tsc --noEmit -p ${SCRIPT_TSCONFIG_FILE_NAME}`,
61
+ cwd: '{projectRoot}'
62
+ }
63
+ }),
64
+ build: normalizeTargetKeyOrder({
65
+ ...project.targets.build,
66
+ dependsOn: [
67
+ 'lint',
68
+ 'typecheck'
69
+ ]
70
+ })
71
+ });
72
+ registerBiomeNamedInput(tree);
73
+ };
74
+
75
+ //# sourceMappingURL=script-project-targets.js.map