@aws/nx-plugin 1.0.0-rc.57 → 1.0.0-rc.59

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 (223) hide show
  1. package/LICENSE-THIRD-PARTY +2917 -1295
  2. package/generators.json +17 -1
  3. package/migrations.json +36 -26
  4. package/package.json +13 -13
  5. package/src/agentcore-gateway/__snapshots__/generator.spec.ts.snap +273 -0
  6. package/src/agentcore-gateway/agent-connection/generator.d.ts +19 -0
  7. package/src/agentcore-gateway/agent-connection/generator.js +90 -0
  8. package/src/agentcore-gateway/agent-connection/generator.js.map +1 -0
  9. package/src/agentcore-gateway/agent-connection/schema.d.js +6 -0
  10. package/src/agentcore-gateway/agent-connection/schema.d.js.map +1 -0
  11. package/src/agentcore-gateway/agent-connection/schema.d.ts +13 -0
  12. package/src/agentcore-gateway/agent-connection/schema.json +31 -0
  13. package/src/agentcore-gateway/attach-upstream.d.ts +16 -0
  14. package/src/agentcore-gateway/attach-upstream.js +32 -11
  15. package/src/agentcore-gateway/attach-upstream.js.map +1 -1
  16. package/src/agentcore-gateway/files/project/http/local-dev.ts.template +77 -0
  17. package/src/agentcore-gateway/generator.d.ts +17 -1
  18. package/src/agentcore-gateway/generator.js +25 -12
  19. package/src/agentcore-gateway/generator.js.map +1 -1
  20. package/src/agentcore-gateway/react-connection/__snapshots__/generator.spec.ts.snap +68 -0
  21. package/src/agentcore-gateway/react-connection/generator.d.ts +19 -0
  22. package/src/agentcore-gateway/react-connection/generator.js +119 -0
  23. package/src/agentcore-gateway/react-connection/generator.js.map +1 -0
  24. package/src/agentcore-gateway/react-connection/schema.d.js +6 -0
  25. package/src/agentcore-gateway/react-connection/schema.d.js.map +1 -0
  26. package/src/agentcore-gateway/react-connection/schema.d.ts +13 -0
  27. package/src/agentcore-gateway/react-connection/schema.json +31 -0
  28. package/src/agentcore-gateway/schema.d.js.map +1 -1
  29. package/src/agentcore-gateway/schema.d.ts +1 -1
  30. package/src/agentcore-gateway/schema.json +3 -2
  31. package/src/connection/agent-local-dev.d.ts +16 -0
  32. package/src/connection/agent-local-dev.js +44 -2
  33. package/src/connection/agent-local-dev.js.map +1 -1
  34. package/src/connection/gateway-runtime-config.d.ts +19 -0
  35. package/src/connection/gateway-runtime-config.js +47 -0
  36. package/src/connection/gateway-runtime-config.js.map +1 -0
  37. package/src/connection/generator.js +5 -0
  38. package/src/connection/generator.js.map +1 -1
  39. package/src/connection/scaffold-catalog.d.ts +267 -0
  40. package/src/connection/scaffold-catalog.js +347 -0
  41. package/src/connection/scaffold-catalog.js.map +1 -0
  42. package/src/connection/schema-resolver.d.ts +5 -0
  43. package/src/connection/schema-resolver.js +27 -0
  44. package/src/connection/schema-resolver.js.map +1 -0
  45. package/src/connection/supported-connections.d.ts +9 -0
  46. package/src/connection/supported-connections.js +12 -0
  47. package/src/connection/supported-connections.js.map +1 -1
  48. package/src/infra/app/__snapshots__/generator.spec.ts.snap +7 -7
  49. package/src/internal/test-matrix/generator.js +39 -1
  50. package/src/internal/test-matrix/generator.js.map +1 -1
  51. package/src/migrations/latest/gateway-agent-targets/__snapshots__/migration.spec.ts.snap +223 -0
  52. package/src/migrations/latest/gateway-agent-targets/metadata.json +3 -0
  53. package/src/migrations/latest/gateway-agent-targets/migration.js +217 -0
  54. package/src/migrations/latest/gateway-agent-targets/migration.js.map +1 -0
  55. package/src/migrations/latest/smithy-ssdk-bundle-pins/metadata.json +3 -0
  56. package/src/migrations/latest/smithy-ssdk-bundle-pins/migration.js +78 -0
  57. package/src/migrations/latest/smithy-ssdk-bundle-pins/migration.js.map +1 -0
  58. package/src/migrations/v1.0.0-rc.50/modernize-function-props-cast/metadata.json +3 -0
  59. package/src/migrations/v1.0.0-rc.50/modernize-function-props-cast/migration.js.map +1 -0
  60. package/src/migrations/v1.0.0-rc.50/restrict-cors-to-custom-domains/metadata.json +3 -0
  61. package/src/migrations/v1.0.0-rc.50/restrict-cors-to-custom-domains/migration.js.map +1 -0
  62. package/src/migrations/v1.0.0-rc.50/terraform-bootstrap-adopt-existing-bucket/metadata.json +3 -0
  63. package/src/migrations/v1.0.0-rc.50/terraform-bootstrap-adopt-existing-bucket/migration.js.map +1 -0
  64. package/src/migrations/v1.0.0-rc.52/user-identity-waf-allow-localhost-callback/metadata.json +3 -0
  65. package/src/migrations/v1.0.0-rc.52/user-identity-waf-allow-localhost-callback/migration.js.map +1 -0
  66. package/src/migrations/v1.0.0-rc.54/order-access-log-delivery-after-bucket-policy/metadata.json +3 -0
  67. package/src/migrations/v1.0.0-rc.54/order-access-log-delivery-after-bucket-policy/migration.js.map +1 -0
  68. package/src/migrations/v1.0.0-rc.55/backfill-generator-metadata/metadata.json +3 -0
  69. package/src/migrations/v1.0.0-rc.55/backfill-generator-metadata/migration.js.map +1 -0
  70. package/src/migrations/v1.0.0-rc.56/dynamodb-local-remove-optimize-flag/metadata.json +3 -0
  71. package/src/migrations/v1.0.0-rc.56/dynamodb-local-remove-optimize-flag/migration.d.ts +6 -0
  72. package/src/migrations/v1.0.0-rc.56/dynamodb-local-remove-optimize-flag/migration.js.map +1 -0
  73. package/src/migrations/v1.0.0-rc.57/ts-agent-session-management-support/metadata.json +3 -0
  74. package/src/migrations/v1.0.0-rc.57/ts-agent-session-management-support/migration.d.ts +6 -0
  75. package/src/migrations/v1.0.0-rc.57/ts-agent-session-management-support/migration.js.map +1 -0
  76. package/src/preset/__snapshots__/generator.spec.ts.snap +5 -5
  77. package/src/py/agent/__snapshots__/generator.constructs.spec.ts.snap +10 -8
  78. package/src/py/agent/__snapshots__/generator.frameworks.spec.ts.snap +8 -8
  79. package/src/py/agent/__snapshots__/generator.protocols.spec.ts.snap +2 -2
  80. package/src/py/agent/a2a-connection/generator.d.ts +1 -1
  81. package/src/py/agent/gateway-connection/generator.d.ts +1 -1
  82. package/src/py/agent/mcp-connection/generator.d.ts +1 -1
  83. package/src/py/agent/react-connection/generator.d.ts +4 -1
  84. package/src/py/agent/react-connection/generator.js +35 -14
  85. package/src/py/agent/react-connection/generator.js.map +1 -1
  86. package/src/py/agent/schema.json +1 -0
  87. package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +2 -2
  88. package/src/py/dynamodb/schema.json +1 -0
  89. package/src/py/fast-api/__snapshots__/generator.terraform.spec.ts.snap +12 -12
  90. package/src/py/fast-api/generator.d.ts +5 -0
  91. package/src/py/fast-api/generator.js +3 -2
  92. package/src/py/fast-api/generator.js.map +1 -1
  93. package/src/py/fast-api/schema.json +1 -0
  94. package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
  95. package/src/py/mcp-server/__snapshots__/generator.spec.ts.snap +5 -5
  96. package/src/py/mcp-server/schema.json +1 -0
  97. package/src/py/rdb/__snapshots__/generator.spec.ts.snap +2 -2
  98. package/src/py/rdb/schema.json +1 -0
  99. package/src/smithy/project/__snapshots__/generator.spec.ts.snap +4 -4
  100. package/src/smithy/project/files/service/build.Dockerfile.template +2 -2
  101. package/src/smithy/project/generator.d.ts +25 -0
  102. package/src/smithy/project/generator.js +24 -3
  103. package/src/smithy/project/generator.js.map +1 -1
  104. package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +7 -7
  105. package/src/smithy/ts/api/generator.d.ts +6 -1
  106. package/src/smithy/ts/api/generator.js +3 -2
  107. package/src/smithy/ts/api/generator.js.map +1 -1
  108. package/src/smithy/ts/api/schema.json +1 -0
  109. package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +12 -12
  110. package/src/trpc/backend/generator.d.ts +6 -1
  111. package/src/trpc/backend/generator.js +3 -2
  112. package/src/trpc/backend/generator.js.map +1 -1
  113. package/src/trpc/backend/schema.json +1 -0
  114. package/src/ts/agent/__snapshots__/generator.spec.ts.snap +9 -5
  115. package/src/ts/agent/generator.d.ts +32 -1
  116. package/src/ts/agent/generator.js +7 -4
  117. package/src/ts/agent/generator.js.map +1 -1
  118. package/src/ts/agent/react-connection/generator.d.ts +16 -1
  119. package/src/ts/agent/react-connection/generator.js +21 -8
  120. package/src/ts/agent/react-connection/generator.js.map +1 -1
  121. package/src/ts/agent/schema.json +1 -0
  122. package/src/ts/dcr-proxy/__snapshots__/generator.spec.ts.snap +1 -1
  123. package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +2 -2
  124. package/src/ts/dynamodb/schema.json +1 -0
  125. package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
  126. package/src/ts/mcp-server/__snapshots__/generator.spec.ts.snap +2 -2
  127. package/src/ts/mcp-server/generator.d.ts +32 -1
  128. package/src/ts/mcp-server/generator.js +7 -4
  129. package/src/ts/mcp-server/generator.js.map +1 -1
  130. package/src/ts/mcp-server/schema.json +1 -0
  131. package/src/ts/nx-migration/generator.js +40 -27
  132. package/src/ts/nx-migration/generator.js.map +1 -1
  133. package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +6 -6
  134. package/src/ts/rdb/generator.d.ts +8 -0
  135. package/src/ts/rdb/generator.js +3 -2
  136. package/src/ts/rdb/generator.js.map +1 -1
  137. package/src/ts/rdb/schema.json +1 -0
  138. package/src/ts/react-website/agui/files/common/src/hooks/useAgui__agentNameClassName__.tsx.template +16 -0
  139. package/src/ts/react-website/agui/generator.d.ts +11 -0
  140. package/src/ts/react-website/agui/generator.js +11 -7
  141. package/src/ts/react-website/agui/generator.js.map +1 -1
  142. package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +61 -45
  143. package/src/ts/react-website/app/generator.d.ts +6 -1
  144. package/src/ts/react-website/app/generator.js +3 -2
  145. package/src/ts/react-website/app/generator.js.map +1 -1
  146. package/src/ts/react-website/app/schema.json +1 -0
  147. package/src/ts/react-website/cognito-auth/__snapshots__/generator.terraform.spec.ts.snap +2 -2
  148. package/src/ts/react-website/cognito-auth/generator.d.ts +6 -1
  149. package/src/ts/react-website/cognito-auth/generator.js +3 -2
  150. package/src/ts/react-website/cognito-auth/generator.js.map +1 -1
  151. package/src/utils/agent-core-constructs/agent-core-constructs.d.ts +23 -0
  152. package/src/utils/agent-core-constructs/agent-core-constructs.js +24 -1
  153. package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
  154. package/src/utils/agent-core-constructs/files/cdk/app/agent-core/__nameKebabCase__/__nameKebabCase__.ts.template +3 -0
  155. package/src/utils/agent-core-constructs/files/cdk/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.ts.template +6 -4
  156. package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +119 -3
  157. package/src/utils/agent-core-constructs/files/terraform/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.tf.template +17 -0
  158. package/src/utils/api-constructs/api-constructs.d.ts +9 -0
  159. package/src/utils/api-constructs/api-constructs.js +11 -1
  160. package/src/utils/api-constructs/api-constructs.js.map +1 -1
  161. package/src/utils/config/utils.d.ts +5 -0
  162. package/src/utils/config/utils.js +7 -1
  163. package/src/utils/config/utils.js.map +1 -1
  164. package/src/utils/connection/open-api/files/components/__apiNameClassName__Provider.tsx.template +13 -2
  165. package/src/utils/connection/open-api/react.d.ts +10 -1
  166. package/src/utils/connection/open-api/react.js +3 -2
  167. package/src/utils/connection/open-api/react.js.map +1 -1
  168. package/src/utils/docker.d.ts +27 -2
  169. package/src/utils/docker.js +31 -2
  170. package/src/utils/docker.js.map +1 -1
  171. package/src/utils/identity-constructs/identity-constructs.d.ts +10 -0
  172. package/src/utils/identity-constructs/identity-constructs.js +11 -1
  173. package/src/utils/identity-constructs/identity-constructs.js.map +1 -1
  174. package/src/utils/migration-manifest.d.ts +58 -0
  175. package/src/utils/migration-manifest.js +76 -0
  176. package/src/utils/migration-manifest.js.map +1 -0
  177. package/src/utils/migration-versions.d.ts +2 -0
  178. package/src/utils/migration-versions.js.map +1 -1
  179. package/src/utils/shared-constructs-constants.d.ts +6 -0
  180. package/src/utils/shared-constructs-constants.js +5 -0
  181. package/src/utils/shared-constructs-constants.js.map +1 -1
  182. package/src/utils/version-upgrade-migration/owned-dependencies.d.ts +26 -0
  183. package/src/utils/version-upgrade-migration/owned-dependencies.js +52 -4
  184. package/src/utils/version-upgrade-migration/owned-dependencies.js.map +1 -1
  185. package/src/utils/version-upgrade-migration/register.d.ts +9 -3
  186. package/src/utils/version-upgrade-migration/register.js +18 -14
  187. package/src/utils/version-upgrade-migration/register.js.map +1 -1
  188. package/src/utils/version-upgrade-migration/sync-embedded-versions.d.ts +26 -0
  189. package/src/utils/version-upgrade-migration/sync-embedded-versions.js +304 -0
  190. package/src/utils/version-upgrade-migration/sync-embedded-versions.js.map +1 -0
  191. package/src/utils/version-upgrade-migration/sync-vended-versions.js +14 -0
  192. package/src/utils/version-upgrade-migration/sync-vended-versions.js.map +1 -1
  193. package/src/utils/versions.d.ts +90 -77
  194. package/src/utils/versions.js +86 -75
  195. package/src/utils/versions.js.map +1 -1
  196. package/src/utils/website-constructs/website-constructs.d.ts +11 -0
  197. package/src/utils/website-constructs/website-constructs.js +12 -1
  198. package/src/utils/website-constructs/website-constructs.js.map +1 -1
  199. package/src/migrations/latest/backfill-generator-metadata/migration.js.map +0 -1
  200. package/src/migrations/latest/dynamodb-local-remove-optimize-flag/migration.js.map +0 -1
  201. package/src/migrations/latest/modernize-function-props-cast/migration.js.map +0 -1
  202. package/src/migrations/latest/order-access-log-delivery-after-bucket-policy/migration.js.map +0 -1
  203. package/src/migrations/latest/restrict-cors-to-custom-domains/migration.js.map +0 -1
  204. package/src/migrations/latest/terraform-bootstrap-adopt-existing-bucket/migration.js.map +0 -1
  205. package/src/migrations/latest/ts-agent-session-management-support/migration.js.map +0 -1
  206. package/src/migrations/latest/user-identity-waf-allow-localhost-callback/migration.js.map +0 -1
  207. /package/src/agentcore-gateway/files/project/{local-dev.ts.template → mcp/local-dev.ts.template} +0 -0
  208. /package/src/migrations/latest/{dynamodb-local-remove-optimize-flag → gateway-agent-targets}/migration.d.ts +0 -0
  209. /package/src/migrations/latest/{modernize-function-props-cast → smithy-ssdk-bundle-pins}/migration.d.ts +0 -0
  210. /package/src/migrations/{latest/restrict-cors-to-custom-domains → v1.0.0-rc.50/modernize-function-props-cast}/migration.d.ts +0 -0
  211. /package/src/migrations/{latest → v1.0.0-rc.50}/modernize-function-props-cast/migration.js +0 -0
  212. /package/src/migrations/{latest/terraform-bootstrap-adopt-existing-bucket → v1.0.0-rc.50/restrict-cors-to-custom-domains}/migration.d.ts +0 -0
  213. /package/src/migrations/{latest → v1.0.0-rc.50}/restrict-cors-to-custom-domains/migration.js +0 -0
  214. /package/src/migrations/{latest/ts-agent-session-management-support → v1.0.0-rc.50/terraform-bootstrap-adopt-existing-bucket}/migration.d.ts +0 -0
  215. /package/src/migrations/{latest → v1.0.0-rc.50}/terraform-bootstrap-adopt-existing-bucket/migration.js +0 -0
  216. /package/src/migrations/{latest/order-access-log-delivery-after-bucket-policy → v1.0.0-rc.52/user-identity-waf-allow-localhost-callback}/migration.d.ts +0 -0
  217. /package/src/migrations/{latest → v1.0.0-rc.52}/user-identity-waf-allow-localhost-callback/migration.js +0 -0
  218. /package/src/migrations/{latest/user-identity-waf-allow-localhost-callback → v1.0.0-rc.54/order-access-log-delivery-after-bucket-policy}/migration.d.ts +0 -0
  219. /package/src/migrations/{latest → v1.0.0-rc.54}/order-access-log-delivery-after-bucket-policy/migration.js +0 -0
  220. /package/src/migrations/{latest → v1.0.0-rc.55}/backfill-generator-metadata/migration.d.ts +0 -0
  221. /package/src/migrations/{latest → v1.0.0-rc.55}/backfill-generator-metadata/migration.js +0 -0
  222. /package/src/migrations/{latest → v1.0.0-rc.56}/dynamodb-local-remove-optimize-flag/migration.js +0 -0
  223. /package/src/migrations/{latest → v1.0.0-rc.57}/ts-agent-session-management-support/migration.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/config/utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { generateFiles, joinPathFragments, type Tree } from '@nx/devkit';\nimport { existsSync, readFileSync } from 'fs';\nimport { createJiti } from 'jiti';\nimport { join } from 'path';\nimport { applyGritQL, matchGritQL } from '../ast';\nimport { formatFilesInSubtree } from '../format';\nimport type { AwsNxPluginConfig } from '.';\n\nexport const AWS_NX_PLUGIN_CONFIG_FILE_NAME = 'aws-nx-plugin.config.mts';\n\n/**\n * Aliases used by jiti to resolve `@aws/nx-plugin` imports in the config file\n * to this package's source, so the config can be evaluated in-memory.\n */\nconst AWS_NX_PLUGIN_JITI_ALIASES = {\n '@aws/nx-plugin/sdk/license': join(\n import.meta.dirname,\n '..',\n '..',\n 'sdk',\n 'license',\n ),\n '@aws/nx-plugin': join(import.meta.dirname, '..', '..'),\n};\n\n/**\n * Ensure that the config file exists\n */\nexport const ensureAwsNxPluginConfig = async (\n tree: Tree,\n): Promise<AwsNxPluginConfig> => {\n if (!tree.exists(AWS_NX_PLUGIN_CONFIG_FILE_NAME)) {\n // Create an empty config file if it doesn't already exist\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n '.',\n {},\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return readAwsNxPluginConfig(tree)!;\n};\n\n/**\n * Read config from the aws nx plugin configuration file.\n *\n * Uses jiti to evaluate the TypeScript source in-memory with proper module\n * resolution — imports from @aws/nx-plugin/* resolve via alias, and any\n * third-party imports resolve from the workspace's node_modules. Synchronous,\n * since `jiti.evalModule` runs in-memory.\n */\nexport const readAwsNxPluginConfig = (\n tree: Tree,\n): AwsNxPluginConfig | undefined => {\n if (!tree.exists(AWS_NX_PLUGIN_CONFIG_FILE_NAME)) {\n return undefined;\n }\n const source = tree.read(AWS_NX_PLUGIN_CONFIG_FILE_NAME, 'utf-8')!;\n const configFilePath = join(tree.root, AWS_NX_PLUGIN_CONFIG_FILE_NAME);\n\n const jiti = createJiti(import.meta.filename, {\n alias: AWS_NX_PLUGIN_JITI_ALIASES,\n });\n\n const mod = jiti.evalModule(source, { filename: configFilePath });\n return (mod as any).default ?? mod;\n};\n\n/**\n * Read config directly from disk. Used by executors that run in the real\n * workspace (not a virtual Tree). Resolves all imports — including\n * third-party dependencies — from the workspace's node_modules.\n */\nexport const readAwsNxPluginConfigFromDisk = (\n workspaceRoot: string,\n): AwsNxPluginConfig | undefined => {\n const configPath = join(workspaceRoot, AWS_NX_PLUGIN_CONFIG_FILE_NAME);\n if (!existsSync(configPath)) return undefined;\n\n const source = readFileSync(configPath, 'utf-8');\n\n const jiti = createJiti(import.meta.filename, {\n alias: AWS_NX_PLUGIN_JITI_ALIASES,\n });\n const mod = jiti.evalModule(source, { filename: configPath });\n return (mod as any).default ?? mod;\n};\n\nconst PLACEHOLDER = '\"__PLACEHOLDER__\"';\n\n/**\n * Use GritQL to set a top-level property in the export default object,\n * then substitute the placeholder with the JSON-serialized value.\n * Preserves all other properties (including JS expressions) untouched.\n */\nconst setConfigProperty = async (\n tree: Tree,\n filePath: string,\n key: string,\n value: unknown,\n): Promise<void> => {\n const json = JSON.stringify(value);\n\n // Check if the property already exists using a named metavariable\n // to avoid ambiguity with anonymous $_ in nested where clauses\n const existsInSatisfies = await matchGritQL(\n tree,\n filePath,\n `\\`${key}: $val\\` where { $val <: within \\`export default $_ satisfies $_\\` }`,\n );\n const existsInPlain =\n !existsInSatisfies &&\n (await matchGritQL(\n tree,\n filePath,\n `\\`${key}: $val\\` where { $val <: within \\`export default $_\\` }`,\n ));\n\n if (existsInSatisfies || existsInPlain) {\n // Replace only this property's value, scoped to the export default\n const within = existsInSatisfies\n ? `within \\`export default $_ satisfies $_\\``\n : `within \\`export default $_\\``;\n await applyGritQL(\n tree,\n filePath,\n `\\`${key}: $old\\` => \\`${key}: ${PLACEHOLDER}\\` where { $old <: ${within} }`,\n );\n } else {\n // Add the new property using GritQL's += (accumulate) operator.\n // For non-empty objects, += appends correctly without double commas.\n // For empty objects, += fails so we fall back to a direct replacement.\n let added = await applyGritQL(\n tree,\n filePath,\n `\\`export default { $props } satisfies $type\\` where { $props += \\`, ${key}: ${PLACEHOLDER}\\` }`,\n );\n\n if (!added) {\n added = await applyGritQL(\n tree,\n filePath,\n `\\`export default { } satisfies $type\\` => \\`export default { ${key}: ${PLACEHOLDER} } satisfies $type\\``,\n );\n }\n\n if (!added) {\n added = await applyGritQL(\n tree,\n filePath,\n `\\`export default { $props }\\` where { $props += \\`, ${key}: ${PLACEHOLDER}\\` }`,\n );\n }\n\n if (!added) {\n await applyGritQL(\n tree,\n filePath,\n `\\`export default { }\\` => \\`export default { ${key}: ${PLACEHOLDER} }\\``,\n );\n }\n }\n\n // Substitute the placeholder with the actual JSON value\n const content = tree.read(filePath)!.toString();\n tree.write(filePath, content.replace(PLACEHOLDER, json));\n};\n\n/**\n * Update the aws nx plugin config file.\n * Only the specified top-level keys are replaced; all other properties\n * (including those containing JS expressions) are left untouched in source.\n */\nexport const updateAwsNxPluginConfig = async (\n tree: Tree,\n configUpdate: Partial<AwsNxPluginConfig>,\n): Promise<void> => {\n const filePath = AWS_NX_PLUGIN_CONFIG_FILE_NAME;\n\n for (const [key, value] of Object.entries(configUpdate)) {\n await setConfigProperty(tree, filePath, key, value);\n }\n\n // Prettier formats the result into properly indented TypeScript\n await formatFilesInSubtree(tree, filePath);\n};\n"],"names":["generateFiles","joinPathFragments","existsSync","readFileSync","createJiti","join","applyGritQL","matchGritQL","formatFilesInSubtree","AWS_NX_PLUGIN_CONFIG_FILE_NAME","AWS_NX_PLUGIN_JITI_ALIASES","dirname","ensureAwsNxPluginConfig","tree","exists","readAwsNxPluginConfig","undefined","source","read","configFilePath","root","jiti","filename","alias","mod","evalModule","default","readAwsNxPluginConfigFromDisk","workspaceRoot","configPath","PLACEHOLDER","setConfigProperty","filePath","key","value","json","JSON","stringify","existsInSatisfies","existsInPlain","within","added","content","toString","write","replace","updateAwsNxPluginConfig","configUpdate","Object","entries"],"mappings":"AAAA;;;CAGC,GACD,SAASA,aAAa,EAAEC,iBAAiB,QAAmB,aAAa;AACzE,SAASC,UAAU,EAAEC,YAAY,QAAQ,KAAK;AAC9C,SAASC,UAAU,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AAU7B,KAAKK,IAAI,CAACc,UAAWW,QAAQ;IAC7C9B,KAAK+B,KAAK,CAACZ,UAAUU,QAAQG,OAAO,CAACf,aAAaK;AACpD;AAEA;;;;CAIC,GACD,OAAO,MAAMW,0BAA0B,OACrCjC,MACAkC;IAEA,MAAMf,WAAWvB;IAEjB,KAAK,MAAM,CAACwB,KAAKC,MAAM,IAAIc,OAAOC,OAAO,CAACF,cAAe;QACvD,MAAMhB,kBAAkBlB,MAAMmB,UAAUC,KAAKC;IAC/C;IAEA,gEAAgE;IAChE,MAAM1B,qBAAqBK,MAAMmB;AACnC,EAAE"}
1
+ {"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/config/utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { generateFiles, joinPathFragments, type Tree } from '@nx/devkit';\nimport { existsSync, readFileSync } from 'fs';\nimport { createJiti } from 'jiti';\nimport { join } from 'path';\nimport { applyGritQL, matchGritQL } from '../ast';\nimport { formatFilesInSubtree } from '../format';\nimport type { AwsNxPluginConfig } from '.';\n\nexport const AWS_NX_PLUGIN_CONFIG_FILE_NAME = 'aws-nx-plugin.config.mts';\n\n/**\n * Aliases used by jiti to resolve `@aws/nx-plugin` imports in the config file\n * to this package's source, so the config can be evaluated in-memory.\n */\nconst AWS_NX_PLUGIN_JITI_ALIASES = {\n '@aws/nx-plugin/sdk/license': join(\n import.meta.dirname,\n '..',\n '..',\n 'sdk',\n 'license',\n ),\n '@aws/nx-plugin': join(import.meta.dirname, '..', '..'),\n};\n\n/**\n * Ensure that the config file exists\n */\nexport const ensureAwsNxPluginConfig = async (\n tree: Tree,\n): Promise<AwsNxPluginConfig> => {\n if (!tree.exists(AWS_NX_PLUGIN_CONFIG_FILE_NAME)) {\n // Create an empty config file if it doesn't already exist\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n '.',\n {},\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return readAwsNxPluginConfig(tree)!;\n};\n\n/**\n * Read config from the aws nx plugin configuration file.\n *\n * Uses jiti to evaluate the TypeScript source in-memory with proper module\n * resolution — imports from @aws/nx-plugin/* resolve via alias, and any\n * third-party imports resolve from the workspace's node_modules. Synchronous,\n * since `jiti.evalModule` runs in-memory.\n *\n * The on-disk transform cache is off: jiti keys it by file path, but the source\n * here comes from the Tree, so one path holds different content as generators\n * mutate the config — and every test Tree shares the `/virtual` root, making\n * concurrent workers collide on a single cache file.\n */\nexport const readAwsNxPluginConfig = (\n tree: Tree,\n): AwsNxPluginConfig | undefined => {\n if (!tree.exists(AWS_NX_PLUGIN_CONFIG_FILE_NAME)) {\n return undefined;\n }\n const source = tree.read(AWS_NX_PLUGIN_CONFIG_FILE_NAME, 'utf-8')!;\n const configFilePath = join(tree.root, AWS_NX_PLUGIN_CONFIG_FILE_NAME);\n\n const jiti = createJiti(import.meta.filename, {\n alias: AWS_NX_PLUGIN_JITI_ALIASES,\n fsCache: false,\n });\n\n const mod = jiti.evalModule(source, { filename: configFilePath });\n return (mod as any).default ?? mod;\n};\n\n/**\n * Read config directly from disk. Used by executors that run in the real\n * workspace (not a virtual Tree). Resolves all imports — including\n * third-party dependencies — from the workspace's node_modules.\n */\nexport const readAwsNxPluginConfigFromDisk = (\n workspaceRoot: string,\n): AwsNxPluginConfig | undefined => {\n const configPath = join(workspaceRoot, AWS_NX_PLUGIN_CONFIG_FILE_NAME);\n if (!existsSync(configPath)) return undefined;\n\n const source = readFileSync(configPath, 'utf-8');\n\n const jiti = createJiti(import.meta.filename, {\n alias: AWS_NX_PLUGIN_JITI_ALIASES,\n });\n const mod = jiti.evalModule(source, { filename: configPath });\n return (mod as any).default ?? mod;\n};\n\nconst PLACEHOLDER = '\"__PLACEHOLDER__\"';\n\n/**\n * Use GritQL to set a top-level property in the export default object,\n * then substitute the placeholder with the JSON-serialized value.\n * Preserves all other properties (including JS expressions) untouched.\n */\nconst setConfigProperty = async (\n tree: Tree,\n filePath: string,\n key: string,\n value: unknown,\n): Promise<void> => {\n const json = JSON.stringify(value);\n\n // Check if the property already exists using a named metavariable\n // to avoid ambiguity with anonymous $_ in nested where clauses\n const existsInSatisfies = await matchGritQL(\n tree,\n filePath,\n `\\`${key}: $val\\` where { $val <: within \\`export default $_ satisfies $_\\` }`,\n );\n const existsInPlain =\n !existsInSatisfies &&\n (await matchGritQL(\n tree,\n filePath,\n `\\`${key}: $val\\` where { $val <: within \\`export default $_\\` }`,\n ));\n\n if (existsInSatisfies || existsInPlain) {\n // Replace only this property's value, scoped to the export default\n const within = existsInSatisfies\n ? `within \\`export default $_ satisfies $_\\``\n : `within \\`export default $_\\``;\n await applyGritQL(\n tree,\n filePath,\n `\\`${key}: $old\\` => \\`${key}: ${PLACEHOLDER}\\` where { $old <: ${within} }`,\n );\n } else {\n // Add the new property using GritQL's += (accumulate) operator.\n // For non-empty objects, += appends correctly without double commas.\n // For empty objects, += fails so we fall back to a direct replacement.\n let added = await applyGritQL(\n tree,\n filePath,\n `\\`export default { $props } satisfies $type\\` where { $props += \\`, ${key}: ${PLACEHOLDER}\\` }`,\n );\n\n if (!added) {\n added = await applyGritQL(\n tree,\n filePath,\n `\\`export default { } satisfies $type\\` => \\`export default { ${key}: ${PLACEHOLDER} } satisfies $type\\``,\n );\n }\n\n if (!added) {\n added = await applyGritQL(\n tree,\n filePath,\n `\\`export default { $props }\\` where { $props += \\`, ${key}: ${PLACEHOLDER}\\` }`,\n );\n }\n\n if (!added) {\n await applyGritQL(\n tree,\n filePath,\n `\\`export default { }\\` => \\`export default { ${key}: ${PLACEHOLDER} }\\``,\n );\n }\n }\n\n // Substitute the placeholder with the actual JSON value\n const content = tree.read(filePath)!.toString();\n tree.write(filePath, content.replace(PLACEHOLDER, json));\n};\n\n/**\n * Update the aws nx plugin config file.\n * Only the specified top-level keys are replaced; all other properties\n * (including those containing JS expressions) are left untouched in source.\n */\nexport const updateAwsNxPluginConfig = async (\n tree: Tree,\n configUpdate: Partial<AwsNxPluginConfig>,\n): Promise<void> => {\n const filePath = AWS_NX_PLUGIN_CONFIG_FILE_NAME;\n\n for (const [key, value] of Object.entries(configUpdate)) {\n await setConfigProperty(tree, filePath, key, value);\n }\n\n // Prettier formats the result into properly indented TypeScript\n await formatFilesInSubtree(tree, filePath);\n};\n"],"names":["generateFiles","joinPathFragments","existsSync","readFileSync","createJiti","join","applyGritQL","matchGritQL","formatFilesInSubtree","AWS_NX_PLUGIN_CONFIG_FILE_NAME","AWS_NX_PLUGIN_JITI_ALIASES","dirname","ensureAwsNxPluginConfig","tree","exists","readAwsNxPluginConfig","undefined","source","read","configFilePath","root","jiti","filename","alias","fsCache","mod","evalModule","default","readAwsNxPluginConfigFromDisk","workspaceRoot","configPath","PLACEHOLDER","setConfigProperty","filePath","key","value","json","JSON","stringify","existsInSatisfies","existsInPlain","within","added","content","toString","write","replace","updateAwsNxPluginConfig","configUpdate","Object","entries"],"mappings":"AAAA;;;CAGC,GACD,SAASA,aAAa,EAAEC,iBAAiB,QAAmB,aAAa;AACzE,SAASC,UAAU,EAAEC,YAAY,QAAQ,KAAK;AAC9C,SAASC,UAAU,QAAQ,OAAO;AAClC,SAASC,IAAI,QAAQ,OAAO;AAC5B,SAASC,WAAW,EAAEC,WAAW,QAAQ,YAAS;AAClD,SAASC,oBAAoB,QAAQ,eAAY;AAGjD,OAAO,MAAMC,iCAAiC,2BAA2B;AAEzE;;;CAGC,GACD,MAAMC,6BAA6B;IACjC,8BAA8BL,KAC5B,YAAYM,OAAO,EACnB,MACA,MACA,OACA;IAEF,kBAAkBN,KAAK,YAAYM,OAAO,EAAE,MAAM;AACpD;AAEA;;CAEC,GACD,OAAO,MAAMC,0BAA0B,OACrCC;IAEA,IAAI,CAACA,KAAKC,MAAM,CAACL,iCAAiC;QAChD,0DAA0D;QAC1DT,cACEa,MACAZ,kBAAkB,YAAYU,OAAO,EAAE,UACvC,KACA,CAAC;IAEL;IACA,oEAAoE;IACpE,OA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CAAC,GAC3C,CAAC,4BAA4B,CAAC;QAClC,MAAMjC,YACJO,MACAoB,UACA,CAAC,EAAE,EAAEC,IAAI,cAAc,EAAEA,IAAI,EAAE,EAAEH,YAAY,mBAAmB,EAAEU,OAAO,EAAE,CAAC;IAEhF,OAAO;QACL,gEAAgE;QAChE,qEAAqE;QACrE,uEAAuE;QACvE,IAAIC,QAAQ,MAAMpC,YAChBO,MACAoB,UACA,CAAC,oEAAoE,EAAEC,IAAI,EAAE,EAAEH,YAAY,IAAI,CAAC;QAGlG,IAAI,CAACW,OAAO;YACVA,QAAQ,MAAMpC,YACZO,MACAoB,UACA,CAAC,6DAA6D,EAAEC,IAAI,EAAE,EAAEH,YAAY,oBAAoB,CAAC;QAE7G;QAEA,IAAI,CAACW,OAAO;YACVA,QAAQ,MAAMpC,YACZO,MACAoB,UACA,CAAC,oDAAoD,EAAEC,IAAI,EAAE,EAAEH,YAAY,IAAI,CAAC;QAEpF;QAEA,IAAI,CAACW,OAAO;YACV,MAAMpC,YACJO,MACAoB,UACA,CAAC,6CAA6C,EAAEC,IAAI,EAAE,EAAEH,YAAY,IAAI,CAAC;QAE7E;IACF;IAEA,wDAAwD;IACxD,MAAMY,UAAU9B,KAAKK,IAAI,CAACe,UAAWW,QAAQ;IAC7C/B,KAAKgC,KAAK,CAACZ,UAAUU,QAAQG,OAAO,CAACf,aAAaK;AACpD;AAEA;;;;CAIC,GACD,OAAO,MAAMW,0BAA0B,OACrClC,MACAmC;IAEA,MAAMf,WAAWxB;IAEjB,KAAK,MAAM,CAACyB,KAAKC,MAAM,IAAIc,OAAOC,OAAO,CAACF,cAAe;QACvD,MAAMhB,kBAAkBnB,MAAMoB,UAAUC,KAAKC;IAC/C;IAEA,gEAAgE;IAChE,MAAM3B,qBAAqBK,MAAMoB;AACnC,EAAE"}
@@ -7,7 +7,16 @@ import { useSigV4 } from '../hooks/useSigV4';
7
7
  <%_ } else if (auth === 'cognito') { _%>
8
8
  import { useAuth } from 'react-oidc-context';
9
9
  <%_ } _%>
10
- <%_ if (isAgentRuntime) { _%>
10
+ <%_ if (gatewayRoute) { _%>
11
+
12
+ /**
13
+ * Build the agent's base URL from its AgentCore Gateway's URL. The gateway
14
+ * proxies `/<targetName>/...` paths to the agent runtime.
15
+ */
16
+ function buildGatewayTargetUrl(gatewayUrl: string): string {
17
+ return `${new URL(gatewayUrl).origin}/<%- gatewayRoute.targetName %>`;
18
+ }
19
+ <%_ } else if (isAgentRuntime) { _%>
11
20
 
12
21
  /**
13
22
  * Build an HTTP URL from a Bedrock AgentCore Runtime ARN
@@ -24,7 +33,9 @@ export const <%- apiNameClassName %>ClientContext = createContext<<%- apiNameCla
24
33
 
25
34
  const useCreate<%- apiNameClassName %>Client = (): <%- apiNameClassName %> => {
26
35
  const runtimeConfig = useRuntimeConfig();
27
- <%_ if (isAgentRuntime) { _%>
36
+ <%_ if (gatewayRoute) { _%>
37
+ const apiUrl = buildGatewayTargetUrl(runtimeConfig.gateways.<%- gatewayRoute.gatewayClassName %>);
38
+ <%_ } else if (isAgentRuntime) { _%>
28
39
  const agentRuntimeValue = runtimeConfig.agentRuntimes.<%- apiNameClassName %>;
29
40
  // A local-dev override is a plain URL; otherwise it's the agent's runtime
30
41
  // ARN, so build the invocation URL from it.
@@ -59,6 +59,15 @@ export interface AddOpenApiReactClientOptions {
59
59
  * When false (default), reads from runtimeConfig.apis directly.
60
60
  */
61
61
  isAgentRuntime?: boolean;
62
+ /**
63
+ * When set, the generated provider reads the gateway's URL from
64
+ * runtimeConfig.gateways and routes to the agent via the gateway's
65
+ * path-based `/<targetName>` route instead of invoking the runtime directly.
66
+ */
67
+ gatewayRoute?: {
68
+ gatewayClassName: string;
69
+ targetName: string;
70
+ };
62
71
  /**
63
72
  * When true, skips the dev target setup. Use this when the caller
64
73
  * handles dev target configuration separately (e.g. agent connections
@@ -69,4 +78,4 @@ export interface AddOpenApiReactClientOptions {
69
78
  /**
70
79
  * Adds an OpenAPI React client to the frontend project along with supporting build targets
71
80
  */
72
- export declare const addOpenApiReactClient: <const D extends DependencyDeclaration>(tree: Tree, { apiName, frontendProjectConfig, backendProjectConfig, specBuildProject, specPath, specBuildTargetName, auth, port, isAgentRuntime, skipLocalDev, }: AddOpenApiReactClientOptions, declaration: D & MustDeclare<typeof OPEN_API_REACT_DEPENDENCIES, D>) => Promise<void>;
81
+ export declare const addOpenApiReactClient: <const D extends DependencyDeclaration>(tree: Tree, { apiName, frontendProjectConfig, backendProjectConfig, specBuildProject, specPath, specBuildTargetName, auth, port, isAgentRuntime, gatewayRoute, skipLocalDev, }: AddOpenApiReactClientOptions, declaration: D & MustDeclare<typeof OPEN_API_REACT_DEPENDENCIES, D>) => Promise<void>;
@@ -36,7 +36,7 @@ import { withVersions } from "../../versions.js";
36
36
  ];
37
37
  /**
38
38
  * Adds an OpenAPI React client to the frontend project along with supporting build targets
39
- */ export const addOpenApiReactClient = async (tree, { apiName, frontendProjectConfig, backendProjectConfig, specBuildProject, specPath, specBuildTargetName, auth, port, isAgentRuntime = false, skipLocalDev = false }, declaration)=>{
39
+ */ export const addOpenApiReactClient = async (tree, { apiName, frontendProjectConfig, backendProjectConfig, specBuildProject, specPath, specBuildTargetName, auth, port, isAgentRuntime = false, gatewayRoute, skipLocalDev = false }, declaration)=>{
40
40
  const clientGenTarget = `generate:${kebabCase(apiName)}-client`;
41
41
  const clientGenWatchTarget = `watch-${clientGenTarget}`;
42
42
  const generatedClientDir = joinPathFragments('generated', kebabCase(apiName));
@@ -120,7 +120,8 @@ import { withVersions } from "../../versions.js";
120
120
  apiName,
121
121
  apiNameClassName,
122
122
  generatedClientDir,
123
- isAgentRuntime
123
+ isAgentRuntime,
124
+ gatewayRoute
124
125
  });
125
126
  // Update main.tsx to add required providers
126
127
  const mainTsxPath = joinPathFragments(frontendProjectConfig.sourceRoot, 'main.tsx');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../packages/nx-plugin/src/utils/connection/open-api/react.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { addTargetToLocalDev } from '../../../connection/local-dev';\nimport runtimeConfigGenerator from '../../../ts/react-website/runtime-config/generator';\nimport { addSingleImport, applyGritQL } from '../../ast';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from '../../declared-dependencies';\nimport { addDependenciesToPackageJson } from '../../dependencies';\nimport { updateGitIgnore } from '../../git';\nimport { kebabCase, toClassName } from '../../names';\nimport { sortObjectKeys } from '../../object';\nimport { type ITsDepVersion, withVersions } from '../../versions';\n\n/** Dependencies a caller must declare to add an OpenAPI React client. */\nexport const OPEN_API_REACT_DEPENDENCIES = [\n { name: 'oidc-client-ts' },\n { name: 'react-oidc-context' },\n { name: '@aws-sdk/credential-provider-cognito-identity' },\n { name: 'aws4fetch' },\n { name: '@tanstack/react-query' },\n { name: '@tanstack/react-query-devtools' },\n { name: '@smithy/types' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\nexport interface AddOpenApiReactClientOptions {\n /**\n * The react project to add the openapi client and build targets to\n */\n frontendProjectConfig: ProjectConfiguration;\n /**\n * The backend project which serves the api\n */\n backendProjectConfig: ProjectConfiguration;\n /**\n * The project which builds/generates the openapi spec\n */\n specBuildProject: ProjectConfiguration;\n /**\n * Name of the api\n */\n apiName: string;\n /**\n * Path to the openapi spec from the workspace root\n */\n specPath: string;\n /**\n * Fully qualified target name for the target that builds/generates the openapi spec\n */\n specBuildTargetName: string;\n /**\n * Authentication method\n */\n auth: 'iam' | 'cognito' | 'custom';\n /**\n * Port on which the backend project's local server listens\n */\n port: number;\n /**\n * When true, the generated provider reads from runtimeConfig.agentRuntimes\n * and converts Bedrock AgentCore Runtime ARNs to HTTP URLs.\n * When false (default), reads from runtimeConfig.apis directly.\n */\n isAgentRuntime?: boolean;\n /**\n * When true, skips the dev target setup. Use this when the caller\n * handles dev target configuration separately (e.g. agent connections\n * that use a component-specific dev target instead of 'serve').\n */\n skipLocalDev?: boolean;\n}\n\n/**\n * Adds an OpenAPI React client to the frontend project along with supporting build targets\n */\nexport const addOpenApiReactClient = async <\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n {\n apiName,\n frontendProjectConfig,\n backendProjectConfig,\n specBuildProject,\n specPath,\n specBuildTargetName,\n auth,\n port,\n isAgentRuntime = false,\n skipLocalDev = false,\n }: AddOpenApiReactClientOptions,\n declaration: D & MustDeclare<typeof OPEN_API_REACT_DEPENDENCIES, D>,\n) => {\n const clientGenTarget = `generate:${kebabCase(apiName)}-client`;\n const clientGenWatchTarget = `watch-${clientGenTarget}`;\n\n const generatedClientDir = joinPathFragments('generated', kebabCase(apiName));\n const generatedClientDirFromRoot = joinPathFragments(\n frontendProjectConfig.sourceRoot,\n generatedClientDir,\n );\n\n // Add TypeScript client generation to Frontend project.json\n updateProjectConfiguration(tree, frontendProjectConfig.name, {\n ...frontendProjectConfig,\n targets: sortObjectKeys({\n ...frontendProjectConfig.targets,\n // Generate should run before compile and bundle as the client is created as part of the website src\n ...Object.fromEntries(\n ['compile', 'bundle'].map((target) => [\n target,\n {\n ...frontendProjectConfig.targets?.[target],\n dependsOn: [\n ...(\n frontendProjectConfig.targets?.[target]?.dependsOn ?? []\n ).filter((t) => t !== clientGenTarget),\n clientGenTarget,\n ],\n },\n ]),\n ),\n [clientGenTarget]: {\n cache: true,\n executor: 'nx:run-commands',\n inputs: [\n {\n dependentTasksOutputFiles: '**/*.json',\n },\n ],\n outputs: [\n joinPathFragments('{workspaceRoot}', generatedClientDirFromRoot),\n ],\n options: {\n commands: [\n `nx g @aws/nx-plugin:open-api#ts-hooks --openApiSpecPath=\"${specPath}\" --outputPath=\"${generatedClientDirFromRoot}\" --no-interactive`,\n ],\n },\n dependsOn: [specBuildTargetName],\n },\n // Watch target for regenerating the client\n [clientGenWatchTarget]: {\n executor: 'nx:run-commands',\n options: {\n commands: [\n `nx watch --projects=${specBuildProject.name} --includeDependencies -- nx run ${frontendProjectConfig.name}:\"${clientGenTarget}\"`,\n ],\n },\n continuous: true,\n },\n }),\n });\n\n const relativeSrcDir = frontendProjectConfig.sourceRoot.slice(\n frontendProjectConfig.root.length + 1,\n );\n\n // Ignore the generated client by default\n // Users can safely remove the entry from the .gitignore if they prefer to check it in\n updateGitIgnore(tree, frontendProjectConfig.root, (patterns) => [\n ...patterns,\n joinPathFragments(relativeSrcDir, generatedClientDir),\n ]);\n\n // Ensure that the frontend has runtime config as we'll use the url for creating the client\n await runtimeConfigGenerator(tree, {\n project: frontendProjectConfig.name,\n });\n\n // Add sigv4 fetch\n if (auth === 'iam') {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, '../../files/website/hooks/sigv4'),\n joinPathFragments(frontendProjectConfig.sourceRoot, 'hooks'),\n {},\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n }\n\n // Generate the tanstack query provider if it does not exist already\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n '../../files/website/components/tanstack-query',\n ),\n joinPathFragments(frontendProjectConfig.sourceRoot, 'components'),\n {},\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n const apiNameClassName = toClassName(apiName);\n\n // Add a hook to instantiate the client\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n frontendProjectConfig.sourceRoot,\n {\n auth,\n apiName,\n apiNameClassName,\n generatedClientDir,\n isAgentRuntime,\n },\n );\n\n // Update main.tsx to add required providers\n const mainTsxPath = joinPathFragments(\n frontendProjectConfig.sourceRoot,\n 'main.tsx',\n );\n\n // Add the query client provider if it doesn't exist already\n await addSingleImport(\n tree,\n mainTsxPath,\n 'QueryClientProvider',\n './components/QueryClientProvider',\n );\n await applyGritQL(\n tree,\n mainTsxPath,\n '`<App />` => `<QueryClientProvider><App /></QueryClientProvider>` where { $program <: not contains `<QueryClientProvider>$_</QueryClientProvider>` }',\n );\n\n // Add the api provider if it does not exist\n const providerName = `${apiNameClassName}Provider`;\n await addSingleImport(\n tree,\n mainTsxPath,\n providerName,\n `./components/${providerName}`,\n );\n await applyGritQL(\n tree,\n mainTsxPath,\n `\\`<App />\\` => \\`<${providerName}><App /></${providerName}>\\` where { $program <: not contains \\`<${providerName}>$_</${providerName}>\\` }`,\n );\n\n // Update the dev target on the website to use our local server.\n // Callers that handle the dev target separately (e.g. agent connections) set skipLocalDev.\n if (!skipLocalDev) {\n await addTargetToLocalDev(\n tree,\n frontendProjectConfig.name,\n backendProjectConfig.name,\n {\n url: `http://localhost:${port}/`,\n apiName,\n // Additionally add a dependency on the generate watch command to ensure that local\n // API changes that affect the client are also reloaded.\n // We include a dependency on the generate target as watch ONLY triggers on a change,\n // and we need to ensure the client is generated the first time if not already present.\n additionalDependencyTargets: [clientGenTarget, clientGenWatchTarget],\n },\n );\n }\n\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof OPEN_API_REACT_DEPENDENCIES>(declaration),\n [\n ...((auth === 'iam'\n ? [\n 'oidc-client-ts',\n 'react-oidc-context',\n '@aws-sdk/credential-provider-cognito-identity',\n 'aws4fetch',\n ]\n : []) as any),\n ...((auth === 'cognito' ? ['react-oidc-context'] : []) as any),\n '@tanstack/react-query',\n '@tanstack/react-query-devtools',\n ],\n ),\n withVersions(\n forDependencies<typeof OPEN_API_REACT_DEPENDENCIES>(declaration),\n ['@smithy/types'],\n ),\n joinPathFragments(frontendProjectConfig.root, 'package.json'),\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","updateProjectConfiguration","addTargetToLocalDev","runtimeConfigGenerator","addSingleImport","applyGritQL","forDependencies","addDependenciesToPackageJson","updateGitIgnore","kebabCase","toClassName","sortObjectKeys","withVersions","OPEN_API_REACT_DEPENDENCIES","name","addOpenApiReactClient","tree","apiName","frontendProjectConfig","backendProjectConfig","specBuildProject","specPath","specBuildTargetName","auth","port","isAgentRuntime","skipLocalDev","declaration","clientGenTarget","clientGenWatchTarget","generatedClientDir","generatedClientDirFromRoot","sourceRoot","targets","Object","fromEntries","map","target","dependsOn","filter","t","cache","executor","inputs","dependentTasksOutputFiles","outputs","options","commands","continuous","relativeSrcDir","slice","root","length","patterns","project","dirname","overwriteStrategy","KeepExisting","apiNameClassName","mainTsxPath","providerName","url","additionalDependencyTargets"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAGjBC,0BAA0B,QACrB,aAAa;AACpB,SAASC,mBAAmB,QAAQ,mCAAgC;AACpE,OAAOC,4BAA4B,wDAAqD;AACxF,SAASC,eAAe,EAAEC,WAAW,QAAQ,eAAY;AACzD,SAEEC,eAAe,QAEV,iCAA8B;AACrC,SAASC,4BAA4B,QAAQ,wBAAqB;AAClE,SAASC,eAAe,QAAQ,eAAY;AAC5C,SAASC,SAAS,EAAEC,WAAW,QAAQ,iBAAc;AACrD,SAASC,cAAc,QAAQ,kBAAe;AAC9C,SAA6BC,YAAY,QAAQ,oBAAiB;AAElE,uEAAuE,GACvE,OAAO,MAAMC,8BAA8B;IACzC;QAAEC,MAAM;IAAiB;IACzB;QAAEA,MAAM;IAAqB;IAC7B;QAAEA,MAAM;IAAgD;IACxD;QAAEA,MAAM;IAAY;IACpB;QAAEA,MAAM;IAAwB;IAChC;QAAEA,MAAM;IAAiC;IACzC;QAAEA,MAAM;IAAgB;CACzB,CAAuD;AAiDxD;;CAEC,GACD,OAAO,MAAMC,wBAAwB,OAGnCC,MACA,EACEC,OAAO,EACPC,qBAAqB,EACrBC,oBAAoB,EACpBC,gBAAgB,EAChBC,QAAQ,EACRC,mBAAmB,EACnBC,IAAI,EACJC,IAAI,EACJC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACS,EAC/BC;IAEA,MAAMC,kBAAkB,CAAC,SAAS,EAAEnB,UAAUQ,SAAS,OAAO,CAAC;IAC/D,MAAMY,uBAAuB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AMxB,oBACJc,MACAE,sBAAsBJ,IAAI,EAC1BK,qBAAqBL,IAAI,EACzB;YACE+C,KAAK,CAAC,iBAAiB,EAAErC,KAAK,CAAC,CAAC;YAChCP;YACA,mFAAmF;YACnF,wDAAwD;YACxD,qFAAqF;YACrF,uFAAuF;YACvF6C,6BAA6B;gBAAClC;gBAAiBC;aAAqB;QACtE;IAEJ;IAEAtB,6BACES,MACAJ,aACEN,gBAAoDqB,cACpD;WACOJ,SAAS,QACV;YACE;YACA;YACA;YACA;SACD,GACD,EAAE;WACDA,SAAS,YAAY;YAAC;SAAqB,GAAG,EAAE;QACrD;QACA;KACD,GAEHX,aACEN,gBAAoDqB,cACpD;QAAC;KAAgB,GAEnB5B,kBAAkBmB,sBAAsBiC,IAAI,EAAE;AAElD,EAAE"}
1
+ {"version":3,"sources":["../../../../../../../packages/nx-plugin/src/utils/connection/open-api/react.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { addTargetToLocalDev } from '../../../connection/local-dev';\nimport runtimeConfigGenerator from '../../../ts/react-website/runtime-config/generator';\nimport { addSingleImport, applyGritQL } from '../../ast';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from '../../declared-dependencies';\nimport { addDependenciesToPackageJson } from '../../dependencies';\nimport { updateGitIgnore } from '../../git';\nimport { kebabCase, toClassName } from '../../names';\nimport { sortObjectKeys } from '../../object';\nimport { type ITsDepVersion, withVersions } from '../../versions';\n\n/** Dependencies a caller must declare to add an OpenAPI React client. */\nexport const OPEN_API_REACT_DEPENDENCIES = [\n { name: 'oidc-client-ts' },\n { name: 'react-oidc-context' },\n { name: '@aws-sdk/credential-provider-cognito-identity' },\n { name: 'aws4fetch' },\n { name: '@tanstack/react-query' },\n { name: '@tanstack/react-query-devtools' },\n { name: '@smithy/types' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\nexport interface AddOpenApiReactClientOptions {\n /**\n * The react project to add the openapi client and build targets to\n */\n frontendProjectConfig: ProjectConfiguration;\n /**\n * The backend project which serves the api\n */\n backendProjectConfig: ProjectConfiguration;\n /**\n * The project which builds/generates the openapi spec\n */\n specBuildProject: ProjectConfiguration;\n /**\n * Name of the api\n */\n apiName: string;\n /**\n * Path to the openapi spec from the workspace root\n */\n specPath: string;\n /**\n * Fully qualified target name for the target that builds/generates the openapi spec\n */\n specBuildTargetName: string;\n /**\n * Authentication method\n */\n auth: 'iam' | 'cognito' | 'custom';\n /**\n * Port on which the backend project's local server listens\n */\n port: number;\n /**\n * When true, the generated provider reads from runtimeConfig.agentRuntimes\n * and converts Bedrock AgentCore Runtime ARNs to HTTP URLs.\n * When false (default), reads from runtimeConfig.apis directly.\n */\n isAgentRuntime?: boolean;\n /**\n * When set, the generated provider reads the gateway's URL from\n * runtimeConfig.gateways and routes to the agent via the gateway's\n * path-based `/<targetName>` route instead of invoking the runtime directly.\n */\n gatewayRoute?: {\n gatewayClassName: string;\n targetName: string;\n };\n /**\n * When true, skips the dev target setup. Use this when the caller\n * handles dev target configuration separately (e.g. agent connections\n * that use a component-specific dev target instead of 'serve').\n */\n skipLocalDev?: boolean;\n}\n\n/**\n * Adds an OpenAPI React client to the frontend project along with supporting build targets\n */\nexport const addOpenApiReactClient = async <\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n {\n apiName,\n frontendProjectConfig,\n backendProjectConfig,\n specBuildProject,\n specPath,\n specBuildTargetName,\n auth,\n port,\n isAgentRuntime = false,\n gatewayRoute,\n skipLocalDev = false,\n }: AddOpenApiReactClientOptions,\n declaration: D & MustDeclare<typeof OPEN_API_REACT_DEPENDENCIES, D>,\n) => {\n const clientGenTarget = `generate:${kebabCase(apiName)}-client`;\n const clientGenWatchTarget = `watch-${clientGenTarget}`;\n\n const generatedClientDir = joinPathFragments('generated', kebabCase(apiName));\n const generatedClientDirFromRoot = joinPathFragments(\n frontendProjectConfig.sourceRoot,\n generatedClientDir,\n );\n\n // Add TypeScript client generation to Frontend project.json\n updateProjectConfiguration(tree, frontendProjectConfig.name, {\n ...frontendProjectConfig,\n targets: sortObjectKeys({\n ...frontendProjectConfig.targets,\n // Generate should run before compile and bundle as the client is created as part of the website src\n ...Object.fromEntries(\n ['compile', 'bundle'].map((target) => [\n target,\n {\n ...frontendProjectConfig.targets?.[target],\n dependsOn: [\n ...(\n frontendProjectConfig.targets?.[target]?.dependsOn ?? []\n ).filter((t) => t !== clientGenTarget),\n clientGenTarget,\n ],\n },\n ]),\n ),\n [clientGenTarget]: {\n cache: true,\n executor: 'nx:run-commands',\n inputs: [\n {\n dependentTasksOutputFiles: '**/*.json',\n },\n ],\n outputs: [\n joinPathFragments('{workspaceRoot}', generatedClientDirFromRoot),\n ],\n options: {\n commands: [\n `nx g @aws/nx-plugin:open-api#ts-hooks --openApiSpecPath=\"${specPath}\" --outputPath=\"${generatedClientDirFromRoot}\" --no-interactive`,\n ],\n },\n dependsOn: [specBuildTargetName],\n },\n // Watch target for regenerating the client\n [clientGenWatchTarget]: {\n executor: 'nx:run-commands',\n options: {\n commands: [\n `nx watch --projects=${specBuildProject.name} --includeDependencies -- nx run ${frontendProjectConfig.name}:\"${clientGenTarget}\"`,\n ],\n },\n continuous: true,\n },\n }),\n });\n\n const relativeSrcDir = frontendProjectConfig.sourceRoot.slice(\n frontendProjectConfig.root.length + 1,\n );\n\n // Ignore the generated client by default\n // Users can safely remove the entry from the .gitignore if they prefer to check it in\n updateGitIgnore(tree, frontendProjectConfig.root, (patterns) => [\n ...patterns,\n joinPathFragments(relativeSrcDir, generatedClientDir),\n ]);\n\n // Ensure that the frontend has runtime config as we'll use the url for creating the client\n await runtimeConfigGenerator(tree, {\n project: frontendProjectConfig.name,\n });\n\n // Add sigv4 fetch\n if (auth === 'iam') {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, '../../files/website/hooks/sigv4'),\n joinPathFragments(frontendProjectConfig.sourceRoot, 'hooks'),\n {},\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n }\n\n // Generate the tanstack query provider if it does not exist already\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n '../../files/website/components/tanstack-query',\n ),\n joinPathFragments(frontendProjectConfig.sourceRoot, 'components'),\n {},\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n const apiNameClassName = toClassName(apiName);\n\n // Add a hook to instantiate the client\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n frontendProjectConfig.sourceRoot,\n {\n auth,\n apiName,\n apiNameClassName,\n generatedClientDir,\n isAgentRuntime,\n gatewayRoute,\n },\n );\n\n // Update main.tsx to add required providers\n const mainTsxPath = joinPathFragments(\n frontendProjectConfig.sourceRoot,\n 'main.tsx',\n );\n\n // Add the query client provider if it doesn't exist already\n await addSingleImport(\n tree,\n mainTsxPath,\n 'QueryClientProvider',\n './components/QueryClientProvider',\n );\n await applyGritQL(\n tree,\n mainTsxPath,\n '`<App />` => `<QueryClientProvider><App /></QueryClientProvider>` where { $program <: not contains `<QueryClientProvider>$_</QueryClientProvider>` }',\n );\n\n // Add the api provider if it does not exist\n const providerName = `${apiNameClassName}Provider`;\n await addSingleImport(\n tree,\n mainTsxPath,\n providerName,\n `./components/${providerName}`,\n );\n await applyGritQL(\n tree,\n mainTsxPath,\n `\\`<App />\\` => \\`<${providerName}><App /></${providerName}>\\` where { $program <: not contains \\`<${providerName}>$_</${providerName}>\\` }`,\n );\n\n // Update the dev target on the website to use our local server.\n // Callers that handle the dev target separately (e.g. agent connections) set skipLocalDev.\n if (!skipLocalDev) {\n await addTargetToLocalDev(\n tree,\n frontendProjectConfig.name,\n backendProjectConfig.name,\n {\n url: `http://localhost:${port}/`,\n apiName,\n // Additionally add a dependency on the generate watch command to ensure that local\n // API changes that affect the client are also reloaded.\n // We include a dependency on the generate target as watch ONLY triggers on a change,\n // and we need to ensure the client is generated the first time if not already present.\n additionalDependencyTargets: [clientGenTarget, clientGenWatchTarget],\n },\n );\n }\n\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof OPEN_API_REACT_DEPENDENCIES>(declaration),\n [\n ...((auth === 'iam'\n ? [\n 'oidc-client-ts',\n 'react-oidc-context',\n '@aws-sdk/credential-provider-cognito-identity',\n 'aws4fetch',\n ]\n : []) as any),\n ...((auth === 'cognito' ? ['react-oidc-context'] : []) as any),\n '@tanstack/react-query',\n '@tanstack/react-query-devtools',\n ],\n ),\n withVersions(\n forDependencies<typeof OPEN_API_REACT_DEPENDENCIES>(declaration),\n ['@smithy/types'],\n ),\n joinPathFragments(frontendProjectConfig.root, 'package.json'),\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","updateProjectConfiguration","addTargetToLocalDev","runtimeConfigGenerator","addSingleImport","applyGritQL","forDependencies","addDependenciesToPackageJson","updateGitIgnore","kebabCase","toClassName","sortObjectKeys","withVersions","OPEN_API_REACT_DEPENDENCIES","name","addOpenApiReactClient","tree","apiName","frontendProjectConfig","backendProjectConfig","specBuildProject","specPath","specBuildTargetName","auth","port","isAgentRuntime","gatewayRoute","skipLocalDev","declaration","clientGenTarget","clientGenWatchTarget","generatedClientDir","generatedClientDirFromRoot","sourceRoot","targets","Object","fromEntries","map","target","dependsOn","filter","t","cache","executor","inputs","dependentTasksOutputFiles","outputs","options","commands","continuous","relativeSrcDir","slice","root","length","patterns","project","dirname","overwriteStrategy","KeepExisting","apiNameClassName","mainTsxPath","providerName","url","additionalDependencyTargets"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAGjBC,0BAA0B,QACrB,aAAa;AACpB,SAASC,mBAAmB,QAAQ,mCAAgC;AACpE,OAAOC,4BAA4B,wDAAqD;AACxF,SAASC,eAAe,EAAEC,WAAW,QAAQ,eAAY;AACzD,SA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7B,kBAAkBmB,sBAAsBkC,IAAI,EAAE;AAElD,EAAE"}
@@ -17,9 +17,34 @@ export declare const DOCKER_DEPENDENCIES: readonly [{
17
17
  * version to install globally, and the versions its dependency overrides pin.
18
18
  */
19
19
  export declare const nodeImageVersions: () => {
20
- npmVersion: "12.0.1";
21
- minimatchVersion: "10.2.5";
20
+ npmVersion: "12.0.2";
21
+ minimatchVersion: "10.2.6";
22
22
  };
23
+ /**
24
+ * Packages a vended Node `Dockerfile` pins, which every generator writing one
25
+ * must declare so the version sync keeps those pins current.
26
+ *
27
+ * Spread through `ownedElsewhere`: the pin lives in the image build rather than
28
+ * in any manifest, so nothing is installed into the workspace. Left undeclared
29
+ * these would be the only vended versions never upgraded — and they are
30
+ * precisely the ones held at a version clear of a known HIGH/CRITICAL
31
+ * vulnerability.
32
+ */
33
+ export declare const NODE_IMAGE_DEPENDENCIES: readonly [{
34
+ readonly name: "npm";
35
+ }, {
36
+ readonly name: "minimatch";
37
+ }];
38
+ /**
39
+ * Packages the AWS Distro for OpenTelemetry install in a vended `Dockerfile`
40
+ * pins, for the images that auto-instrument with it. Spread through
41
+ * `ownedElsewhere` for the same reason as {@link NODE_IMAGE_DEPENDENCIES}.
42
+ */
43
+ export declare const ADOT_IMAGE_DEPENDENCIES: readonly [{
44
+ readonly name: "@aws/aws-distro-opentelemetry-node-autoinstrumentation";
45
+ }, {
46
+ readonly name: "@opentelemetry/propagator-jaeger";
47
+ }];
23
48
  export interface DockerScanTargetOptions {
24
49
  /**
25
50
  * Project configuration to add the scan target to (mutated in place).
@@ -5,7 +5,7 @@
5
5
  import { forDependencies } from "./declared-dependencies.js";
6
6
  import { FS_DEPENDENCIES, FsCommands } from "./fs.js";
7
7
  import { addDependencyToTargetIfNotPresent } from "./nx.js";
8
- import { CONTAINER_VERSIONS, TS_VERSIONS } from "./versions.js";
8
+ import { containerImage, TS_VERSIONS } from "./versions.js";
9
9
  /** Dependencies a caller must declare to add a Docker scan target. */ export const DOCKER_DEPENDENCIES = [
10
10
  ...FS_DEPENDENCIES
11
11
  ];
@@ -21,6 +21,35 @@ const TRIVY_IGNORE_CONTENTS = `# Trivy ignore file. Add one vulnerability ID (e.
21
21
  npmVersion: TS_VERSIONS.npm,
22
22
  minimatchVersion: TS_VERSIONS.minimatch
23
23
  });
24
+ /**
25
+ * Packages a vended Node `Dockerfile` pins, which every generator writing one
26
+ * must declare so the version sync keeps those pins current.
27
+ *
28
+ * Spread through `ownedElsewhere`: the pin lives in the image build rather than
29
+ * in any manifest, so nothing is installed into the workspace. Left undeclared
30
+ * these would be the only vended versions never upgraded — and they are
31
+ * precisely the ones held at a version clear of a known HIGH/CRITICAL
32
+ * vulnerability.
33
+ */ export const NODE_IMAGE_DEPENDENCIES = [
34
+ {
35
+ name: 'npm'
36
+ },
37
+ {
38
+ name: 'minimatch'
39
+ }
40
+ ];
41
+ /**
42
+ * Packages the AWS Distro for OpenTelemetry install in a vended `Dockerfile`
43
+ * pins, for the images that auto-instrument with it. Spread through
44
+ * `ownedElsewhere` for the same reason as {@link NODE_IMAGE_DEPENDENCIES}.
45
+ */ export const ADOT_IMAGE_DEPENDENCIES = [
46
+ {
47
+ name: '@aws/aws-distro-opentelemetry-node-autoinstrumentation'
48
+ },
49
+ {
50
+ name: '@opentelemetry/propagator-jaeger'
51
+ }
52
+ ];
24
53
  /**
25
54
  * Add a cacheable Trivy scan target for the images built by a docker target
26
55
  * and wire it under the aggregate \`trivy\` target. The scan is not part of
@@ -50,7 +79,7 @@ const TRIVY_IGNORE_CONTENTS = `# Trivy ignore file. Add one vulnerability ID (e.
50
79
  // per target, so it makes a stable, collision-free key.
51
80
  const scanKey = imageTags[0].replace(/[^a-zA-Z0-9-]/g, '-');
52
81
  const scanDir = joinPathFragments('dist', projectRoot, 'trivy', scanKey);
53
- const trivyImage = `public.ecr.aws/aquasecurity/trivy:${CONTAINER_VERSIONS.trivy}`;
82
+ const trivyImage = containerImage('trivy');
54
83
  const fs = new FsCommands(tree, forDependencies(declaration));
55
84
  const commands = [
56
85
  fs.rm(scanDir),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/docker.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n joinPathFragments,\n type ProjectConfiguration,\n type Tree,\n} from '@nx/devkit';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from './declared-dependencies';\nimport { FS_DEPENDENCIES, FsCommands } from './fs';\nimport { addDependencyToTargetIfNotPresent } from './nx';\nimport { CONTAINER_VERSIONS, TS_VERSIONS } from './versions';\n\n/** Dependencies a caller must declare to add a Docker scan target. */\nexport const DOCKER_DEPENDENCIES = [...FS_DEPENDENCIES] as const;\n\nconst TRIVY_IGNORE_FILE = '.trivyignore';\n\nconst TRIVY_IGNORE_CONTENTS = `# Trivy ignore file. Add one vulnerability ID (e.g. CVE-2021-12345) per line to\n# suppress it during the image scan (\\`nx run-many --target trivy\\`).\n# https://trivy.dev/latest/docs/configuration/filtering/#by-finding-ids\n`;\n\n/**\n * Substitution variables for the vended Node `Dockerfile` templates: the npm\n * version to install globally, and the versions its dependency overrides pin.\n */\nexport const nodeImageVersions = () => ({\n npmVersion: TS_VERSIONS.npm,\n minimatchVersion: TS_VERSIONS.minimatch,\n});\n\nexport interface DockerScanTargetOptions {\n /**\n * Project configuration to add the scan target to (mutated in place).\n */\n readonly project: ProjectConfiguration;\n /**\n * Container engine command to invoke (\\`docker\\` or \\`finch\\`).\n */\n readonly containerEngine: string;\n /**\n * Name of the scan target to add, e.g. \\`my-agent-trivy\\`.\n */\n readonly trivyTargetName: string;\n /**\n * Name of the docker target that builds the image(s) to scan. The scan\n * target depends on it.\n */\n readonly dockerTargetName: string;\n /**\n * Tags of the images built by the docker target which should be scanned.\n */\n readonly imageTags: string[];\n}\n\n/**\n * Add a cacheable Trivy scan target for the images built by a docker target\n * and wire it under the aggregate \\`trivy\\` target. The scan is not part of\n * \\`build\\` — run \\`nx run-many --target trivy\\` (the root \\`trivy\\` script) in CI.\n *\n * The scan target depends on the docker target and declares the project source\n * as its inputs, so an unchanged image is never re-scanned (a cache hit skips\n * the scan entirely). Each image is saved to a tarball under\n * \\`dist/<projectRoot>/trivy/<scan-key>\\` (kept out of any Docker build context)\n * and scanned with the pinned ECR-hosted Trivy image via a workspace-relative\n * bind mount, so the same commands work under both docker and finch. The scan\n * exits non-zero (exit code 1) on HIGH/CRITICAL vulnerabilities.\n *\n * A \\`.trivyignore\\` is vended at the project root (kept if it already exists)\n * for suppressing findings.\n */\nexport const addDockerScanTarget = <const D extends DependencyDeclaration>(\n tree: Tree,\n options: DockerScanTargetOptions,\n declaration: D & MustDeclare<typeof DOCKER_DEPENDENCIES, D>,\n): void => {\n const { project, containerEngine, trivyTargetName, dockerTargetName } =\n options;\n const { imageTags } = options;\n const projectRoot = project.root;\n\n const ignoreFilePath = joinPathFragments(projectRoot, TRIVY_IGNORE_FILE);\n if (!tree.exists(ignoreFilePath)) {\n tree.write(ignoreFilePath, TRIVY_IGNORE_CONTENTS);\n }\n\n // Stage scan artifacts in a directory unique to this scan target so that\n // sibling targets in the same project (e.g. multiple agents) don't clobber\n // each other's tarballs when run in parallel. The first image tag is unique\n // per target, so it makes a stable, collision-free key.\n const scanKey = imageTags[0].replace(/[^a-zA-Z0-9-]/g, '-');\n const scanDir = joinPathFragments('dist', projectRoot, 'trivy', scanKey);\n const trivyImage = `public.ecr.aws/aquasecurity/trivy:${CONTAINER_VERSIONS.trivy}`;\n\n const fs = new FsCommands(\n tree,\n forDependencies<typeof DOCKER_DEPENDENCIES>(declaration),\n );\n const commands = [\n fs.rm(scanDir),\n fs.mkdir(scanDir),\n fs.cp(ignoreFilePath, joinPathFragments(scanDir, TRIVY_IGNORE_FILE)),\n ];\n\n imageTags.forEach((imageTag, index) => {\n const tarName = `image-${index}.tar`;\n commands.push(\n `${containerEngine} save -o ${joinPathFragments(scanDir, tarName)} ${imageTag}`,\n `${containerEngine} run --rm -v \"./${scanDir}\":/scan ${trivyImage} image --input /scan/${tarName} --ignorefile /scan/${TRIVY_IGNORE_FILE} --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 --no-progress -q`,\n );\n });\n\n project.targets ??= {};\n project.targets[trivyTargetName] = {\n cache: true,\n // The scanned image is fully determined by the project source, so caching\n // on the source ensures an unchanged image is never re-scanned.\n inputs: ['default', '^production'],\n outputs: [`{workspaceRoot}/${scanDir}`],\n executor: 'nx:run-commands',\n options: {\n commands,\n parallel: false,\n },\n dependsOn: [dockerTargetName],\n };\n\n // Aggregate per-component scan targets under a single `trivy` target. The\n // scan is intentionally NOT wired into `build`: image scanning is slow and\n // its result depends on the ever-changing vulnerability database (a scan\n // that passes today can fail tomorrow when a new CVE is published), so\n // coupling it to `build` would make local and CI builds non-deterministic.\n // Run `nx run-many --target trivy` (the root `trivy` script) in CI instead.\n if (trivyTargetName !== 'trivy') {\n addDependencyToTargetIfNotPresent(project, 'trivy', trivyTargetName);\n }\n};\n"],"names":["joinPathFragments","forDependencies","FS_DEPENDENCIES","FsCommands","addDependencyToTargetIfNotPresent","CONTAINER_VERSIONS","TS_VERSIONS","DOCKER_DEPENDENCIES","TRIVY_IGNORE_FILE","TRIVY_IGNORE_CONTENTS","nodeImageVersions","npmVersion","npm","minimatchVersion","minimatch","addDockerScanTarget","tree","options","declaration","project","containerEngine","trivyTargetName","dockerTargetName","imageTags","projectRoot","root","ignoreFilePath","exists","write","scanKey","replace","scanDir","trivyImage","trivy","fs","commands","rm","mkdir","cp","forEach","imageTag","index","tarName","push","targets","cache","inputs","outputs","executor","parallel","dependsOn"],"mappings":"AAAA;;;CAGC,GACD,SACEA,iBAAiB,QAGZ,aAAa;AACpB,SAEEC,eAAe,QAEV,6BAA0B;AACjC,SAASC,eAAe,EAAEC,UAAU,QAAQ,UAAO;AACnD,SAASC,iCAAiC,QAAQ,UAAO;AACzD,SAASC,kBAAkB,EAAEC,WAAW,Q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SAAS,CAAC,EAAEF,UAAU,EAC/E,GAAGpB,gBAAgB,gBAAgB,EAAEW,QAAQ,QAAQ,EAAEC,WAAW,qBAAqB,EAAEU,QAAQ,oBAAoB,EAAElC,kBAAkB,yFAAyF,CAAC;IAEvO;IAEAW,QAAQyB,OAAO,KAAK,CAAC;IACrBzB,QAAQyB,OAAO,CAACvB,gBAAgB,GAAG;QACjCwB,OAAO;QACP,0EAA0E;QAC1E,gEAAgE;QAChEC,QAAQ;YAAC;YAAW;SAAc;QAClCC,SAAS;YAAC,CAAC,gBAAgB,EAAEhB,SAAS;SAAC;QACvCiB,UAAU;QACV/B,SAAS;YACPkB;YACAc,UAAU;QACZ;QACAC,WAAW;YAAC5B;SAAiB;IAC/B;IAEA,0EAA0E;IAC1E,2EAA2E;IAC3E,yEAAyE;IACzE,uEAAuE;IACvE,2EAA2E;IAC3E,4EAA4E;IAC5E,IAAID,oBAAoB,SAAS;QAC/BjB,kCAAkCe,SAAS,SAASE;IACtD;AACF,EAAE"}
1
+ {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/docker.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n joinPathFragments,\n type ProjectConfiguration,\n type Tree,\n} from '@nx/devkit';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from './declared-dependencies';\nimport { FS_DEPENDENCIES, FsCommands } from './fs';\nimport { addDependencyToTargetIfNotPresent } from './nx';\nimport { containerImage, type ITsDepVersion, TS_VERSIONS } from './versions';\n\n/** Dependencies a caller must declare to add a Docker scan target. */\nexport const DOCKER_DEPENDENCIES = [...FS_DEPENDENCIES] as const;\n\nconst TRIVY_IGNORE_FILE = '.trivyignore';\n\nconst TRIVY_IGNORE_CONTENTS = `# Trivy ignore file. Add one vulnerability ID (e.g. CVE-2021-12345) per line to\n# suppress it during the image scan (\\`nx run-many --target trivy\\`).\n# https://trivy.dev/latest/docs/configuration/filtering/#by-finding-ids\n`;\n\n/**\n * Substitution variables for the vended Node `Dockerfile` templates: the npm\n * version to install globally, and the versions its dependency overrides pin.\n */\nexport const nodeImageVersions = () => ({\n npmVersion: TS_VERSIONS.npm,\n minimatchVersion: TS_VERSIONS.minimatch,\n});\n\n/**\n * Packages a vended Node `Dockerfile` pins, which every generator writing one\n * must declare so the version sync keeps those pins current.\n *\n * Spread through `ownedElsewhere`: the pin lives in the image build rather than\n * in any manifest, so nothing is installed into the workspace. Left undeclared\n * these would be the only vended versions never upgraded — and they are\n * precisely the ones held at a version clear of a known HIGH/CRITICAL\n * vulnerability.\n */\nexport const NODE_IMAGE_DEPENDENCIES = [\n { name: 'npm' },\n { name: 'minimatch' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/**\n * Packages the AWS Distro for OpenTelemetry install in a vended `Dockerfile`\n * pins, for the images that auto-instrument with it. Spread through\n * `ownedElsewhere` for the same reason as {@link NODE_IMAGE_DEPENDENCIES}.\n */\nexport const ADOT_IMAGE_DEPENDENCIES = [\n { name: '@aws/aws-distro-opentelemetry-node-autoinstrumentation' },\n { name: '@opentelemetry/propagator-jaeger' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\nexport interface DockerScanTargetOptions {\n /**\n * Project configuration to add the scan target to (mutated in place).\n */\n readonly project: ProjectConfiguration;\n /**\n * Container engine command to invoke (\\`docker\\` or \\`finch\\`).\n */\n readonly containerEngine: string;\n /**\n * Name of the scan target to add, e.g. \\`my-agent-trivy\\`.\n */\n readonly trivyTargetName: string;\n /**\n * Name of the docker target that builds the image(s) to scan. The scan\n * target depends on it.\n */\n readonly dockerTargetName: string;\n /**\n * Tags of the images built by the docker target which should be scanned.\n */\n readonly imageTags: string[];\n}\n\n/**\n * Add a cacheable Trivy scan target for the images built by a docker target\n * and wire it under the aggregate \\`trivy\\` target. The scan is not part of\n * \\`build\\` — run \\`nx run-many --target trivy\\` (the root \\`trivy\\` script) in CI.\n *\n * The scan target depends on the docker target and declares the project source\n * as its inputs, so an unchanged image is never re-scanned (a cache hit skips\n * the scan entirely). Each image is saved to a tarball under\n * \\`dist/<projectRoot>/trivy/<scan-key>\\` (kept out of any Docker build context)\n * and scanned with the pinned ECR-hosted Trivy image via a workspace-relative\n * bind mount, so the same commands work under both docker and finch. The scan\n * exits non-zero (exit code 1) on HIGH/CRITICAL vulnerabilities.\n *\n * A \\`.trivyignore\\` is vended at the project root (kept if it already exists)\n * for suppressing findings.\n */\nexport const addDockerScanTarget = <const D extends DependencyDeclaration>(\n tree: Tree,\n options: DockerScanTargetOptions,\n declaration: D & MustDeclare<typeof DOCKER_DEPENDENCIES, D>,\n): void => {\n const { project, containerEngine, trivyTargetName, dockerTargetName } =\n options;\n const { imageTags } = options;\n const projectRoot = project.root;\n\n const ignoreFilePath = joinPathFragments(projectRoot, TRIVY_IGNORE_FILE);\n if (!tree.exists(ignoreFilePath)) {\n tree.write(ignoreFilePath, TRIVY_IGNORE_CONTENTS);\n }\n\n // Stage scan artifacts in a directory unique to this scan target so that\n // sibling targets in the same project (e.g. multiple agents) don't clobber\n // each other's tarballs when run in parallel. The first image tag is unique\n // per target, so it makes a stable, collision-free key.\n const scanKey = imageTags[0].replace(/[^a-zA-Z0-9-]/g, '-');\n const scanDir = joinPathFragments('dist', projectRoot, 'trivy', scanKey);\n const trivyImage = containerImage('trivy');\n\n const fs = new FsCommands(\n tree,\n forDependencies<typeof DOCKER_DEPENDENCIES>(declaration),\n );\n const commands = [\n fs.rm(scanDir),\n fs.mkdir(scanDir),\n fs.cp(ignoreFilePath, joinPathFragments(scanDir, TRIVY_IGNORE_FILE)),\n ];\n\n imageTags.forEach((imageTag, index) => {\n const tarName = `image-${index}.tar`;\n commands.push(\n `${containerEngine} save -o ${joinPathFragments(scanDir, tarName)} ${imageTag}`,\n `${containerEngine} run --rm -v \"./${scanDir}\":/scan ${trivyImage} image --input /scan/${tarName} --ignorefile /scan/${TRIVY_IGNORE_FILE} --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 --no-progress -q`,\n );\n });\n\n project.targets ??= {};\n project.targets[trivyTargetName] = {\n cache: true,\n // The scanned image is fully determined by the project source, so caching\n // on the source ensures an unchanged image is never re-scanned.\n inputs: ['default', '^production'],\n outputs: [`{workspaceRoot}/${scanDir}`],\n executor: 'nx:run-commands',\n options: {\n commands,\n parallel: false,\n },\n dependsOn: [dockerTargetName],\n };\n\n // Aggregate per-component scan targets under a single `trivy` target. The\n // scan is intentionally NOT wired into `build`: image scanning is slow and\n // its result depends on the ever-changing vulnerability database (a scan\n // that passes today can fail tomorrow when a new CVE is published), so\n // coupling it to `build` would make local and CI builds non-deterministic.\n // Run `nx run-many --target trivy` (the root `trivy` script) in CI instead.\n if (trivyTargetName !== 'trivy') {\n addDependencyToTargetIfNotPresent(project, 'trivy', trivyTargetName);\n }\n};\n"],"names":["joinPathFragments","forDependencies","FS_DEPENDENCIES","FsCommands","addDependencyToTargetIfNotPresent","containerImage","TS_VERSIONS","DOCKER_DEPENDENCIES","TRIVY_IGNORE_FILE","TRIVY_IGNORE_CONTENTS","nodeImageVersions","npmVersion","npm","minimatchVersion","minimatch","NODE_IMAGE_DEPENDENCIES","name","ADOT_IMAGE_DEPENDENCIES","addDockerScanTarget","tree","options","declaration","project","containerEngine","trivyTargetName","dockerTargetName","imageTags","projectRoot","root","ignoreFilePath","exists","write","scanKey","replace","scanDir","trivyImage","fs","commands","rm","mkdir","cp","forEach","imageTag","index","tarName","push","targets","cache","inputs","outputs","executor","parallel","dependsOn"],"mappings":"AAAA;;;CAGC,GACD,SACEA,iBAAiB,QAGZ,aAAa;AACpB,SAEEC,eAAe,QAEV,6BAA0B;AACjC,SAASC,eAAe,EAAEC,UAAU,QAAQ,UAAO;AACnD,SAASC,iCAAiC,QAAQ,UAAO;AACzD,SAASC,cAAc,EAAsBC,WAAW,QAAQ,gBAAa;AAE7E,oEAAoE,GACpE,OAAO,MAAMC,sBAAsB;OAAIL;CAAgB,CAAU;AAEjE,M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AM,EAAED,MAAM,IAAI,CAAC;QACpCN,SAASQ,IAAI,CACX,GAAGtB,gBAAgB,SAAS,EAAEvB,kBAAkBkC,SAASU,SAAS,CAAC,EAAEF,UAAU,EAC/E,GAAGnB,gBAAgB,gBAAgB,EAAEW,QAAQ,QAAQ,EAAEC,WAAW,qBAAqB,EAAES,QAAQ,oBAAoB,EAAEpC,kBAAkB,yFAAyF,CAAC;IAEvO;IAEAc,QAAQwB,OAAO,KAAK,CAAC;IACrBxB,QAAQwB,OAAO,CAACtB,gBAAgB,GAAG;QACjCuB,OAAO;QACP,0EAA0E;QAC1E,gEAAgE;QAChEC,QAAQ;YAAC;YAAW;SAAc;QAClCC,SAAS;YAAC,CAAC,gBAAgB,EAAEf,SAAS;SAAC;QACvCgB,UAAU;QACV9B,SAAS;YACPiB;YACAc,UAAU;QACZ;QACAC,WAAW;YAAC3B;SAAiB;IAC/B;IAEA,0EAA0E;IAC1E,2EAA2E;IAC3E,yEAAyE;IACzE,uEAAuE;IACvE,2EAA2E;IAC3E,4EAA4E;IAC5E,IAAID,oBAAoB,SAAS;QAC/BpB,kCAAkCkB,SAAS,SAASE;IACtD;AACF,EAAE"}
@@ -4,6 +4,16 @@
4
4
  */
5
5
  import { type Tree } from '@nx/devkit';
6
6
  import type { Iac } from '../iac';
7
+ import { type IacMetadata } from '../shared-constructs-constants';
8
+ /**
9
+ * Python version the generated Terraform pins in the callback URL module's inline
10
+ * `uv run --with` script. Nothing installs it, so it is declared for its version
11
+ * alone, and only on the Terraform branch that writes the script.
12
+ */
13
+ export declare const IDENTITY_CONSTRUCTS_PY_DEPENDENCIES: readonly [{
14
+ readonly name: "boto3";
15
+ readonly when: (m: IacMetadata) => boolean;
16
+ }];
7
17
  export interface AddIdentityInfraOptions {
8
18
  cognitoDomain: string;
9
19
  allowSignup: boolean;
@@ -4,8 +4,18 @@
4
4
  */ import { generateFiles, joinPathFragments, OverwriteStrategy } from "@nx/devkit";
5
5
  import { addStarExport } from "../ast.js";
6
6
  import { esmVars } from "../module-format.js";
7
- import { PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, SHARED_TERRAFORM_DIR } from "../shared-constructs-constants.js";
7
+ import { generatedTerraform, PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, SHARED_TERRAFORM_DIR } from "../shared-constructs-constants.js";
8
8
  import { PY_VERSIONS, terraformProviderVersions } from "../versions.js";
9
+ /**
10
+ * Python version the generated Terraform pins in the callback URL module's inline
11
+ * `uv run --with` script. Nothing installs it, so it is declared for its version
12
+ * alone, and only on the Terraform branch that writes the script.
13
+ */ export const IDENTITY_CONSTRUCTS_PY_DEPENDENCIES = [
14
+ {
15
+ name: 'boto3',
16
+ when: generatedTerraform
17
+ }
18
+ ];
9
19
  /**
10
20
  * Add infrastructure for a static website
11
21
  */ export const addIdentityInfra = async (tree, options)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/identity-constructs/identity-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast';\nimport type { Iac } from '../iac';\nimport { esmVars } from '../module-format';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants';\nimport { PY_VERSIONS, terraformProviderVersions } from '../versions';\n\nexport interface AddIdentityInfraOptions {\n cognitoDomain: string;\n allowSignup: boolean;\n}\n\n/**\n * Add infrastructure for a static website\n */\nexport const addIdentityInfra = async (\n tree: Tree,\n options: AddIdentityInfraOptions & { iac: Iac },\n) => {\n if (options.iac === 'cdk') {\n await addIdentityCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addIdentityTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n};\n\nconst addIdentityCdkConstructs = async (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'cdk', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, 'src', 'core'),\n { ...options, ...esmVars(tree) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'core',\n 'index.ts',\n ),\n './user-identity.js',\n );\n};\n\nconst addIdentityTerraformModules = (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'terraform', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'core'),\n {\n ...options,\n boto3Version: PY_VERSIONS.boto3,\n ...terraformProviderVersions(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Update the static website module to add the callback url\n const staticWebsiteModule = tree.read(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n 'utf-8',\n );\n if (\n staticWebsiteModule &&\n !staticWebsiteModule.includes(\n 'source = \"../user-identity/add-callback-url\"',\n )\n ) {\n // Find the aws_cloudfront_distribution.website resource and add the callback URL module after it.\n // Includes the CloudFront domain plus any custom domain names (aliases) configured via var.custom_domain_names.\n const callbackUrlModule = `\n\n# Add CloudFront domain and any custom domain names to user pool client callback URLs.\n# Keyed by statically-known values so for_each keys are resolvable at plan time; the\n# CloudFront domain is only known at apply time, so it appears in the value, not the key.\nlocals {\n callback_urls = merge(\n { cloudfront = \"https://\\${aws_cloudfront_distribution.website.domain_name}\" },\n { for domain in var.custom_domain_names : domain => \"https://\\${domain}\" },\n )\n}\n\nmodule \"add_callback_url\" {\n source = \"../user-identity/add-callback-url\"\n for_each = local.callback_urls\n\n callback_url = each.value\n\n depends_on = [aws_cloudfront_distribution.website]\n}`;\n\n // Find the CloudFront distribution resource using proper brace counting\n // This handles deeply nested structures correctly\n const resourceStartPattern =\n /resource\\s+\"aws_cloudfront_distribution\"\\s+\"website\"\\s*\\{/;\n const resourceStartMatch = staticWebsiteModule.match(resourceStartPattern);\n\n if (resourceStartMatch) {\n const startIndex =\n resourceStartMatch.index! + resourceStartMatch[0].length - 1; // Position at opening brace\n let braceCount = 0;\n let insertionPoint = -1;\n\n // Count braces to find the end of the resource block\n for (let i = startIndex; i < staticWebsiteModule.length; i++) {\n const char = staticWebsiteModule[i];\n if (char === '{') {\n braceCount++;\n } else if (char === '}') {\n braceCount--;\n if (braceCount === 0) {\n // Found the closing brace of the CloudFront resource\n insertionPoint = i + 1;\n break;\n }\n }\n }\n\n if (insertionPoint !== -1) {\n // Insert the callback URL module right after the CloudFront distribution\n const beforeInsertion = staticWebsiteModule.substring(\n 0,\n insertionPoint,\n );\n const afterInsertion = staticWebsiteModule.substring(insertionPoint);\n const updatedContent =\n beforeInsertion + callbackUrlModule + afterInsertion;\n\n tree.write(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n updatedContent,\n );\n }\n }\n }\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","addStarExport","esmVars","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_TERRAFORM_DIR","PY_VERSIONS","terraformProviderVersions","addIdentityInfra","tree","options","iac","addIdentityCdkConstructs","addIdentityTerraformModules","Error","dirname","overwriteStrategy","KeepExisting","boto3Version","boto3","staticWebsiteModule","read","includes","callbackUrlModule","resourceStartPattern","resourceStartMatch","match","startIndex","index","length","braceCount","insertionPoint","i","char","beforeInsertion","substring","afterInsertion","updatedContent","write"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,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,gHAAgH;QAChH,MAAMC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;CAmB9B,CAAC;QAEE,wEAAwE;QACxE,kDAAkD;QAClD,MAAMC,uBACJ;QACF,MAAMC,qBAAqBL,oBAAoBM,KAAK,CAACF;QAErD,IAAIC,oBAAoB;YACtB,MAAME,aACJF,mBAAmBG,KAAK,GAAIH,kBAAkB,CAAC,EAAE,CAACI,MAAM,GAAG,GAAG,4BAA4B;YAC5F,IAAIC,aAAa;YACjB,IAAIC,iBAAiB,CAAC;YAEtB,qDAAqD;YACrD,IAAK,IAAIC,IAAIL,YAAYK,IAAIZ,oBAAoBS,MAAM,EAAEG,IAAK;gBAC5D,MAAMC,OAAOb,mBAAmB,CAACY,EAAE;gBACnC,IAAIC,SAAS,KAAK;oBAChBH;gBACF,OAAO,IAAIG,SAAS,KAAK;oBACvBH;oBACA,IAAIA,eAAe,GAAG;wBACpB,qDAAqD;wBACrDC,iBAAiBC,IAAI;wBACrB;oBACF;gBACF;YACF;YAEA,IAAID,mBAAmB,CAAC,GAAG;gBACzB,yEAAyE;gBACzE,MAAMG,kBAAkBd,oBAAoBe,SAAS,CACnD,GACAJ;gBAEF,MAAMK,iBAAiBhB,oBAAoBe,SAAS,CAACJ;gBACrD,MAAMM,iBACJH,kBAAkBX,oBAAoBa;gBAExC3B,KAAK6B,KAAK,CACRvC,kBACEI,cACAE,sBACA,OACA,QACA,kBACA,sBAEFgC;YAEJ;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/identity-constructs/identity-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast';\nimport type { DeclaredPyDependency } from '../declared-dependencies';\nimport type { Iac } from '../iac';\nimport { esmVars } from '../module-format';\nimport {\n generatedTerraform,\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants';\nimport {\n type IPyDepVersion,\n PY_VERSIONS,\n terraformProviderVersions,\n} from '../versions';\n\n/**\n * Python version the generated Terraform pins in the callback URL module's inline\n * `uv run --with` script. Nothing installs it, so it is declared for its version\n * alone, and only on the Terraform branch that writes the script.\n */\nexport const IDENTITY_CONSTRUCTS_PY_DEPENDENCIES = [\n { name: 'boto3', when: generatedTerraform },\n] as const satisfies readonly DeclaredPyDependency<\n IPyDepVersion,\n IacMetadata\n>[];\n\nexport interface AddIdentityInfraOptions {\n cognitoDomain: string;\n allowSignup: boolean;\n}\n\n/**\n * Add infrastructure for a static website\n */\nexport const addIdentityInfra = async (\n tree: Tree,\n options: AddIdentityInfraOptions & { iac: Iac },\n) => {\n if (options.iac === 'cdk') {\n await addIdentityCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addIdentityTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n};\n\nconst addIdentityCdkConstructs = async (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'cdk', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, 'src', 'core'),\n { ...options, ...esmVars(tree) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'core',\n 'index.ts',\n ),\n './user-identity.js',\n );\n};\n\nconst addIdentityTerraformModules = (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'terraform', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'core'),\n {\n ...options,\n boto3Version: PY_VERSIONS.boto3,\n ...terraformProviderVersions(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Update the static website module to add the callback url\n const staticWebsiteModule = tree.read(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n 'utf-8',\n );\n if (\n staticWebsiteModule &&\n !staticWebsiteModule.includes(\n 'source = \"../user-identity/add-callback-url\"',\n )\n ) {\n // Find the aws_cloudfront_distribution.website resource and add the callback URL module after it.\n // Includes the CloudFront domain plus any custom domain names (aliases) configured via var.custom_domain_names.\n const callbackUrlModule = `\n\n# Add CloudFront domain and any custom domain names to user pool client callback URLs.\n# Keyed by statically-known values so for_each keys are resolvable at plan time; the\n# CloudFront domain is only known at apply time, so it appears in the value, not the key.\nlocals {\n callback_urls = merge(\n { cloudfront = \"https://\\${aws_cloudfront_distribution.website.domain_name}\" },\n { for domain in var.custom_domain_names : domain => \"https://\\${domain}\" },\n )\n}\n\nmodule \"add_callback_url\" {\n source = \"../user-identity/add-callback-url\"\n for_each = local.callback_urls\n\n callback_url = each.value\n\n depends_on = [aws_cloudfront_distribution.website]\n}`;\n\n // Find the CloudFront distribution resource using proper brace counting\n // This handles deeply nested structures correctly\n const resourceStartPattern =\n /resource\\s+\"aws_cloudfront_distribution\"\\s+\"website\"\\s*\\{/;\n const resourceStartMatch = staticWebsiteModule.match(resourceStartPattern);\n\n if (resourceStartMatch) {\n const startIndex =\n resourceStartMatch.index! + resourceStartMatch[0].length - 1; // Position at opening brace\n let braceCount = 0;\n let insertionPoint = -1;\n\n // Count braces to find the end of the resource block\n for (let i = startIndex; i < staticWebsiteModule.length; i++) {\n const char = staticWebsiteModule[i];\n if (char === '{') {\n braceCount++;\n } else if (char === '}') {\n braceCount--;\n if (braceCount === 0) {\n // Found the closing brace of the CloudFront resource\n insertionPoint = i + 1;\n break;\n }\n }\n }\n\n if (insertionPoint !== -1) {\n // Insert the callback URL module right after the CloudFront distribution\n const beforeInsertion = staticWebsiteModule.substring(\n 0,\n insertionPoint,\n );\n const afterInsertion = staticWebsiteModule.substring(insertionPoint);\n const updatedContent =\n beforeInsertion + callbackUrlModule + afterInsertion;\n\n tree.write(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n updatedContent,\n );\n }\n }\n }\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","addStarExport","esmVars","generatedTerraform","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_TERRAFORM_DIR","PY_VERSIONS","terraformProviderVersions","IDENTITY_CONSTRUCTS_PY_DEPENDENCIES","name","when","addIdentityInfra","tree","options","iac","addIdentityCdkConstructs","addIdentityTerraformModules","Error","dirname","overwriteStrategy","KeepExisting","boto3Version","boto3","staticWebsiteModule","read","includes","callbackUrlModule","resourceStartPattern","resourceStartMatch","match","startIndex","index","length","braceCount","insertionPoint","i","char","beforeInsertion","substring","afterInsertion","updatedContent","write"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,SAASC,aAAa,QAAQ,YAAS;AAGvC,SAASC,OAAO,QAAQ,sBAAmB;AAC3C,SACEC,kBAAkB,EAElBC,YAAY,EACZC,qBAAqB,EACrBC,oBAAoB,QACf,oCAAiC;AACxC,SAEEC,WAAW,EACXC,yBAAyB,QACpB,iBAAc;AAErB;;;;CAIC,GACD,OAAO,MAAMC,sCAAsC;IACjD;QAAEC,MAAM;QAASC,MAAMR;IAAmB;CAC3C,CAGG;AAOJ;;CAEC,GACD,OAAO,MAAMS,mBAAmB,OAC9BC,MACAC;IAEA,IAAIA,QAAQC,GAAG,KAAK,OAAO;QACzB,MAAMC,yBAAyBH,MAAMC;IACvC,OAAO,IAAIA,QAAQC,GAAG,KAAK,aAAa;QACtCE,4BAA4BJ,MAAMC;I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IZ,oBAAoBS,MAAM,EAAEG,IAAK;gBAC5D,MAAMC,OAAOb,mBAAmB,CAACY,EAAE;gBACnC,IAAIC,SAAS,KAAK;oBAChBH;gBACF,OAAO,IAAIG,SAAS,KAAK;oBACvBH;oBACA,IAAIA,eAAe,GAAG;wBACpB,qDAAqD;wBACrDC,iBAAiBC,IAAI;wBACrB;oBACF;gBACF;YACF;YAEA,IAAID,mBAAmB,CAAC,GAAG;gBACzB,yEAAyE;gBACzE,MAAMG,kBAAkBd,oBAAoBe,SAAS,CACnD,GACAJ;gBAEF,MAAMK,iBAAiBhB,oBAAoBe,SAAS,CAACJ;gBACrD,MAAMM,iBACJH,kBAAkBX,oBAAoBa;gBAExC3B,KAAK6B,KAAK,CACR3C,kBACEK,cACAE,sBACA,OACA,QACA,kBACA,sBAEFmC;YAEJ;QACF;IACF;AACF"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ import type { MigrationsJson } from './migration-versions';
6
+ /**
7
+ * `migrations.json` is assembled from the plugin's source rather than committed,
8
+ * so two PRs each adding a migration touch disjoint files and never conflict on
9
+ * a shared manifest.
10
+ *
11
+ * The pieces it is assembled from:
12
+ * - one folder per migration under `src/migrations/<dir>/<name>/`, where `<dir>`
13
+ * is `latest` until a release claims it and `v<version>` after — the folder
14
+ * carries a `metadata.json` (its description) beside the code, and its files
15
+ * discriminate the kind: a `migration.ts` makes it deterministic, a `prompt.md`
16
+ * agentic, both hybrid;
17
+ * - `packageJsonUpdates.json`, the nx bumps the weekly update maintains, kept in
18
+ * its own file so that churn never shares an edit with a migration PR;
19
+ * - the version sync entry, a fixed `everyMigration` codemod that runs on every
20
+ * upgrade and so has no folder.
21
+ *
22
+ * The assembled manifest is unversioned — release-time stamping resolves versions
23
+ * (see `migration-versions.ts`).
24
+ */
25
+ /** JSON schema the manifest declares, matching what nx expects. */
26
+ export declare const MIGRATIONS_JSON_SCHEMA = "http://json-schema.org/schema";
27
+ /** Key the version sync migration is registered under. */
28
+ export declare const SYNC_VENDED_MIGRATION_KEY = "sync-vended-versions";
29
+ /**
30
+ * The version sync migration entry. Committed as code rather than a folder: it
31
+ * carries no release-specific registration and must run on every upgrade, so it
32
+ * is fixed and can't conflict.
33
+ */
34
+ export declare const syncVendedMigrationEntry: () => NonNullable<MigrationsJson["generators"]>[string];
35
+ /** A migration folder discovered under `src/migrations`. */
36
+ export interface DiscoveredMigration {
37
+ /** Folder grouping the migration by release: `latest` or `v<version>`. */
38
+ dir: string;
39
+ /** Migration folder name. */
40
+ name: string;
41
+ /** Description read from the folder's `metadata.json`. */
42
+ description: string;
43
+ /** A `migration.ts` is present, so the migration has a codemod. */
44
+ hasImplementation: boolean;
45
+ /** A `prompt.md` is present, so the migration hands off to an agent. */
46
+ hasPrompt: boolean;
47
+ }
48
+ /**
49
+ * Assemble the plugin's `migrations.json` from its source pieces: the discovered
50
+ * migration folders, the version sync entry, and the nx `packageJsonUpdates`.
51
+ *
52
+ * Deterministic — keys are sorted — so regenerating always yields the same file.
53
+ *
54
+ * @param pluginName the plugin package name the manifest is for
55
+ * @param migrations migration folders discovered under `src/migrations`
56
+ * @param packageJsonUpdates parsed `packageJsonUpdates.json`, if present
57
+ */
58
+ export declare const assembleMigrations: (pluginName: string, migrations: DiscoveredMigration[], packageJsonUpdates?: MigrationsJson["packageJsonUpdates"]) => MigrationsJson;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */ import { isValidVersion, LATEST_MIGRATIONS_DIR, migrationKey } from "./migration-versions.js";
5
+ import { sortObjectKeys } from "./object.js";
6
+ /**
7
+ * `migrations.json` is assembled from the plugin's source rather than committed,
8
+ * so two PRs each adding a migration touch disjoint files and never conflict on
9
+ * a shared manifest.
10
+ *
11
+ * The pieces it is assembled from:
12
+ * - one folder per migration under `src/migrations/<dir>/<name>/`, where `<dir>`
13
+ * is `latest` until a release claims it and `v<version>` after — the folder
14
+ * carries a `metadata.json` (its description) beside the code, and its files
15
+ * discriminate the kind: a `migration.ts` makes it deterministic, a `prompt.md`
16
+ * agentic, both hybrid;
17
+ * - `packageJsonUpdates.json`, the nx bumps the weekly update maintains, kept in
18
+ * its own file so that churn never shares an edit with a migration PR;
19
+ * - the version sync entry, a fixed `everyMigration` codemod that runs on every
20
+ * upgrade and so has no folder.
21
+ *
22
+ * The assembled manifest is unversioned — release-time stamping resolves versions
23
+ * (see `migration-versions.ts`).
24
+ */ /** JSON schema the manifest declares, matching what nx expects. */ export const MIGRATIONS_JSON_SCHEMA = 'http://json-schema.org/schema';
25
+ /** Key the version sync migration is registered under. */ export const SYNC_VENDED_MIGRATION_KEY = 'sync-vended-versions';
26
+ /**
27
+ * The version sync migration entry. Committed as code rather than a folder: it
28
+ * carries no release-specific registration and must run on every upgrade, so it
29
+ * is fixed and can't conflict.
30
+ */ export const syncVendedMigrationEntry = ()=>({
31
+ description: 'Sync vended dependency versions and the tracked plugin version to those vended by this release',
32
+ implementation: './src/utils/version-upgrade-migration/migration',
33
+ everyMigration: true
34
+ });
35
+ /** Registration for a single discovered migration folder. */ const migrationEntry = (migration)=>{
36
+ const path = `./src/migrations/${migration.dir}/${migration.name}`;
37
+ return {
38
+ // A migration in a `v<version>` folder has already been claimed by that
39
+ // release; its version is the folder. One in `latest` is left for stamping.
40
+ ...migration.dir !== LATEST_MIGRATIONS_DIR && isValidVersion(migration.dir.replace(/^v/, '')) ? {
41
+ version: migration.dir.replace(/^v/, '')
42
+ } : {},
43
+ description: migration.description,
44
+ ...migration.hasImplementation ? {
45
+ implementation: `${path}/migration`
46
+ } : {},
47
+ ...migration.hasPrompt ? {
48
+ prompt: `${path}/prompt.md`
49
+ } : {}
50
+ };
51
+ };
52
+ /**
53
+ * Assemble the plugin's `migrations.json` from its source pieces: the discovered
54
+ * migration folders, the version sync entry, and the nx `packageJsonUpdates`.
55
+ *
56
+ * Deterministic — keys are sorted — so regenerating always yields the same file.
57
+ *
58
+ * @param pluginName the plugin package name the manifest is for
59
+ * @param migrations migration folders discovered under `src/migrations`
60
+ * @param packageJsonUpdates parsed `packageJsonUpdates.json`, if present
61
+ */ export const assembleMigrations = (pluginName, migrations, packageJsonUpdates)=>({
62
+ $schema: MIGRATIONS_JSON_SCHEMA,
63
+ name: pluginName,
64
+ generators: sortObjectKeys({
65
+ [SYNC_VENDED_MIGRATION_KEY]: syncVendedMigrationEntry(),
66
+ ...Object.fromEntries(migrations.map((migration)=>[
67
+ migrationKey(migration.dir, migration.name),
68
+ migrationEntry(migration)
69
+ ]))
70
+ }),
71
+ ...packageJsonUpdates && Object.keys(packageJsonUpdates).length > 0 ? {
72
+ packageJsonUpdates
73
+ } : {}
74
+ });
75
+
76
+ //# sourceMappingURL=migration-manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/migration-manifest.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { MigrationsJson } from './migration-versions';\nimport {\n isValidVersion,\n LATEST_MIGRATIONS_DIR,\n migrationKey,\n} from './migration-versions';\nimport { sortObjectKeys } from './object';\n\n/**\n * `migrations.json` is assembled from the plugin's source rather than committed,\n * so two PRs each adding a migration touch disjoint files and never conflict on\n * a shared manifest.\n *\n * The pieces it is assembled from:\n * - one folder per migration under `src/migrations/<dir>/<name>/`, where `<dir>`\n * is `latest` until a release claims it and `v<version>` after — the folder\n * carries a `metadata.json` (its description) beside the code, and its files\n * discriminate the kind: a `migration.ts` makes it deterministic, a `prompt.md`\n * agentic, both hybrid;\n * - `packageJsonUpdates.json`, the nx bumps the weekly update maintains, kept in\n * its own file so that churn never shares an edit with a migration PR;\n * - the version sync entry, a fixed `everyMigration` codemod that runs on every\n * upgrade and so has no folder.\n *\n * The assembled manifest is unversioned — release-time stamping resolves versions\n * (see `migration-versions.ts`).\n */\n\n/** JSON schema the manifest declares, matching what nx expects. */\nexport const MIGRATIONS_JSON_SCHEMA = 'http://json-schema.org/schema';\n\n/** Key the version sync migration is registered under. */\nexport const SYNC_VENDED_MIGRATION_KEY = 'sync-vended-versions';\n\n/**\n * The version sync migration entry. Committed as code rather than a folder: it\n * carries no release-specific registration and must run on every upgrade, so it\n * is fixed and can't conflict.\n */\nexport const syncVendedMigrationEntry = (): NonNullable<\n MigrationsJson['generators']\n>[string] => ({\n description:\n 'Sync vended dependency versions and the tracked plugin version to those vended by this release',\n implementation: './src/utils/version-upgrade-migration/migration',\n everyMigration: true,\n});\n\n/** A migration folder discovered under `src/migrations`. */\nexport interface DiscoveredMigration {\n /** Folder grouping the migration by release: `latest` or `v<version>`. */\n dir: string;\n /** Migration folder name. */\n name: string;\n /** Description read from the folder's `metadata.json`. */\n description: string;\n /** A `migration.ts` is present, so the migration has a codemod. */\n hasImplementation: boolean;\n /** A `prompt.md` is present, so the migration hands off to an agent. */\n hasPrompt: boolean;\n}\n\n/** Registration for a single discovered migration folder. */\nconst migrationEntry = (\n migration: DiscoveredMigration,\n): NonNullable<MigrationsJson['generators']>[string] => {\n const path = `./src/migrations/${migration.dir}/${migration.name}`;\n return {\n // A migration in a `v<version>` folder has already been claimed by that\n // release; its version is the folder. One in `latest` is left for stamping.\n ...(migration.dir !== LATEST_MIGRATIONS_DIR &&\n isValidVersion(migration.dir.replace(/^v/, ''))\n ? { version: migration.dir.replace(/^v/, '') }\n : {}),\n description: migration.description,\n ...(migration.hasImplementation\n ? { implementation: `${path}/migration` }\n : {}),\n ...(migration.hasPrompt ? { prompt: `${path}/prompt.md` } : {}),\n };\n};\n\n/**\n * Assemble the plugin's `migrations.json` from its source pieces: the discovered\n * migration folders, the version sync entry, and the nx `packageJsonUpdates`.\n *\n * Deterministic — keys are sorted — so regenerating always yields the same file.\n *\n * @param pluginName the plugin package name the manifest is for\n * @param migrations migration folders discovered under `src/migrations`\n * @param packageJsonUpdates parsed `packageJsonUpdates.json`, if present\n */\nexport const assembleMigrations = (\n pluginName: string,\n migrations: DiscoveredMigration[],\n packageJsonUpdates?: MigrationsJson['packageJsonUpdates'],\n): MigrationsJson => ({\n $schema: MIGRATIONS_JSON_SCHEMA,\n name: pluginName,\n generators: sortObjectKeys({\n [SYNC_VENDED_MIGRATION_KEY]: syncVendedMigrationEntry(),\n ...Object.fromEntries(\n migrations.map((migration) => [\n migrationKey(migration.dir, migration.name),\n migrationEntry(migration),\n ]),\n ),\n }),\n ...(packageJsonUpdates && Object.keys(packageJsonUpdates).length > 0\n ? { packageJsonUpdates }\n : {}),\n});\n"],"names":["isValidVersion","LATEST_MIGRATIONS_DIR","migrationKey","sortObjectKeys","MIGRATIONS_JSON_SCHEMA","SYNC_VENDED_MIGRATION_KEY","syncVendedMigrationEntry","description","implementation","everyMigration","migrationEntry","migration","path","dir","name","replace","version","hasImplementation","hasPrompt","prompt","assembleMigrations","pluginName","migrations","packageJsonUpdates","$schema","generators","Object","fromEntries","map","keys","length"],"mappings":"AAAA;;;CAGC,GAED,SACEA,cAAc,EACdC,qBAAqB,EACrBC,YAAY,QACP,0BAAuB;AAC9B,SAASC,cAAc,QAAQ,cAAW;AAE1C;;;;;;;;;;;;;;;;;;CAkBC,GAED,iEAAiE,GACjE,OAAO,MAAMC,yBAAyB,gCAAgC;AAEtE,wDAAwD,GACxD,OAAO,MAAMC,4BAA4B,uBAAuB;AAEhE;;;;CAIC,GACD,OAAO,MAAMC,2BAA2B,IAE1B,CAAA;QACZC,aACE;QACFC,gBAAgB;QAChBC,gBAAgB;IAClB,CAAA,EAAG;AAgBH,2DAA2D,GAC3D,MAAMC,iBAAiB,CACrBC;IAEA,MAAMC,OAAO,CAAC,iBAAiB,EAAED,UAAUE,GAAG,CAAC,CAAC,EAAEF,UAAUG,IAAI,EAAE;IAClE,OAAO;QACL,wEAAwE;QACxE,4EAA4E;QAC5E,GAAIH,UAAUE,GAAG,KAAKZ,yBACtBD,eAAeW,UAAUE,GAAG,CAACE,OAAO,CAAC,MAAM,OACvC;YAAEC,SAASL,UAAUE,GAAG,CAACE,OAAO,CAAC,MAAM;QAAI,IAC3C,CAAC,CAAC;QACNR,aAAaI,UAAUJ,WAAW;QAClC,GAAII,UAAUM,iBAAiB,GAC3B;YAAET,gBAAgB,GAAGI,KAAK,UAAU,CAAC;QAAC,IACtC,CAAC,CAAC;QACN,GAAID,UAAUO,SAAS,GAAG;YAAEC,QAAQ,GAAGP,KAAK,UAAU,CAAC;QAAC,IAAI,CAAC,CAAC;IAChE;AACF;AAEA;;;;;;;;;CASC,GACD,OAAO,MAAMQ,qBAAqB,CAChCC,YACAC,YACAC,qBACoB,CAAA;QACpBC,SAASpB;QACTU,MAAMO;QACNI,YAAYtB,eAAe;YACzB,CAACE,0BAA0B,EAAEC;YAC7B,GAAGoB,OAAOC,WAAW,CACnBL,WAAWM,GAAG,CAAC,CAACjB,YAAc;oBAC5BT,aAAaS,UAAUE,GAAG,EAAEF,UAAUG,IAAI;oBAC1CJ,eAAeC;iBAChB,EACF;QACH;QACA,GAAIY,sBAAsBG,OAAOG,IAAI,CAACN,oBAAoBO,MAAM,GAAG,IAC/D;YAAEP;QAAmB,IACrB,CAAC,CAAC;IACR,CAAA,EAAG"}
@@ -27,6 +27,8 @@ import { compare } from 'semver';
27
27
  * re-stamped with each pending version, so it runs on every upgrade.
28
28
  */
29
29
  export interface MigrationsJson {
30
+ $schema?: string;
31
+ name?: string;
30
32
  generators?: Record<string, {
31
33
  version?: string;
32
34
  everyMigration?: boolean;