@aws/nx-plugin 1.0.0-rc.72 → 1.0.0-rc.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-THIRD-PARTY +1379 -2592
- package/README.md +7 -89
- package/migrations.json +38 -23
- package/package.json +4 -4
- package/src/agentcore-gateway/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +3 -3
- package/src/internal/test-matrix/generator.js +15 -0
- package/src/internal/test-matrix/generator.js.map +1 -1
- package/src/license/config.d.ts +9 -0
- package/src/license/config.js +28 -0
- package/src/license/config.js.map +1 -1
- package/src/license/dependency-check/collectors/collector.js.map +1 -1
- package/src/license/dependency-check/collectors/python-collector.js +9 -3
- package/src/license/dependency-check/collectors/python-collector.js.map +1 -1
- package/src/license/generator.js +3 -17
- package/src/license/generator.js.map +1 -1
- package/src/license/known-exceptions.d.ts +0 -1
- package/src/license/known-exceptions.js +1 -23
- package/src/license/known-exceptions.js.map +1 -1
- package/src/migrations/latest/apt-security-updates-in-container-images/__snapshots__/migration.spec.ts.snap +90 -0
- package/src/migrations/latest/apt-security-updates-in-container-images/metadata.json +3 -0
- package/src/migrations/latest/apt-security-updates-in-container-images/migration.js +90 -0
- package/src/migrations/latest/apt-security-updates-in-container-images/migration.js.map +1 -0
- package/src/migrations/latest/py-agent-session-id-middleware-extraction/metadata.json +3 -0
- package/src/migrations/latest/py-agent-session-id-middleware-extraction/migration.js +118 -0
- package/src/migrations/latest/py-agent-session-id-middleware-extraction/migration.js.map +1 -0
- package/src/migrations/latest/remove-mcp-inspector-license-exceptions/metadata.json +3 -0
- package/src/migrations/latest/remove-mcp-inspector-license-exceptions/migration.d.ts +6 -0
- package/src/migrations/latest/remove-mcp-inspector-license-exceptions/migration.js +38 -0
- package/src/migrations/latest/remove-mcp-inspector-license-exceptions/migration.js.map +1 -0
- package/src/migrations/v1.0.0-rc.67/0001-smithy-server-package-rename/migration.js.map +1 -0
- package/src/migrations/v1.0.0-rc.68/0001-translate-script-whole-file-writes/migration.js.map +1 -0
- package/src/migrations/{latest/py-agent-a2a-lifespan-construction → v1.0.0-rc.70/0001-py-agent-a2a-lifespan-construction}/migration.js +14 -2
- package/src/migrations/v1.0.0-rc.70/0001-py-agent-a2a-lifespan-construction/migration.js.map +1 -0
- package/src/migrations/v1.0.0-rc.71/0001-py-agent-a2a-httpx-client-per-call/migration.d.ts +6 -0
- package/src/migrations/v1.0.0-rc.71/0001-py-agent-a2a-httpx-client-per-call/migration.js.map +1 -0
- package/src/migrations/v1.0.0-rc.72/0001-py-agent-session-management-support/migration.d.ts +2 -0
- package/src/migrations/v1.0.0-rc.72/0001-py-agent-session-management-support/migration.js.map +1 -0
- package/src/preset/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/py/agent/__snapshots__/generator.constructs.spec.ts.snap +14 -22
- package/src/py/agent/__snapshots__/generator.frameworks.spec.ts.snap +10 -21
- package/src/py/agent/__snapshots__/generator.protocols.spec.ts.snap +2 -2
- package/src/py/agent/a2a-connection/generator.js +5 -11
- package/src/py/agent/a2a-connection/generator.js.map +1 -1
- package/src/py/agent/files/deploy/Dockerfile.template +7 -0
- package/src/py/agent/files/langchain/a2a/main.py.template +4 -15
- package/src/py/agent/files/langchain/ag-ui/main.py.template +2 -13
- package/src/py/agent/files/langchain/common/middleware/__init__.py.template +0 -0
- package/src/py/agent/files/langchain/common/middleware/session_id_middleware.py.template +17 -0
- package/src/py/agent/files/langchain/http/main.py.template +2 -14
- package/src/py/agent/files/strands/a2a/main.py.template +4 -15
- package/src/py/agent/files/strands/ag-ui/main.py.template +2 -13
- package/src/py/agent/files/strands/common/middleware/__init__.py.template +0 -0
- package/src/py/agent/files/strands/common/middleware/session_id_middleware.py.template +17 -0
- package/src/py/agent/files/strands/http/main.py.template +2 -17
- package/src/py/mcp-server/__snapshots__/generator.spec.ts.snap +5 -5
- package/src/py/mcp-server/files/deploy/Dockerfile.template +7 -0
- package/src/py/mcp-server/generator.js +8 -3
- package/src/py/mcp-server/generator.js.map +1 -1
- package/src/py/rdb/__snapshots__/generator.spec.ts.snap +7 -5
- package/src/py/rdb/generator.js +36 -2
- package/src/py/rdb/generator.js.map +1 -1
- package/src/sdk/agentcore-harness.d.ts +6 -0
- package/src/sdk/agentcore-harness.js +7 -0
- package/src/sdk/agentcore-harness.js.map +1 -0
- package/src/sdk/smithy.d.ts +6 -0
- package/src/sdk/smithy.js +7 -0
- package/src/sdk/smithy.js.map +1 -0
- package/src/smithy/project/__snapshots__/generator.spec.ts.snap +14 -14
- package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/ts/agent/__snapshots__/generator.spec.ts.snap +9 -2
- package/src/ts/agent/a2a-connection/generator.js +4 -2
- package/src/ts/agent/a2a-connection/generator.js.map +1 -1
- package/src/ts/agent/files/deploy/Dockerfile.template +7 -0
- package/src/ts/mcp-server/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/ts/mcp-server/files/Dockerfile.template +7 -0
- package/src/ts/mcp-server/generator.js +8 -3
- package/src/ts/mcp-server/generator.js.map +1 -1
- package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +8 -6
- package/src/ts/rdb/generator.js +29 -2
- package/src/ts/rdb/generator.js.map +1 -1
- package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +15 -15
- package/src/ts/react-website/app/generator.js +4 -2
- package/src/ts/react-website/app/generator.js.map +1 -1
- package/src/ts/react-website/cognito-auth/__snapshots__/generator.terraform.spec.ts.snap +1 -1
- package/src/utils/agent-connection/agent-connection.js +5 -9
- package/src/utils/agent-connection/agent-connection.js.map +1 -1
- package/src/utils/ast.d.ts +29 -0
- package/src/utils/ast.js +31 -0
- package/src/utils/ast.js.map +1 -1
- package/src/utils/metrics.js +2 -2
- package/src/utils/metrics.js.map +1 -1
- package/src/utils/versions.d.ts +73 -73
- package/src/utils/versions.js +70 -70
- package/src/utils/versions.js.map +1 -1
- package/src/migrations/latest/py-agent-a2a-httpx-client-per-call/migration.js.map +0 -1
- package/src/migrations/latest/py-agent-a2a-lifespan-construction/migration.js.map +0 -1
- package/src/migrations/latest/py-agent-session-management-support/migration.js.map +0 -1
- package/src/migrations/latest/smithy-server-package-rename/migration.js.map +0 -1
- package/src/migrations/latest/translate-script-whole-file-writes/migration.js.map +0 -1
- package/src/py/rdb/files/__name__/__init__.py.template +0 -3
- package/src/py/rdb/files/config.json.template +0 -14
- package/src/ts/rdb/files/config.json.template +0 -14
- package/src/ts/rdb/files/src/index.ts.template +0 -1
- /package/src/migrations/latest/{py-agent-a2a-httpx-client-per-call → apt-security-updates-in-container-images}/migration.d.ts +0 -0
- /package/src/migrations/latest/{py-agent-session-management-support → py-agent-session-id-middleware-extraction}/migration.d.ts +0 -0
- /package/src/migrations/{latest/smithy-server-package-rename → v1.0.0-rc.67/0001-smithy-server-package-rename}/metadata.json +0 -0
- /package/src/migrations/{latest/py-agent-a2a-lifespan-construction → v1.0.0-rc.67/0001-smithy-server-package-rename}/migration.d.ts +0 -0
- /package/src/migrations/{latest/smithy-server-package-rename → v1.0.0-rc.67/0001-smithy-server-package-rename}/migration.js +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/build-system-prompt.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/build-user-prompt.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/config-path.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/file-to-translate.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/get-files-to-translate.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/header.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/log.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/main-call.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/main.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/project-root.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/run-with-concurrency.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/scripts-dir.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/files/translate-file-for-language.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/already-migrated.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/build-system-prompt.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/build-user-prompt.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/config-path.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/file-to-translate.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/get-files-to-translate.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/log.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/main-call.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/main.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/project-root.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/run-with-concurrency.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/grit/translate-file-for-language.grit +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/metadata.json +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/migration.d.ts +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/migration.js +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/test-fixtures/released-script-first.ts.fixture +0 -0
- /package/src/migrations/{latest/translate-script-whole-file-writes → v1.0.0-rc.68/0001-translate-script-whole-file-writes}/test-fixtures/released-script.ts.fixture +0 -0
- /package/src/migrations/{latest/py-agent-a2a-lifespan-construction → v1.0.0-rc.70/0001-py-agent-a2a-lifespan-construction}/metadata.json +0 -0
- /package/src/migrations/{latest/smithy-server-package-rename → v1.0.0-rc.70/0001-py-agent-a2a-lifespan-construction}/migration.d.ts +0 -0
- /package/src/migrations/{latest/py-agent-a2a-httpx-client-per-call → v1.0.0-rc.71/0001-py-agent-a2a-httpx-client-per-call}/metadata.json +0 -0
- /package/src/migrations/{latest/py-agent-a2a-httpx-client-per-call → v1.0.0-rc.71/0001-py-agent-a2a-httpx-client-per-call}/migration.js +0 -0
- /package/src/migrations/{latest/py-agent-session-management-support → v1.0.0-rc.72/0001-py-agent-session-management-support}/metadata.json +0 -0
- /package/src/migrations/{latest/py-agent-session-management-support → v1.0.0-rc.72/0001-py-agent-session-management-support}/migration.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/ts/react-website/app/generator.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 names,\n OverwriteStrategy,\n readProjectConfiguration,\n removeDependenciesFromPackageJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { applicationGenerator } from '@nx/react';\nimport { relative, sep } from 'path';\nimport { addTsDependencies } from '../../../utils/add-dependencies';\nimport {\n addDestructuredImport,\n addSingleImport,\n applyGritQL,\n} from '../../../utils/ast';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { resolveIac } from '../../../utils/iac';\nimport { installDependencies } from '../../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx';\nimport { sortObjectKeys } from '../../../utils/object';\nimport { getRelativePathToRoot } from '../../../utils/paths';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n} from '../../../utils/shared-constructs-constants';\nimport {\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs';\nimport { configureTsProject } from '../../lib/ts-project-utils';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest';\n// typescript factory imports removed — now using GritQL for vite config transforms\nimport type {\n TsReactWebsiteGeneratorSchema,\n WebsiteInfraOption,\n} from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsReactWebsiteMetadata extends IacMetadata {\n readonly ux: UxOption;\n readonly framework: string;\n readonly infra: WebsiteInfraOption;\n readonly tailwind: boolean;\n readonly tanstackRouter: boolean;\n}\n\n// Each entry names the branch it belongs to, so the same declaration drives both\n// adding and the version sync.\nexport const DEPENDENCIES = declareDependencies<TsReactWebsiteMetadata>()({\n ts: [\n { name: 'react' },\n { name: 'react-dom' },\n // Build/test tooling imported only from vite.config.mts stays at the root.\n { name: '@nx/react', dev: true, root: true },\n { name: '@vitest/ui', dev: true, root: true },\n {\n name: '@cloudscape-design/components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/board-components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/global-styles',\n when: (m) => m.ux === 'cloudscape',\n },\n // Shared shadcn components live in the common/shadcn package, but the\n // website's own generated components (e.g. the tanstack-router sidebar)\n // import lucide-react directly, so the website must declare it.\n {\n name: 'lucide-react',\n when: (m) => m.ux === 'shadcn' && m.tanstackRouter,\n },\n { name: 'tailwindcss', when: (m) => m.tailwind },\n {\n name: '@tailwindcss/vite',\n when: (m) => m.tailwind,\n dev: true,\n root: true,\n },\n { name: '@tanstack/react-router', when: (m) => m.tanstackRouter },\n {\n name: '@tanstack/router-plugin',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-generator',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/virtual-file-routes',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-utils',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n ...ownedElsewhere(SHADCN_DEPENDENCIES),\n ...ownedElsewhere(VITEST_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ],\n py: ownedElsewhere(WEBSITE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const SUPPORTED_UX_PROVIDERS = ['none', 'cloudscape', 'shadcn'] as const;\n\nexport type UxOption = (typeof SUPPORTED_UX_PROVIDERS)[number];\n\nexport type Ux = UxOption;\n\nexport const REACT_WEBSITE_APP_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport async function tsReactWebsiteGenerator(\n tree: Tree,\n schema: TsReactWebsiteGeneratorSchema,\n) {\n const tailwind = schema.tailwind ?? true;\n const tanstackRouter = schema.tanstackRouter ?? true;\n const ux: Ux = schema.ux ?? 'shadcn';\n if (ux === 'shadcn' && !tailwind) {\n throw new Error('Shadcn requires TailwindCSS to be enabled.');\n }\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const websiteNameClassName = toClassName(schema.name);\n const websiteNameKebabCase = toKebabCase(schema.name);\n const fullyQualifiedName = `${npmScopePrefix}${websiteNameKebabCase}`;\n // NB: interactive nx generator cli can pass empty string\n const websiteContentPath = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || websiteNameKebabCase,\n );\n\n const projectAlreadyExists = tree.exists(\n joinPathFragments(websiteContentPath, 'project.json'),\n );\n\n // TODO: consider exposing and supporting e2e tests\n const e2eTestRunner = 'none';\n\n if (!projectAlreadyExists) {\n await applicationGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: websiteContentPath,\n routing: false,\n e2eTestRunner,\n linter: 'none',\n bundler: 'vite',\n unitTestRunner: 'vitest',\n useProjectJson: true,\n style: 'css',\n // Register the @nx/vite and @nx/vitest plugins so build/serve/test\n // targets are inferred rather than emitting deprecated executor targets.\n addPlugin: true,\n });\n\n // Pin the inferred target names. The vite production build is exposed as\n // `bundle` (which produces the deployable artifact), leaving `build` as an\n // aggregator over lint/compile/test/bundle. vite's own typecheck is dropped\n // in favour of the tsc `compile`.\n updateJson(tree, 'nx.json', (nxJson) => {\n for (const plugin of nxJson.plugins ?? []) {\n if (typeof plugin === 'string') continue;\n if (plugin.plugin === '@nx/vite/plugin') {\n plugin.options = {\n ...plugin.options,\n buildTargetName: 'bundle',\n // Map both of vite's inferred dev-server targets onto `serve` so the\n // plugin doesn't emit a separate `dev`; we author our own `dev`\n // below running the local-dev vite mode.\n serveTargetName: 'serve',\n devTargetName: 'serve',\n previewTargetName: 'preview',\n serveStaticTargetName: 'serve-static',\n typecheckTargetName: 'vite:typecheck',\n };\n } else if (plugin.plugin === '@nx/vitest') {\n plugin.options = {\n ...plugin.options,\n testTargetName: 'test',\n };\n }\n }\n return nxJson;\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(websiteContentPath, 'src'));\n }\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n\n const targets = projectConfiguration.targets;\n\n const infra = schema.infra ?? 'cloudfront-s3';\n\n // Configure load-runtime-config target based on IaC provider (only when infra is not none)\n const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;\n\n if (iac === 'cdk') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx load-runtime-config ${fullyQualifiedName}'`,\n },\n options: {\n command: `aws s3 cp s3://\\`aws cloudformation describe-stacks --query \"Stacks[?starts_with(StackName, '${kebabCase(npmScopePrefix)}-')][].Outputs[] | [?contains(OutputKey, '${websiteNameClassName}WebsiteBucketName')].OutputValue\" --output text\\`/runtime-config.json \"{projectRoot}/public/runtime-config.json\"`,\n },\n };\n } else if (iac === 'terraform') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description:\n \"Load runtime config from most recently applied terraform env for dev purposes. Copies the runtime config from the Terraform dist directory to the website's public directory.\",\n },\n options: {\n command:\n 'node -e \"const fs=require(\\'fs\\');fs.mkdirSync(process.env.DEST_DIR,{recursive:true});fs.copyFileSync(process.env.SRC_FILE,process.env.DEST_FILE);\"',\n env: {\n SRC_FILE: 'dist/packages/common/terraform/runtime-config.json',\n DEST_DIR: `{projectRoot}/public`,\n DEST_FILE: `{projectRoot}/public/runtime-config.json`,\n },\n },\n };\n }\n\n if (!projectAlreadyExists) {\n targets['compile'] = {\n dependsOn: ['^build'],\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.app.json',\n cwd: '{projectRoot}',\n },\n };\n // bundle is the @nx/vite/plugin inferred `vite build` (writing to the\n // bundle dir configured in vite.config) — it produces the deployable\n // artifact. build aggregates lint/compile/test/bundle.\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test', 'bundle'],\n };\n\n // Run the website and its connected dependencies locally. Mirrors the\n // inferred `serve` target but with the local-dev vite mode.\n targets['dev'] = {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n command: 'vite --mode local-dev',\n cwd: '{projectRoot}',\n },\n };\n }\n\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n // Recorded here and read by the declaration's predicates, so the packages\n // added below are exactly the ones the version sync will own.\n const metadata: TsReactWebsiteMetadata = {\n ux,\n framework: 'react',\n infra,\n tailwind,\n tanstackRouter,\n // Undefined when no infrastructure was generated, so neither provider's\n // packages were added.\n ...(iac ? { iac } : {}),\n };\n addGeneratorMetadata(\n tree,\n projectConfiguration.name,\n REACT_WEBSITE_APP_GENERATOR_INFO,\n metadata,\n );\n\n await configureTsProject(\n tree,\n {\n dir: websiteContentPath,\n fullyQualifiedName,\n },\n DEPENDENCIES,\n );\n\n if (ux === 'shadcn') {\n await sharedShadcnGenerator(tree, DEPENDENCIES);\n }\n\n if (iac) {\n await sharedConstructsGenerator(\n tree,\n {\n iac,\n },\n DEPENDENCIES,\n );\n\n await addWebsiteInfra(tree, {\n iac,\n websiteProjectName: fullyQualifiedName,\n scopeAlias,\n websiteContentPath: joinPathFragments('dist', websiteContentPath),\n websiteNameKebabCase,\n websiteNameClassName,\n });\n }\n\n const projectConfig = readProjectConfiguration(tree, fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const sharedShadcnStylesImport = relative(\n joinPathFragments(libraryRoot, 'src'),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'src',\n 'styles',\n 'globals.css',\n ),\n )\n .split(sep)\n .join('/');\n const sharedShadcnTsconfigRef = relative(\n joinPathFragments(tree.root, websiteContentPath),\n joinPathFragments(\n tree.root,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'tsconfig.json',\n ),\n )\n .split(sep)\n .join('/');\n const templateOptions = {\n ...schema,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n tailwind,\n tanstackRouter,\n scopeAlias,\n sharedShadcnStylesImport,\n };\n tree.delete(joinPathFragments(libraryRoot, 'src', 'app'));\n const appCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/app/common',\n );\n const appTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/app/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree, // the virtual file system\n appCommonTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree, // the virtual file system\n appTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n if (tanstackRouter) {\n const routerCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/tanstack-router/common',\n );\n const routerTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/tanstack-router/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree,\n routerCommonTemplatePath,\n libraryRoot,\n templateOptions,\n {\n // User-editable source (and the TanStack-managed route tree) - preserve on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n routerTemplatePath,\n libraryRoot,\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n tree.delete(joinPathFragments(websiteContentPath, 'src', 'app.tsx'));\n }\n\n if (e2eTestRunner !== 'none') {\n const e2eFullyQualifiedName = `${fullyQualifiedName}-e2e`;\n const e2eRoot = readProjectConfiguration(tree, e2eFullyQualifiedName).root;\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, `./files/e2e/${e2eTestRunner}`), // path to the file templates\n e2eRoot, // destination path of the files\n { ...schema, ...names(fullyQualifiedName) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n await configureTsProject(\n tree,\n {\n fullyQualifiedName: e2eFullyQualifiedName,\n dir: e2eRoot,\n },\n DEPENDENCIES,\n );\n }\n const viteConfigPath = joinPathFragments(libraryRoot, 'vite.config.mts');\n\n if (tree.exists(viteConfigPath)) {\n // Add Tanstack Router import if enabled\n if (tanstackRouter) {\n await addDestructuredImport(\n tree,\n viteConfigPath,\n ['tanstackRouter'],\n '@tanstack/router-plugin/vite',\n );\n\n await addDestructuredImport(tree, viteConfigPath, ['resolve'], 'path');\n }\n\n // Add TailwindCSS import if enabled\n if (tailwind) {\n await addSingleImport(\n tree,\n viteConfigPath,\n 'tailwindcss',\n '@tailwindcss/vite',\n );\n }\n\n // Update build.outDir. The inferred `vite build` target writes here, so\n // point it at the bundle dir the website infrastructure consumes.\n const outDir = joinPathFragments(\n getRelativePathToRoot(tree, fullyQualifiedName),\n 'dist',\n websiteContentPath,\n 'bundle',\n );\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`build: { $bprops }\\` where { $bprops <: contains \\`outDir: $_\\` => \\`outDir: '${outDir}'\\` }`,\n );\n\n // Add plugins to the plugins array\n if (tanstackRouter) {\n // Prepend tanstackRouter (must be first plugin) — rewrite works for both single/multi-element\n await applyGritQL(\n tree,\n viteConfigPath,\n \"`plugins: [$items]` => `plugins: [tanstackRouter({ routesDirectory: resolve(import.meta.dirname, 'src/routes'), generatedRouteTree: resolve(import.meta.dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await applyGritQL(\n tree,\n viteConfigPath,\n '`plugins: [$items]` => `plugins: [$items, tailwindcss()]` where { $items <: within `defineConfig($_)`, $items <: not some `tailwindcss()` }',\n );\n }\n\n // Use Vite's native tsconfig paths resolution (replaces vite-tsconfig-paths).\n // `dedupe` forces a single copy of react/react-dom into the bundle: each\n // project declares its own react dependency, so without this a workspace\n // library's hoisted copy can produce a second React instance and the\n // \"Invalid hook call\" runtime crash.\n await applyGritQL(\n tree,\n viteConfigPath,\n \"or { `defineConfig(() => ({ $props }))` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` }, `defineConfig({ $props })` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` } }\",\n );\n\n // Add define: { global: {} } to the config (handles both callback and direct forms)\n await applyGritQL(\n tree,\n viteConfigPath,\n 'or { `defineConfig(() => ({ $props }))` where { $props <: not contains `define`, $props += `define: { global: {} }` }, `defineConfig({ $props })` where { $props <: not contains `define`, $props += `define: { global: {} }` } }',\n );\n }\n\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n moduleResolution: 'Bundler',\n module: 'Preserve',\n },\n }),\n );\n const outDirToRootRelativePath = relative(\n joinPathFragments(tree.root, websiteContentPath),\n tree.root,\n );\n const distDir = joinPathFragments(\n outDirToRootRelativePath,\n 'dist',\n websiteContentPath,\n 'tsc',\n );\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.app.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n outDir: distDir,\n tsBuildInfoFile: joinPathFragments(distDir, 'tsconfig.lib.tsbuildinfo'),\n lib: ['DOM'],\n },\n references:\n ux === 'shadcn'\n ? [\n ...(tsconfig.references ?? []).filter(\n (ref) => ref.path !== sharedShadcnTsconfigRef,\n ),\n {\n path: sharedShadcnTsconfigRef,\n },\n ]\n : tsconfig.references,\n }),\n );\n\n addTsDependencies(tree, DEPENDENCIES, { metadata, projectRoot: libraryRoot });\n\n // @nx/react's applicationGenerator seeds react/react-dom into the root\n // manifest. The website now declares its own pinned versions, so drop the\n // root copies: without catalogs (npm) the root's floating range resolves to\n // a different version than the website's pin, installing a second React and\n // producing the \"Invalid hook call\" runtime crash.\n removeDependenciesFromPackageJson(tree, ['react', 'react-dom'], []);\n\n await addGeneratorMetricsIfApplicable(tree, [\n REACT_WEBSITE_APP_GENERATOR_INFO,\n ]);\n\n // TanStack Router's vite plugin owns this website's route tree and rewrites it\n // in its own (unformatted) shape whenever the config is loaded — including when\n // Nx computes the project graph — so formatting it here would only make\n // generation non-idempotent. The vended biome config excludes `**/*.gen.*`, so\n // the workspace's own `format` target leaves it alone too.\n await formatFilesInSubtree(tree, undefined, {\n ignore: tanstackRouter\n ? [joinPathFragments(libraryRoot, 'src', 'routeTree.gen.ts')]\n : [],\n });\n // The generated vite.config.mts imports these, and Nx's inferred `@nx/vite`\n // plugin loads that config when computing the project graph — so they must be\n // installed even if the caller would otherwise prefer to defer.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: [\n ...(tailwind ? (['@tailwindcss/vite'] as const) : []),\n ...(tanstackRouter ? (['@tanstack/router-plugin'] as const) : []),\n ],\n });\n}\nexport default tsReactWebsiteGenerator;\n"],"names":["generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","SHADCN_DEPENDENCIES","sharedShadcnGenerator","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","py","SUPPORTED_UX_PROVIDERS","REACT_WEBSITE_APP_GENERATOR_INFO","filename","tsReactWebsiteGenerator","tree","schema","Error","npmScopePrefix","scopeAlias","websiteNameClassName","websiteNameKebabCase","fullyQualifiedName","websiteContentPath","directory","subDirectory","projectAlreadyExists","exists","e2eTestRunner","routing","linter","bundler","unitTestRunner","useProjectJson","style","addPlugin","nxJson","plugin","plugins","options","buildTargetName","serveTargetName","devTargetName","previewTargetName","serveStaticTargetName","typecheckTargetName","testTargetName","delete","projectConfiguration","targets","infra","iac","undefined","executor","metadata","description","exec","command","env","SRC_FILE","DEST_DIR","DEST_FILE","dependsOn","outputs","cwd","continuous","framework","dir","websiteProjectName","projectConfig","libraryRoot","sharedShadcnStylesImport","split","join","sharedShadcnTsconfigRef","templateOptions","pkgMgrCmd","appCommonTemplatePath","dirname","appTemplatePath","toLowerCase","overwriteStrategy","KeepExisting","routerCommonTemplatePath","routerTemplatePath","e2eFullyQualifiedName","e2eRoot","viteConfigPath","outDir","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AACjD,SAASC,QAAQ,EAAEC,GAAG,QAAQ,OAAO;AACrC,SAASC,iBAAiB,QAAQ,qCAAkC;AACpE,SACEC,qBAAqB,EACrBC,eAAe,EACfC,WAAW,QACN,wBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,cAAc,QACT,0CAAuC;AAC9C,SAASC,oBAAoB,QAAQ,2BAAwB;AAC7D,SAASC,UAAU,QAAQ,wBAAqB;AAChD,SAASC,mBAAmB,QAAQ,4BAAyB;AAC7D,SAASC,+BAA+B,QAAQ,4BAAyB;AACzE,SAASC,SAAS,EAAEC,WAAW,EAAEC,WAAW,QAAQ,0BAAuB;AAC3E,SAASC,iBAAiB,QAAQ,8BAA2B;AAC7D,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,uBAAoB;AAC3B,SAASC,cAAc,QAAQ,2BAAwB;AACvD,SAASC,qBAAqB,QAAQ,0BAAuB;AAC7D,SAASC,gCAAgC,QAAQ,gCAA6B;AAC9E,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,sCAAmC;AAC1C,SAEEC,YAAY,EACZC,iBAAiB,QACZ,gDAA6C;AACpD,SACEC,mBAAmB,EACnBC,qBAAqB,QAChB,kCAA+B;AACtC,SACEC,eAAe,EACfC,kC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oC,MAAMC,OAAOuF,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;YACzBC,kBAAkB;mBACZhG,WAAY;oBAAC;iBAAoB,GAAa,EAAE;mBAChDD,iBAAkB;oBAAC;iBAA0B,GAAa,EAAE;aACjE;QACH;AACJ;AACA,eAAeM,wBAAwB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/ts/react-website/app/generator.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 names,\n OverwriteStrategy,\n readProjectConfiguration,\n removeDependenciesFromPackageJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { applicationGenerator } from '@nx/react';\nimport { relative, sep } from 'path';\nimport { addTsDependencies } from '../../../utils/add-dependencies';\nimport {\n addDestructuredImport,\n addSingleImport,\n appendToArrayViaGritQL,\n applyGritQL,\n} from '../../../utils/ast';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { resolveIac } from '../../../utils/iac';\nimport { installDependencies } from '../../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx';\nimport { sortObjectKeys } from '../../../utils/object';\nimport { getRelativePathToRoot } from '../../../utils/paths';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n} from '../../../utils/shared-constructs-constants';\nimport {\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs';\nimport { configureTsProject } from '../../lib/ts-project-utils';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest';\n// typescript factory imports removed — now using GritQL for vite config transforms\nimport type {\n TsReactWebsiteGeneratorSchema,\n WebsiteInfraOption,\n} from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsReactWebsiteMetadata extends IacMetadata {\n readonly ux: UxOption;\n readonly framework: string;\n readonly infra: WebsiteInfraOption;\n readonly tailwind: boolean;\n readonly tanstackRouter: boolean;\n}\n\n// Each entry names the branch it belongs to, so the same declaration drives both\n// adding and the version sync.\nexport const DEPENDENCIES = declareDependencies<TsReactWebsiteMetadata>()({\n ts: [\n { name: 'react' },\n { name: 'react-dom' },\n // Build/test tooling imported only from vite.config.mts stays at the root.\n { name: '@nx/react', dev: true, root: true },\n { name: '@vitest/ui', dev: true, root: true },\n {\n name: '@cloudscape-design/components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/board-components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/global-styles',\n when: (m) => m.ux === 'cloudscape',\n },\n // Shared shadcn components live in the common/shadcn package, but the\n // website's own generated components (e.g. the tanstack-router sidebar)\n // import lucide-react directly, so the website must declare it.\n {\n name: 'lucide-react',\n when: (m) => m.ux === 'shadcn' && m.tanstackRouter,\n },\n { name: 'tailwindcss', when: (m) => m.tailwind },\n {\n name: '@tailwindcss/vite',\n when: (m) => m.tailwind,\n dev: true,\n root: true,\n },\n { name: '@tanstack/react-router', when: (m) => m.tanstackRouter },\n {\n name: '@tanstack/router-plugin',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-generator',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/virtual-file-routes',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-utils',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n ...ownedElsewhere(SHADCN_DEPENDENCIES),\n ...ownedElsewhere(VITEST_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ],\n py: ownedElsewhere(WEBSITE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const SUPPORTED_UX_PROVIDERS = ['none', 'cloudscape', 'shadcn'] as const;\n\nexport type UxOption = (typeof SUPPORTED_UX_PROVIDERS)[number];\n\nexport type Ux = UxOption;\n\nexport const REACT_WEBSITE_APP_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport async function tsReactWebsiteGenerator(\n tree: Tree,\n schema: TsReactWebsiteGeneratorSchema,\n) {\n const tailwind = schema.tailwind ?? true;\n const tanstackRouter = schema.tanstackRouter ?? true;\n const ux: Ux = schema.ux ?? 'shadcn';\n if (ux === 'shadcn' && !tailwind) {\n throw new Error('Shadcn requires TailwindCSS to be enabled.');\n }\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const websiteNameClassName = toClassName(schema.name);\n const websiteNameKebabCase = toKebabCase(schema.name);\n const fullyQualifiedName = `${npmScopePrefix}${websiteNameKebabCase}`;\n // NB: interactive nx generator cli can pass empty string\n const websiteContentPath = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || websiteNameKebabCase,\n );\n\n const projectAlreadyExists = tree.exists(\n joinPathFragments(websiteContentPath, 'project.json'),\n );\n\n // TODO: consider exposing and supporting e2e tests\n const e2eTestRunner = 'none';\n\n if (!projectAlreadyExists) {\n await applicationGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: websiteContentPath,\n routing: false,\n e2eTestRunner,\n linter: 'none',\n bundler: 'vite',\n unitTestRunner: 'vitest',\n useProjectJson: true,\n style: 'css',\n // Register the @nx/vite and @nx/vitest plugins so build/serve/test\n // targets are inferred rather than emitting deprecated executor targets.\n addPlugin: true,\n });\n\n // Pin the inferred target names. The vite production build is exposed as\n // `bundle` (which produces the deployable artifact), leaving `build` as an\n // aggregator over lint/compile/test/bundle. vite's own typecheck is dropped\n // in favour of the tsc `compile`.\n updateJson(tree, 'nx.json', (nxJson) => {\n for (const plugin of nxJson.plugins ?? []) {\n if (typeof plugin === 'string') continue;\n if (plugin.plugin === '@nx/vite/plugin') {\n plugin.options = {\n ...plugin.options,\n buildTargetName: 'bundle',\n // Map both of vite's inferred dev-server targets onto `serve` so the\n // plugin doesn't emit a separate `dev`; we author our own `dev`\n // below running the local-dev vite mode.\n serveTargetName: 'serve',\n devTargetName: 'serve',\n previewTargetName: 'preview',\n serveStaticTargetName: 'serve-static',\n typecheckTargetName: 'vite:typecheck',\n };\n } else if (plugin.plugin === '@nx/vitest') {\n plugin.options = {\n ...plugin.options,\n testTargetName: 'test',\n };\n }\n }\n return nxJson;\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(websiteContentPath, 'src'));\n }\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n\n const targets = projectConfiguration.targets;\n\n const infra = schema.infra ?? 'cloudfront-s3';\n\n // Configure load-runtime-config target based on IaC provider (only when infra is not none)\n const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;\n\n if (iac === 'cdk') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx load-runtime-config ${fullyQualifiedName}'`,\n },\n options: {\n command: `aws s3 cp s3://\\`aws cloudformation describe-stacks --query \"Stacks[?starts_with(StackName, '${kebabCase(npmScopePrefix)}-')][].Outputs[] | [?contains(OutputKey, '${websiteNameClassName}WebsiteBucketName')].OutputValue\" --output text\\`/runtime-config.json \"{projectRoot}/public/runtime-config.json\"`,\n },\n };\n } else if (iac === 'terraform') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description:\n \"Load runtime config from most recently applied terraform env for dev purposes. Copies the runtime config from the Terraform dist directory to the website's public directory.\",\n },\n options: {\n command:\n 'node -e \"const fs=require(\\'fs\\');fs.mkdirSync(process.env.DEST_DIR,{recursive:true});fs.copyFileSync(process.env.SRC_FILE,process.env.DEST_FILE);\"',\n env: {\n SRC_FILE: 'dist/packages/common/terraform/runtime-config.json',\n DEST_DIR: `{projectRoot}/public`,\n DEST_FILE: `{projectRoot}/public/runtime-config.json`,\n },\n },\n };\n }\n\n if (!projectAlreadyExists) {\n targets['compile'] = {\n dependsOn: ['^build'],\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.app.json',\n cwd: '{projectRoot}',\n },\n };\n // bundle is the @nx/vite/plugin inferred `vite build` (writing to the\n // bundle dir configured in vite.config) — it produces the deployable\n // artifact. build aggregates lint/compile/test/bundle.\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test', 'bundle'],\n };\n\n // Run the website and its connected dependencies locally. Mirrors the\n // inferred `serve` target but with the local-dev vite mode.\n targets['dev'] = {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n command: 'vite --mode local-dev',\n cwd: '{projectRoot}',\n },\n };\n }\n\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n // Recorded here and read by the declaration's predicates, so the packages\n // added below are exactly the ones the version sync will own.\n const metadata: TsReactWebsiteMetadata = {\n ux,\n framework: 'react',\n infra,\n tailwind,\n tanstackRouter,\n // Undefined when no infrastructure was generated, so neither provider's\n // packages were added.\n ...(iac ? { iac } : {}),\n };\n addGeneratorMetadata(\n tree,\n projectConfiguration.name,\n REACT_WEBSITE_APP_GENERATOR_INFO,\n metadata,\n );\n\n await configureTsProject(\n tree,\n {\n dir: websiteContentPath,\n fullyQualifiedName,\n },\n DEPENDENCIES,\n );\n\n if (ux === 'shadcn') {\n await sharedShadcnGenerator(tree, DEPENDENCIES);\n }\n\n if (iac) {\n await sharedConstructsGenerator(\n tree,\n {\n iac,\n },\n DEPENDENCIES,\n );\n\n await addWebsiteInfra(tree, {\n iac,\n websiteProjectName: fullyQualifiedName,\n scopeAlias,\n websiteContentPath: joinPathFragments('dist', websiteContentPath),\n websiteNameKebabCase,\n websiteNameClassName,\n });\n }\n\n const projectConfig = readProjectConfiguration(tree, fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const sharedShadcnStylesImport = relative(\n joinPathFragments(libraryRoot, 'src'),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'src',\n 'styles',\n 'globals.css',\n ),\n )\n .split(sep)\n .join('/');\n const sharedShadcnTsconfigRef = relative(\n joinPathFragments(tree.root, websiteContentPath),\n joinPathFragments(\n tree.root,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'tsconfig.json',\n ),\n )\n .split(sep)\n .join('/');\n const templateOptions = {\n ...schema,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n tailwind,\n tanstackRouter,\n scopeAlias,\n sharedShadcnStylesImport,\n };\n tree.delete(joinPathFragments(libraryRoot, 'src', 'app'));\n const appCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/app/common',\n );\n const appTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/app/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree, // the virtual file system\n appCommonTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree, // the virtual file system\n appTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n if (tanstackRouter) {\n const routerCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/tanstack-router/common',\n );\n const routerTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/tanstack-router/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree,\n routerCommonTemplatePath,\n libraryRoot,\n templateOptions,\n {\n // User-editable source (and the TanStack-managed route tree) - preserve on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n routerTemplatePath,\n libraryRoot,\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n tree.delete(joinPathFragments(websiteContentPath, 'src', 'app.tsx'));\n }\n\n if (e2eTestRunner !== 'none') {\n const e2eFullyQualifiedName = `${fullyQualifiedName}-e2e`;\n const e2eRoot = readProjectConfiguration(tree, e2eFullyQualifiedName).root;\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, `./files/e2e/${e2eTestRunner}`), // path to the file templates\n e2eRoot, // destination path of the files\n { ...schema, ...names(fullyQualifiedName) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n await configureTsProject(\n tree,\n {\n fullyQualifiedName: e2eFullyQualifiedName,\n dir: e2eRoot,\n },\n DEPENDENCIES,\n );\n }\n const viteConfigPath = joinPathFragments(libraryRoot, 'vite.config.mts');\n\n if (tree.exists(viteConfigPath)) {\n // Add Tanstack Router import if enabled\n if (tanstackRouter) {\n await addDestructuredImport(\n tree,\n viteConfigPath,\n ['tanstackRouter'],\n '@tanstack/router-plugin/vite',\n );\n\n await addDestructuredImport(tree, viteConfigPath, ['resolve'], 'path');\n }\n\n // Add TailwindCSS import if enabled\n if (tailwind) {\n await addSingleImport(\n tree,\n viteConfigPath,\n 'tailwindcss',\n '@tailwindcss/vite',\n );\n }\n\n // Update build.outDir. The inferred `vite build` target writes here, so\n // point it at the bundle dir the website infrastructure consumes.\n const outDir = joinPathFragments(\n getRelativePathToRoot(tree, fullyQualifiedName),\n 'dist',\n websiteContentPath,\n 'bundle',\n );\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`build: { $bprops }\\` where { $bprops <: contains \\`outDir: $_\\` => \\`outDir: '${outDir}'\\` }`,\n );\n\n // Add plugins to the plugins array\n if (tanstackRouter) {\n // Prepend tanstackRouter (must be first plugin) — rewrite works for both single/multi-element\n await applyGritQL(\n tree,\n viteConfigPath,\n \"`plugins: [$items]` => `plugins: [tanstackRouter({ routesDirectory: resolve(import.meta.dirname, 'src/routes'), generatedRouteTree: resolve(import.meta.dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await appendToArrayViaGritQL(\n tree,\n viteConfigPath,\n 'plugins:',\n 'tailwindcss()',\n { scope: 'defineConfig($_)' },\n );\n }\n\n // Use Vite's native tsconfig paths resolution (replaces vite-tsconfig-paths).\n // `dedupe` forces a single copy of react/react-dom into the bundle: each\n // project declares its own react dependency, so without this a workspace\n // library's hoisted copy can produce a second React instance and the\n // \"Invalid hook call\" runtime crash.\n await applyGritQL(\n tree,\n viteConfigPath,\n \"or { `defineConfig(() => ({ $props }))` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` }, `defineConfig({ $props })` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` } }\",\n );\n\n // Add define: { global: {} } to the config (handles both callback and direct forms)\n await applyGritQL(\n tree,\n viteConfigPath,\n 'or { `defineConfig(() => ({ $props }))` where { $props <: not contains `define`, $props += `define: { global: {} }` }, `defineConfig({ $props })` where { $props <: not contains `define`, $props += `define: { global: {} }` } }',\n );\n }\n\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n moduleResolution: 'Bundler',\n module: 'Preserve',\n },\n }),\n );\n const outDirToRootRelativePath = relative(\n joinPathFragments(tree.root, websiteContentPath),\n tree.root,\n );\n const distDir = joinPathFragments(\n outDirToRootRelativePath,\n 'dist',\n websiteContentPath,\n 'tsc',\n );\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.app.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n outDir: distDir,\n tsBuildInfoFile: joinPathFragments(distDir, 'tsconfig.lib.tsbuildinfo'),\n lib: ['DOM'],\n },\n references:\n ux === 'shadcn'\n ? [\n ...(tsconfig.references ?? []).filter(\n (ref) => ref.path !== sharedShadcnTsconfigRef,\n ),\n {\n path: sharedShadcnTsconfigRef,\n },\n ]\n : tsconfig.references,\n }),\n );\n\n addTsDependencies(tree, DEPENDENCIES, { metadata, projectRoot: libraryRoot });\n\n // @nx/react's applicationGenerator seeds react/react-dom into the root\n // manifest. The website now declares its own pinned versions, so drop the\n // root copies: without catalogs (npm) the root's floating range resolves to\n // a different version than the website's pin, installing a second React and\n // producing the \"Invalid hook call\" runtime crash.\n removeDependenciesFromPackageJson(tree, ['react', 'react-dom'], []);\n\n await addGeneratorMetricsIfApplicable(tree, [\n REACT_WEBSITE_APP_GENERATOR_INFO,\n ]);\n\n // TanStack Router's vite plugin owns this website's route tree and rewrites it\n // in its own (unformatted) shape whenever the config is loaded — including when\n // Nx computes the project graph — so formatting it here would only make\n // generation non-idempotent. The vended biome config excludes `**/*.gen.*`, so\n // the workspace's own `format` target leaves it alone too.\n await formatFilesInSubtree(tree, undefined, {\n ignore: tanstackRouter\n ? [joinPathFragments(libraryRoot, 'src', 'routeTree.gen.ts')]\n : [],\n });\n // The generated vite.config.mts imports these, and Nx's inferred `@nx/vite`\n // plugin loads that config when computing the project graph — so they must be\n // installed even if the caller would otherwise prefer to defer.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: [\n ...(tailwind ? (['@tailwindcss/vite'] as const) : []),\n ...(tanstackRouter ? (['@tanstack/router-plugin'] as const) : []),\n ],\n });\n}\nexport default tsReactWebsiteGenerator;\n"],"names":["generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","appendToArrayViaGritQL","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","SHADCN_DEPENDENCIES","sharedShadcnGenerator","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","py","SUPPORTED_UX_PROVIDERS","REACT_WEBSITE_APP_GENERATOR_INFO","filename","tsReactWebsiteGenerator","tree","schema","Error","npmScopePrefix","scopeAlias","websiteNameClassName","websiteNameKebabCase","fullyQualifiedName","websiteContentPath","directory","subDirectory","projectAlreadyExists","exists","e2eTestRunner","routing","linter","bundler","unitTestRunner","useProjectJson","style","addPlugin","nxJson","plugin","plugins","options","buildTargetName","serveTargetName","devTargetName","previewTargetName","serveStaticTargetName","typecheckTargetName","testTargetName","delete","projectConfiguration","targets","infra","iac","undefined","executor","metadata","description","exec","command","env","SRC_FILE","DEST_DIR","DEST_FILE","dependsOn","outputs","cwd","continuous","framework","dir","websiteProjectName","projectConfig","libraryRoot","sharedShadcnStylesImport","split","join","sharedShadcnTsconfigRef","templateOptions","pkgMgrCmd","appCommonTemplatePath","dirname","appTemplatePath","toLowerCase","overwriteStrategy","KeepExisting","routerCommonTemplatePath","routerTemplatePath","e2eFullyQualifiedName","e2eRoot","viteConfigPath","outDir","scope","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AACjD,SAASC,QAAQ,EAAEC,GAAG,QAAQ,OAAO;AACrC,SAASC,iBAAiB,QAAQ,qCAAkC;AACpE,SACEC,qBAAqB,EACrBC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QACN,wBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,cAAc,QACT,0CAAuC;AAC9C,SAASC,oBAAoB,QAAQ,2BAAwB;AAC7D,SAASC,UAAU,QAAQ,wBAAqB;AAChD,SAASC,mBAAmB,QAAQ,4BAAyB;AAC7D,SAASC,+BAA+B,QAAQ,4BAAyB;AACzE,SAASC,SAAS,EAAEC,WAAW,EAAEC,WAAW,QAAQ,0BAAuB;AAC3E,SAASC,iBAAiB,QAAQ,8BAA2B;AAC7D,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,uBAAoB;AAC3B,SAASC,cAAc,QAAQ,2BAAwB;AACvD,SAASC,qBAAqB,QAAQ,0BAAuB;AAC7D,SAASC,gCAAgC,QAAQ,gCAA6B;AAC9E,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,sCAAmC;AAC1C,SAEEC,YAAY,EACZC,iBAAiB,QACZ,gDAA6C;AACpD,SACEC,mBAAmB,EACnBC,qBAAqB,QAChB,kCAA+B;AACtC,SACEC,eAAe,EACfC,kCA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AAgE;IAChE,OAAO,IACL3F,oBAAoBoC,MAAMC,OAAOwF,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;YACzBC,kBAAkB;mBACZjG,WAAY;oBAAC;iBAAoB,GAAa,EAAE;mBAChDD,iBAAkB;oBAAC;iBAA0B,GAAa,EAAE;aACjE;QACH;AACJ;AACA,eAAeM,wBAAwB"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/ import { generateFiles, joinPathFragments, OverwriteStrategy } from "@nx/devkit";
|
|
5
5
|
import pyProjectGenerator, { getPyProjectDetails } from "../../py/project/generator.js";
|
|
6
6
|
import tsProjectGenerator from "../../ts/lib/generator.js";
|
|
7
|
-
import { addStarExport, applyGritQL, matchGritQL } from "../ast.js";
|
|
7
|
+
import { addStarExport, appendToArrayViaGritQL, applyGritQL, matchGritQL } from "../ast.js";
|
|
8
8
|
import { forDependencies } from "../declared-dependencies.js";
|
|
9
9
|
import { addDependenciesToPackageJson } from "../dependencies.js";
|
|
10
10
|
import { esmVars } from "../module-format.js";
|
|
@@ -439,14 +439,10 @@ const emitPy = (tree, templateDir)=>generateFiles(tree, joinPathFragments(import
|
|
|
439
439
|
if (await matchGritQL(tree, filePath, py(`\`${clientVarName}.list_tools_sync()\``))) {
|
|
440
440
|
return;
|
|
441
441
|
}
|
|
442
|
-
await
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
} else {
|
|
447
|
-
$old <: \`[$items]\` where { $items += \`, *${clientVarName}.list_tools_sync()\` }
|
|
448
|
-
}
|
|
449
|
-
}`));
|
|
442
|
+
await appendToArrayViaGritQL(tree, filePath, 'tools=', `*${clientVarName}.list_tools_sync()`, {
|
|
443
|
+
skipIfContains: clientVarName,
|
|
444
|
+
language: 'py'
|
|
445
|
+
});
|
|
450
446
|
};
|
|
451
447
|
/**
|
|
452
448
|
* Create the client in get_agent and enter it in the `with` block.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/agent-connection/agent-connection.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 pyProjectGenerator, {\n getPyProjectDetails,\n} from '../../py/project/generator';\nimport tsProjectGenerator from '../../ts/lib/generator';\nimport { addStarExport, applyGritQL, matchGritQL } from '../ast';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n type MustDeclarePy,\n} from '../declared-dependencies';\nimport { addDependenciesToPackageJson } from '../dependencies';\nimport { esmVars } from '../module-format';\nimport { addDependenciesToPyProjectToml } from '../py';\nimport {\n type IPyDepVersion,\n type ITsDepVersion,\n withVersions,\n} from '../versions';\n\n/** TypeScript dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_DEPENDENCIES = [\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/credential-providers' },\n { name: 'aws4fetch' },\n { name: '@modelcontextprotocol/sdk' },\n { name: '@a2a-js/sdk' },\n { name: '@strands-agents/sdk' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** Python dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_PY_DEPENDENCIES = [\n { name: 'aws-lambda-powertools' },\n { name: 'strands-agents' },\n] as const satisfies readonly { name: IPyDepVersion }[];\n\ntype AgentConnectionPyDependency =\n (typeof AGENT_CONNECTION_PY_DEPENDENCIES)[number]['name'];\n\n/** Prefix a GritQL pattern with `language python` */\nconst py = (pattern: string) => `language python\\n${pattern}`;\n\nconst AGENT_CONNECTION_DIR = 'agent-connection';\nconst PACKAGES_DIR = 'packages';\nconst COMMON_DIR = 'common';\n\nexport const AGENT_CONNECTION_PROJECT_DIR = joinPathFragments(\n PACKAGES_DIR,\n COMMON_DIR,\n AGENT_CONNECTION_DIR,\n);\n\nconst PY_AGENT_CONNECTION_NAME = 'agent_connection';\n\n/**\n * Get the directory of the shared Python agent-connection project.\n */\nexport function getPythonAgentConnectionProjectDir(tree: Tree): string {\n const { dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return dir;\n}\n\n/**\n * Get the Python module name of the shared agent-connection project.\n */\nexport function getPythonAgentConnectionModuleName(tree: Tree): string {\n const { normalizedModuleName } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return normalizedModuleName;\n}\n\n/**\n * Get the shared agent-connection project as `{ name, root }`, suitable for\n * passing to {@link addWorkspaceDependencyToPyProject} (which derives the\n * dependency's PEP 503 distribution name from the project itself, so callers\n * never construct the name).\n */\nexport function getPythonAgentConnectionProject(tree: Tree): {\n name: string;\n root: string;\n} {\n const { fullyQualifiedName, dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return { name: fullyQualifiedName, root: dir };\n}\n\n/**\n * The connection protocols an agent framework can connect over. Each maps to a\n * framework-agnostic Layer-0/1 template directory plus a per-framework Layer-2\n * client directory (see `FRAMEWORKS`).\n */\nexport type ConnectionProtocol = 'mcp' | 'gateway' | 'a2a';\n\n/**\n * The agent frameworks we can generate connection clients for. Adding a new\n * framework is an additive change: append an entry to `FRAMEWORKS` with its\n * Layer-2 template directories and dependencies — the framework-agnostic\n * Layer-0/1 (`core-auth`, `core-shared`, the per-protocol transports/configs)\n * is reused unchanged.\n */\nexport type AgentFramework = 'strands' | 'langchain';\n\n/**\n * Resolve an agent component's framework, defaulting to `strands`. Connection\n * generators dispatch on the returned framework to pick the matching templates\n * and agent.py/agent.ts transforms.\n */\nexport function resolveAgentFramework(\n framework: string | undefined,\n): AgentFramework {\n return framework === 'langchain' ? 'langchain' : 'strands';\n}\n\n/**\n * Framework-agnostic Layer-1 templates, keyed by protocol. These resolve the\n * endpoint and build the signed transport/client-config; they contain no\n * framework dependency.\n */\nconst TS_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'core-mcp',\n gateway: 'core-gateway',\n a2a: 'core-a2a',\n};\nconst PY_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'py-core-mcp',\n gateway: 'py-core-gateway',\n a2a: 'py-core-a2a',\n};\n\n/**\n * A re-export the framework base emits into the agent-connection module's\n * `__init__.py` (the agent server entry point imports these by name).\n */\ninterface BaseReExport {\n fromModule: string;\n importName: string;\n}\n\n/**\n * A framework's Layer-2 templates for one language. `base` (optional) holds the\n * helpers every connection of that framework needs (error logging, per-session\n * agent cache); `baseReExports` lists what those helpers expose at the module\n * root. `protocols` maps each *supported* protocol to the thin client that wraps\n * the matching Layer-1 transport/config in the framework's client type.\n *\n * A framework whose Layer-2 needs no base helpers (e.g. LangChain, whose AG-UI\n * foundation reuses only the framework-agnostic session context) omits `base`\n * and leaves `baseReExports` empty.\n *\n * A protocol absent from `protocols` is not supported by that framework in that\n * language — callers must check before emitting. `deps` are the extra package\n * dependencies the base helpers require (per-connection client deps are added\n * by the connection generators, not here).\n */\ninterface FrameworkLanguageTemplates<Dep extends string> {\n base?: string;\n baseReExports: BaseReExport[];\n protocols: Partial<Record<ConnectionProtocol, string>>;\n deps: Dep[];\n}\n\n/**\n * Per-framework Layer-2 templates. Support is asymmetric by design: a framework\n * may target only one language (`ts`/`py` is optional) and only a subset of\n * protocols. Adding a framework — or extending an existing one to a new\n * language/protocol — is an additive change to this registry.\n */\ninterface FrameworkTemplates {\n ts?: FrameworkLanguageTemplates<string>;\n py?: FrameworkLanguageTemplates<AgentConnectionPyDependency>;\n}\n\nconst FRAMEWORKS: Record<AgentFramework, FrameworkTemplates> = {\n strands: {\n ts: {\n base: 'core-strands/base',\n baseReExports: [\n {\n fromModule: './core/with-session-id-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/model-errors-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/tool-errors-strands.js',\n importName: '*',\n },\n ],\n protocols: {\n mcp: 'core-strands/mcp',\n gateway: 'core-strands/gateway',\n a2a: 'core-strands/a2a',\n },\n deps: [],\n },\n py: {\n base: 'py-core-strands/base',\n baseReExports: [\n {\n fromModule: '.core.with_session_id_strands',\n importName: 'with_session_id',\n },\n {\n fromModule: '.core.model_errors_strands',\n importName: 'log_model_errors',\n },\n {\n fromModule: '.core.tool_errors_strands',\n importName: 'log_tool_errors',\n },\n ],\n protocols: {\n mcp: 'py-core-strands/mcp',\n gateway: 'py-core-strands/gateway',\n a2a: 'py-core-strands/a2a',\n },\n deps: ['strands-agents'],\n },\n },\n langchain: {\n // LangChain is supported for Python agents only (the TypeScript LangChain\n // agent foundation has no in-process AG-UI <-> LangGraph adapter, so it is\n // not scaffolded — see ts#agent). Its Layer-2 clients stay usable after\n // agent construction, so there is no base helper layer (no model-error\n // logger / per-session agent cache) and no strands-agents dependency — its\n // AG-UI foundation reuses only the framework-agnostic session context, and\n // its A2A client drives the a2a SDK directly rather than wrapping Strands'\n // A2AAgent. The per-connection adapter dependency (langchain-mcp-adapters /\n // a2a-sdk) is added by the connection generators.\n py: {\n baseReExports: [],\n protocols: {\n mcp: 'py-core-langchain/mcp',\n gateway: 'py-core-langchain/gateway',\n a2a: 'py-core-langchain/a2a',\n },\n deps: [],\n },\n },\n};\n\n/** Resolve a framework's templates for a language + protocol, or throw. */\nfunction frameworkLanguage<L extends 'ts' | 'py'>(\n framework: AgentFramework,\n language: L,\n protocol: ConnectionProtocol,\n): NonNullable<FrameworkTemplates[L]> & { protocol: string } {\n const lang = FRAMEWORKS[framework][language];\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n const protocolDir = lang.protocols[protocol];\n if (!protocolDir) {\n throw new Error(\n `The '${framework}' framework does not support ${protocol} connections for ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n return { ...lang, protocol: protocolDir } as NonNullable<\n FrameworkTemplates[L]\n > & { protocol: string };\n}\n\n/** Protocols whose Layer-1 needs the shared MCP transport (`core-shared`). */\nconst MCP_TRANSPORT_PROTOCOLS: ConnectionProtocol[] = ['mcp', 'gateway'];\n\nconst tsCoreDir = () =>\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'core');\n\n/**\n * Runtime dependencies each TypeScript core template directory imports. Emitting\n * a template also declares its dependencies in the agent-connection project's\n * package.json so the `noUndeclaredDependencies` lint rule passes.\n */\nconst TS_TEMPLATE_DEPS: Record<\n string,\n (typeof AGENT_CONNECTION_DEPENDENCIES)[number]['name'][]\n> = {\n 'core-runtime-config': ['@aws-lambda-powertools/parameters'],\n 'core-auth': ['@aws-sdk/credential-providers', 'aws4fetch'],\n 'core-shared': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-mcp': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-gateway': [\n '@aws-sdk/credential-providers',\n '@modelcontextprotocol/sdk',\n ],\n 'core-a2a': ['@aws-sdk/credential-providers', '@a2a-js/sdk'],\n 'core-strands/base': ['@strands-agents/sdk'],\n 'core-strands/mcp': ['@strands-agents/sdk'],\n 'core-strands/gateway': ['@strands-agents/sdk'],\n 'core-strands/a2a': ['@strands-agents/sdk'],\n};\n\nconst emitTs = (\n tree: Tree,\n templateDir: string,\n declaration: DependencyDeclaration,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n tsCoreDir(),\n { ...esmVars(tree) },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n const deps = TS_TEMPLATE_DEPS[templateDir];\n if (deps?.length) {\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n deps,\n ),\n {},\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'package.json'),\n );\n }\n};\n\n/**\n * Ensure the shared TypeScript agent-connection project exists and has the\n * framework-agnostic core helpers (runtime-config loader, session context).\n * Per-connection generators emit their own protocol + framework client\n * templates via `addTypeScriptCoreClient`.\n */\nexport async function ensureTypeScriptAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n): Promise<void> {\n const projectJsonPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'project.json',\n );\n if (!tree.exists(projectJsonPath)) {\n await tsProjectGenerator(tree, {\n name: AGENT_CONNECTION_DIR,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n emitTs(tree, 'core-runtime-config', declaration);\n\n // Re-export session-context helpers so agent server entry points can set the\n // current session on each inbound request without pulling in internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/session-context.js',\n );\n\n // Re-export the runtime-config loader so agent server entry points can read\n // their own connected resources (e.g. session storage) without pulling in\n // internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/runtime-config.js',\n );\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the agent-connection project and re-export them. The agent\n * server entry point imports these regardless of whether any connection client\n * is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addTypeScriptCoreClient`.\n */\nexport async function addTypeScriptFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].ts;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support TypeScript agents.`,\n );\n }\n if (lang.base) {\n emitTs(tree, lang.base, declaration);\n }\n\n const indexPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'src',\n 'index.ts',\n );\n for (const reExport of lang.baseReExports) {\n await addStarExport(tree, indexPath, reExport.fromModule);\n }\n}\n\n/**\n * Emit the TypeScript client templates for a connection protocol and agent\n * framework into the agent-connection project's `src/core/` directory. Safe to\n * call multiple times — `KeepExisting` preserves customised files.\n *\n * Layers emitted:\n * - Layer 0 `core-auth` (signed fetch + endpoint resolution) — always\n * - Layer 1 `core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addTypeScriptCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'ts', protocol);\n\n emitTs(tree, 'core-auth', declaration);\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitTs(tree, 'core-shared', declaration);\n }\n emitTs(tree, TS_PROTOCOL_TEMPLATES[protocol], declaration);\n\n // Framework Layer 2: base helpers (re-exported for the agent server) + the\n // thin protocol client.\n await addTypeScriptFrameworkBase(\n tree,\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n framework,\n );\n emitTs(tree, fw.protocol, declaration);\n}\n\n/**\n * Ensure the shared Python agent-connection project exists.\n * Only creates the project shell — per-connection generators are responsible\n * for emitting their own core client templates.\n */\nexport async function ensurePythonAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n): Promise<void> {\n const projectDir = getPythonAgentConnectionProjectDir(tree);\n const moduleName = getPythonAgentConnectionModuleName(tree);\n const projectJsonPath = joinPathFragments(projectDir, 'project.json');\n\n if (!tree.exists(projectJsonPath)) {\n // Create the Python project using the standard py#project generator\n await pyProjectGenerator(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n type: 'library',\n });\n }\n\n const moduleDir = joinPathFragments(projectDir, moduleName);\n\n // Ensure core/__init__.py exists\n const coreDir = joinPathFragments(moduleDir, 'core');\n if (!tree.exists(joinPathFragments(coreDir, '__init__.py'))) {\n tree.write(joinPathFragments(coreDir, '__init__.py'), '');\n }\n\n // Ensure app/__init__.py exists\n const appInitPath = joinPathFragments(moduleDir, 'app', '__init__.py');\n if (!tree.exists(appInitPath)) {\n tree.write(appInitPath, '');\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'py-core-runtime-config'),\n coreDir,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Re-export the session id context so agent server entry points can set the\n // current session on each inbound request without importing internals.\n const moduleInitPath = joinPathFragments(moduleDir, '__init__.py');\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'get_current_session_id',\n );\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'session_id_context',\n );\n\n // The runtime-config loader reads AppConfig via aws-lambda-powertools.\n addDependenciesToPyProjectToml(\n tree,\n projectDir,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n ['aws-lambda-powertools'],\n );\n}\n\nconst pyCoreDir = (tree: Tree) =>\n joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n 'core',\n );\n\nconst emitPy = (tree: Tree, templateDir: string) =>\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n pyCoreDir(tree),\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n/**\n * Ensure the shared Python agent-connection project has\n * `s3_checkpoint_saver_langchain.py` — a vendored `S3CheckpointSaver`\n * (from `langgraph-checkpoint-s3`, MIT licensed) that LangChain agents with\n * `session: 's3'` import from directly (`.core.s3_checkpoint_saver_langchain`),\n * mirroring how they import `.core.runtime_config`. Vendored rather than\n * installed as a dependency, and shared rather than per-agent, since it has\n * no agent-specific templating.\n */\nexport function ensureLangchainS3CheckpointSaver(tree: Tree): void {\n emitPy(tree, 'py-core-langchain/s3');\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the Python agent-connection project and re-export them.\n * The agent server entry point imports these regardless of whether a connection\n * client is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addPythonCoreClient`.\n */\nexport async function addPythonFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].py;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support Python agents.`,\n );\n }\n if (lang.base) {\n emitPy(tree, lang.base);\n }\n\n const moduleInitPath = joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n '__init__.py',\n );\n for (const reExport of lang.baseReExports) {\n await addPythonReExport(\n tree,\n moduleInitPath,\n reExport.fromModule,\n reExport.importName,\n );\n }\n\n if (lang.deps.length > 0) {\n addDependenciesToPyProjectToml(\n tree,\n getPythonAgentConnectionProjectDir(tree),\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n lang.deps,\n );\n }\n}\n\n/**\n * Emit the Python client templates for a connection protocol and agent\n * framework into the agent-connection project's core directory.\n *\n * Layers emitted:\n * - Layer 0 `py-core-auth` (SigV4 httpx.Auth, session auth, endpoints) — always\n * - Layer 1 `py-core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addPythonCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'py', protocol);\n\n emitPy(tree, 'py-core-auth');\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitPy(tree, 'py-core-shared');\n }\n emitPy(tree, PY_PROTOCOL_TEMPLATES[protocol]);\n\n // Framework Layer 2: base helpers + the thin protocol client.\n await addPythonFrameworkBase(\n tree,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n framework,\n );\n emitPy(tree, fw.protocol);\n}\n\n/**\n * Patch a TypeScript agent.ts to create a connection client and register it\n * in the Agent's tools. Used by the MCP and gateway connection generators —\n * the client class must expose a static async `create()` returning a value\n * accepted by `Agent.tools` (e.g. an `McpClient`).\n */\nexport async function addTypeScriptClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n const clientCreationStmt = `const ${clientVarName} = await ${clientClassName}.create();`;\n\n // Transform the arrow function that contains `new Agent`:\n // - Expression body: wrap in block with client creation and return\n // - Block body: prepend client creation statement\n await applyGritQL(\n tree,\n agentFilePath,\n `or { \\`async ($p) => new Agent($args)\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n return new Agent($args);\n}\\` where { $program <: not contains \\`${clientClassName}.create\\` }, \\`async ($p) => { $body }\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n $body\n}\\` where { $body <: contains \\`new Agent($_)\\`, $program <: not contains \\`${clientClassName}.create\\` } }`,\n );\n\n // Prepend the client to the tools array\n await applyGritQL(\n tree,\n agentFilePath,\n `\\`tools: [$items]\\` => \\`tools: [${clientVarName}, $items]\\` where { $items <: within \\`new Agent($_)\\`, $items <: not contains \\`${clientVarName}\\` }`,\n );\n}\n\n/**\n * Patch a Python agent.py to create a context-managed connection client,\n * enter it in the `with` block around `yield Agent(...)`, and spread its\n * `list_tools_sync()` into the Agent's tools. Used by the MCP and gateway\n * connection generators — the client class must expose a static `create()`\n * returning a context manager with `list_tools_sync()` (e.g. an `MCPClient`).\n */\nasync function addPythonClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonClientTools(tree, agentFilePath, clientVarName);\n await addPythonClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Append `*<clientVarName>.list_tools_sync()` to the Agent's tools list.\n */\nconst addPythonClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(\n tree,\n filePath,\n py(`\\`${clientVarName}.list_tools_sync()\\``),\n )\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: not contains \\`${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}.list_tools_sync()]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}.list_tools_sync()\\` }\n }\n}`),\n );\n};\n\n/**\n * Create the client in get_agent and enter it in the `with` block.\n *\n * First connection: rewrites `def get_agent` to wrap the body in a with\n * block. Subsequent connections: adds to the existing with items and\n * prepends the creation line.\n */\nconst addPythonClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n // Try the \"add to existing with block\" pattern first.\n // If it succeeds, there was already a with block from a previous connection.\n const addedToWith = await applyGritQL(\n tree,\n filePath,\n py(`\\`with ($items,): $body\\` where {\n $items <: not contains \\`${clientVarName}\\`,\n $items += \\`, ${clientVarName}\\`\n}`),\n );\n\n if (addedToWith) {\n // Subsequent connection — prepend the creation line to the function body\n // (a single anchor, so the line is inserted exactly once).\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n return;\n }\n\n // First connection — wrap the existing `def get_agent` body in a single\n // `with (<var>,):` block.\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n with (\n ${clientVarName},\n ):\n $body\\``),\n );\n};\n\n/**\n * Patch a LangChain agent.py to load connection tools and spread them into the\n * `create_agent(...)` tools list. Used by the MCP and gateway connection\n * generators when the source agent uses the `langchain` framework — the client\n * class must expose a static `create()` returning a `list[BaseTool]`. The tools\n * come from langchain-mcp-adapters' `MultiServerMCPClient`, which keeps the\n * connection config on each tool and opens a fresh MCP session per call, so the\n * tools stay usable after `get_agent` returns — no `with` block is needed.\n * Mirrors {@link addPythonClientToAgent} for the Strands shape.\n */\nasync function addPythonLangchainClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonLangchainClientTools(tree, agentFilePath, clientVarName);\n await addPythonLangchainClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Spread `*<clientVarName>` into the `create_agent(...)` tools list.\n *\n * Scoped via `$old <: within \\`create_agent($_)\\`` so only the agent's own\n * tools= keyword argument is touched (not an unrelated function with a\n * `tools=` parameter).\n */\nconst addPythonLangchainClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: within \\`create_agent($_)\\`,\n $old <: not contains \\`*${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}\\` }\n }\n}`),\n );\n};\n\n/**\n * Prepend `<clientVarName> = <clientClassName>.create()` to the get_agent body\n * (which loads the connection's tools). No `with` block — the LangChain client\n * hands langchain-mcp-adapters a connection config, so each tool opens its own\n * MCP session per call and the tools are safe to use after get_agent returns.\n * Idempotent via the `not contains <clientClassName>.create` guard.\n */\nconst addPythonLangchainClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`create_agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n};\n\n/**\n * Per-framework naming + template layout for a Python per-connection client.\n * Every py#agent connection generator (mcp, gateway, a2a) names its client\n * class `<Name>Client<suffix>`, its module `<name>_client_<suffix>`, and reads\n * the per-connection app-client template from a per-framework sub-path of its\n * own `files/` dir — all of which vary only by framework, so they live here as\n * one source of truth.\n *\n * Keyed by {@link AgentFramework} rather than a boolean so a third framework is\n * an additive entry here — never another `if (isLangchain)` branch in each\n * generator.\n */\nexport interface PyClientNaming {\n /** Class-name suffix on the per-connection app client (`<Name>Client<suffix>`). */\n clientClassSuffix: string;\n /** Module/file-name suffix on the per-connection app client (`<name>_client_<suffix>`). */\n clientModuleSuffix: string;\n /**\n * Sub-path, under a connection generator's `files/` dir, of the per-connection\n * app client template for this framework. Every connection generator lays its\n * templates out the same way, so this resolves against any of them.\n */\n appTemplateSubdir: string;\n}\n\nexport const PY_CLIENT_NAMING: Record<AgentFramework, PyClientNaming> = {\n strands: {\n clientClassSuffix: 'Strands',\n clientModuleSuffix: 'strands',\n appTemplateSubdir: joinPathFragments('agent-connection', 'app'),\n },\n langchain: {\n clientClassSuffix: 'LangChain',\n clientModuleSuffix: 'langchain',\n appTemplateSubdir: joinPathFragments(\n 'langchain',\n 'agent-connection',\n 'app',\n ),\n },\n};\n\n/**\n * How an MCP-family connection (an MCP server or an AgentCore Gateway, both of\n * which expose tools over MCP) is wired into a Python agent of a given\n * framework. The mcp-connection and gateway-connection generators share this:\n * they differ only in the metadata of the thing being connected, not in how\n * the framework's client is shaped or spliced into agent.py. A2A connections\n * wire tools differently, so they reuse only {@link PY_CLIENT_NAMING}.\n */\nexport interface PyMcpFamilyConnection extends PyClientNaming {\n /** Extra Python deps this framework's MCP-family client needs (beyond the shared transport). */\n deps: IPyDepVersion[];\n /**\n * Splice the per-connection client into the agent's `get_agent` in agent.py.\n * Strands enters a context-managed `MCPClient` and spreads `list_tools_sync()`;\n * LangChain loads `BaseTool`s and spreads them into `create_agent(...)`.\n */\n wireClientIntoAgent: (\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n ) => Promise<void>;\n}\n\nexport const PY_MCP_FAMILY_CONNECTIONS: Record<\n AgentFramework,\n PyMcpFamilyConnection\n> = {\n strands: {\n ...PY_CLIENT_NAMING.strands,\n deps: [],\n wireClientIntoAgent: addPythonClientToAgent,\n },\n langchain: {\n ...PY_CLIENT_NAMING.langchain,\n // langchain-mcp-adapters backs the LangChain client; it must not pull Strands in.\n deps: ['langchain-mcp-adapters'],\n wireClientIntoAgent: addPythonLangchainClientToAgent,\n },\n};\n\n/**\n * Add a re-export to the Python agent-connection module's __init__.py.\n * Equivalent to addStarExport for TS.\n * Uses `__all__` to mark re-exports as public (satisfies ruff F401).\n * Uses GritQL for AST-aware transforms where possible.\n */\nexport async function addPythonReExport(\n tree: Tree,\n initFilePath: string,\n fromModule: string,\n importName: string,\n): Promise<void> {\n // Check if already exported\n if (await matchGritQL(tree, initFilePath, `\\`${importName}\\``)) {\n return;\n }\n\n const importLine = `from ${fromModule} import ${importName}`;\n const allEntry = `\"${importName}\"`;\n\n // If there's already an import from the same module, merge into its name list\n // (ruff I001 rejects two `from X import ...` lines for the same module).\n const mergedImport = await applyGritQL(\n tree,\n initFilePath,\n py(`\\`from ${fromModule} import $names\\` where {\n $names <: not contains \\`${importName}\\`,\n $names += \\`, ${importName}\\`\n}`),\n );\n\n if (mergedImport) {\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // Try to append import after existing import using +=\n const appendedImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`from $mod import $name\\` as $stmt where {\n $program <: not contains \\`${importName}\\`,\n $stmt += \\`\\n${importLine}\\`\n}`,\n ),\n );\n\n if (appendedImport) {\n // Also append to existing __all__\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // No existing imports — first re-export. Try to anchor after docstring.\n const anchoredImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`\"\"\"Automatically generated by Nx.\"\"\"\\` as $doc => \\`$doc\\n${importLine}\\n\\n__all__ = [${allEntry}]\\``,\n ),\n );\n\n if (!anchoredImport) {\n // Completely empty file or no docstring — write directly\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n }\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","pyProjectGenerator","getPyProjectDetails","tsProjectGenerator","addStarExport","applyGritQL","matchGritQL","forDependencies","addDependenciesToPackageJson","esmVars","addDependenciesToPyProjectToml","withVersions","AGENT_CONNECTION_DEPENDENCIES","name","AGENT_CONNECTION_PY_DEPENDENCIES","py","pattern","AGENT_CONNECTION_DIR","PACKAGES_DIR","COMMON_DIR","AGENT_CONNECTION_PROJECT_DIR","PY_AGENT_CONNECTION_NAME","getPythonAgentConnectionProjectDir","tree","dir","directory","getPythonAgentConnectionModuleName","normalizedModuleName","getPythonAgentConnectionProject","fullyQualifiedName","root","resolveAgentFramework","framework","TS_PROTOCOL_TEMPLATES","mcp","gateway","a2a","PY_PROTOCOL_TEMPLATES","FRAMEWORKS","strands","ts","base","baseReExports","fromModule","importName","protocols","deps","langchain","frameworkLanguage","language","protocol","lang","Error","protocolDir","MCP_TRANSPORT_PROTOCOLS","tsCoreDir","TS_TEMPLATE_DEPS","emitTs","templateDir","declaration","dirname","overwriteStrategy","KeepExisting","length","ensureTypeScriptAgentConnectionProject","projectJsonPath","exists","addTypeScriptFrameworkBase","indexPath","reExport","addTypeScriptCoreClient","fw","includes","ensurePythonAgentConnectionProject","projectDir","moduleName","type","moduleDir","coreDir","write","appInitPath","moduleInitPath","addPythonReExport","pyCoreDir","emitPy","ensureLangchainS3CheckpointSaver","addPythonFrameworkBase","addPythonCoreClient","addTypeScriptClientToAgent","agentFilePath","clientClassName","clientVarName","clientCreationStmt","addPythonClientToAgent","addPythonClientTools","addPythonClientToGetAgent","filePath","addedToWith","addPythonLangchainClientToAgent","addPythonLangchainClientTools","addPythonLangchainClientToGetAgent","PY_CLIENT_NAMING","clientClassSuffix","clientModuleSuffix","appTemplateSubdir","PY_MCP_FAMILY_CONNECTIONS","wireClientIntoAgent","initFilePath","importLine","allEntry","mergedImport","appendedImport","anchoredImport"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,OAAOC,sBACLC,mBAAmB,QACd,gCAA6B;AACpC,OAAOC,wBAAwB,4BAAyB;AACxD,SAASC,aAAa,EAAEC,WAAW,EAAEC,WAAW,QAAQ,YAAS;AACjE,SAEEC,eAAe,QAGV,8BAA2B;AAClC,SAASC,4BAA4B,QAAQ,qBAAkB;AAC/D,SAASC,OAAO,QAAQ,sBAAmB;AAC3C,SAASC,8BAA8B,QAAQ,WAAQ;AACvD,SAGEC,YAAY,QACP,iBAAc;AAErB,oFAAoF,GACpF,OAAO,MAAMC,gCAAgC;IAC3C;QAAEC,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MACAoF,cACA5F,GACE,CAAC,4DAA4D,EAAE6F,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IAI5G,IAAI,CAACG,gBAAgB;QACnB,yDAAyD;QACzDzF,KAAKwD,KAAK,CAAC4B,cAAc,GAAGC,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IACvE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/agent-connection/agent-connection.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 pyProjectGenerator, {\n getPyProjectDetails,\n} from '../../py/project/generator';\nimport tsProjectGenerator from '../../ts/lib/generator';\nimport {\n addStarExport,\n appendToArrayViaGritQL,\n applyGritQL,\n matchGritQL,\n} from '../ast';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n type MustDeclarePy,\n} from '../declared-dependencies';\nimport { addDependenciesToPackageJson } from '../dependencies';\nimport { esmVars } from '../module-format';\nimport { addDependenciesToPyProjectToml } from '../py';\nimport {\n type IPyDepVersion,\n type ITsDepVersion,\n withVersions,\n} from '../versions';\n\n/** TypeScript dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_DEPENDENCIES = [\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/credential-providers' },\n { name: 'aws4fetch' },\n { name: '@modelcontextprotocol/sdk' },\n { name: '@a2a-js/sdk' },\n { name: '@strands-agents/sdk' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** Python dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_PY_DEPENDENCIES = [\n { name: 'aws-lambda-powertools' },\n { name: 'strands-agents' },\n] as const satisfies readonly { name: IPyDepVersion }[];\n\ntype AgentConnectionPyDependency =\n (typeof AGENT_CONNECTION_PY_DEPENDENCIES)[number]['name'];\n\n/** Prefix a GritQL pattern with `language python` */\nconst py = (pattern: string) => `language python\\n${pattern}`;\n\nconst AGENT_CONNECTION_DIR = 'agent-connection';\nconst PACKAGES_DIR = 'packages';\nconst COMMON_DIR = 'common';\n\nexport const AGENT_CONNECTION_PROJECT_DIR = joinPathFragments(\n PACKAGES_DIR,\n COMMON_DIR,\n AGENT_CONNECTION_DIR,\n);\n\nconst PY_AGENT_CONNECTION_NAME = 'agent_connection';\n\n/**\n * Get the directory of the shared Python agent-connection project.\n */\nexport function getPythonAgentConnectionProjectDir(tree: Tree): string {\n const { dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return dir;\n}\n\n/**\n * Get the Python module name of the shared agent-connection project.\n */\nexport function getPythonAgentConnectionModuleName(tree: Tree): string {\n const { normalizedModuleName } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return normalizedModuleName;\n}\n\n/**\n * Get the shared agent-connection project as `{ name, root }`, suitable for\n * passing to {@link addWorkspaceDependencyToPyProject} (which derives the\n * dependency's PEP 503 distribution name from the project itself, so callers\n * never construct the name).\n */\nexport function getPythonAgentConnectionProject(tree: Tree): {\n name: string;\n root: string;\n} {\n const { fullyQualifiedName, dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return { name: fullyQualifiedName, root: dir };\n}\n\n/**\n * The connection protocols an agent framework can connect over. Each maps to a\n * framework-agnostic Layer-0/1 template directory plus a per-framework Layer-2\n * client directory (see `FRAMEWORKS`).\n */\nexport type ConnectionProtocol = 'mcp' | 'gateway' | 'a2a';\n\n/**\n * The agent frameworks we can generate connection clients for. Adding a new\n * framework is an additive change: append an entry to `FRAMEWORKS` with its\n * Layer-2 template directories and dependencies — the framework-agnostic\n * Layer-0/1 (`core-auth`, `core-shared`, the per-protocol transports/configs)\n * is reused unchanged.\n */\nexport type AgentFramework = 'strands' | 'langchain';\n\n/**\n * Resolve an agent component's framework, defaulting to `strands`. Connection\n * generators dispatch on the returned framework to pick the matching templates\n * and agent.py/agent.ts transforms.\n */\nexport function resolveAgentFramework(\n framework: string | undefined,\n): AgentFramework {\n return framework === 'langchain' ? 'langchain' : 'strands';\n}\n\n/**\n * Framework-agnostic Layer-1 templates, keyed by protocol. These resolve the\n * endpoint and build the signed transport/client-config; they contain no\n * framework dependency.\n */\nconst TS_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'core-mcp',\n gateway: 'core-gateway',\n a2a: 'core-a2a',\n};\nconst PY_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'py-core-mcp',\n gateway: 'py-core-gateway',\n a2a: 'py-core-a2a',\n};\n\n/**\n * A re-export the framework base emits into the agent-connection module's\n * `__init__.py` (the agent server entry point imports these by name).\n */\ninterface BaseReExport {\n fromModule: string;\n importName: string;\n}\n\n/**\n * A framework's Layer-2 templates for one language. `base` (optional) holds the\n * helpers every connection of that framework needs (error logging, per-session\n * agent cache); `baseReExports` lists what those helpers expose at the module\n * root. `protocols` maps each *supported* protocol to the thin client that wraps\n * the matching Layer-1 transport/config in the framework's client type.\n *\n * A framework whose Layer-2 needs no base helpers (e.g. LangChain, whose AG-UI\n * foundation reuses only the framework-agnostic session context) omits `base`\n * and leaves `baseReExports` empty.\n *\n * A protocol absent from `protocols` is not supported by that framework in that\n * language — callers must check before emitting. `deps` are the extra package\n * dependencies the base helpers require (per-connection client deps are added\n * by the connection generators, not here).\n */\ninterface FrameworkLanguageTemplates<Dep extends string> {\n base?: string;\n baseReExports: BaseReExport[];\n protocols: Partial<Record<ConnectionProtocol, string>>;\n deps: Dep[];\n}\n\n/**\n * Per-framework Layer-2 templates. Support is asymmetric by design: a framework\n * may target only one language (`ts`/`py` is optional) and only a subset of\n * protocols. Adding a framework — or extending an existing one to a new\n * language/protocol — is an additive change to this registry.\n */\ninterface FrameworkTemplates {\n ts?: FrameworkLanguageTemplates<string>;\n py?: FrameworkLanguageTemplates<AgentConnectionPyDependency>;\n}\n\nconst FRAMEWORKS: Record<AgentFramework, FrameworkTemplates> = {\n strands: {\n ts: {\n base: 'core-strands/base',\n baseReExports: [\n {\n fromModule: './core/with-session-id-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/model-errors-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/tool-errors-strands.js',\n importName: '*',\n },\n ],\n protocols: {\n mcp: 'core-strands/mcp',\n gateway: 'core-strands/gateway',\n a2a: 'core-strands/a2a',\n },\n deps: [],\n },\n py: {\n base: 'py-core-strands/base',\n baseReExports: [\n {\n fromModule: '.core.with_session_id_strands',\n importName: 'with_session_id',\n },\n {\n fromModule: '.core.model_errors_strands',\n importName: 'log_model_errors',\n },\n {\n fromModule: '.core.tool_errors_strands',\n importName: 'log_tool_errors',\n },\n ],\n protocols: {\n mcp: 'py-core-strands/mcp',\n gateway: 'py-core-strands/gateway',\n a2a: 'py-core-strands/a2a',\n },\n deps: ['strands-agents'],\n },\n },\n langchain: {\n // LangChain is supported for Python agents only (the TypeScript LangChain\n // agent foundation has no in-process AG-UI <-> LangGraph adapter, so it is\n // not scaffolded — see ts#agent). Its Layer-2 clients stay usable after\n // agent construction, so there is no base helper layer (no model-error\n // logger / per-session agent cache) and no strands-agents dependency — its\n // AG-UI foundation reuses only the framework-agnostic session context, and\n // its A2A client drives the a2a SDK directly rather than wrapping Strands'\n // A2AAgent. The per-connection adapter dependency (langchain-mcp-adapters /\n // a2a-sdk) is added by the connection generators.\n py: {\n baseReExports: [],\n protocols: {\n mcp: 'py-core-langchain/mcp',\n gateway: 'py-core-langchain/gateway',\n a2a: 'py-core-langchain/a2a',\n },\n deps: [],\n },\n },\n};\n\n/** Resolve a framework's templates for a language + protocol, or throw. */\nfunction frameworkLanguage<L extends 'ts' | 'py'>(\n framework: AgentFramework,\n language: L,\n protocol: ConnectionProtocol,\n): NonNullable<FrameworkTemplates[L]> & { protocol: string } {\n const lang = FRAMEWORKS[framework][language];\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n const protocolDir = lang.protocols[protocol];\n if (!protocolDir) {\n throw new Error(\n `The '${framework}' framework does not support ${protocol} connections for ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n return { ...lang, protocol: protocolDir } as NonNullable<\n FrameworkTemplates[L]\n > & { protocol: string };\n}\n\n/** Protocols whose Layer-1 needs the shared MCP transport (`core-shared`). */\nconst MCP_TRANSPORT_PROTOCOLS: ConnectionProtocol[] = ['mcp', 'gateway'];\n\nconst tsCoreDir = () =>\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'core');\n\n/**\n * Runtime dependencies each TypeScript core template directory imports. Emitting\n * a template also declares its dependencies in the agent-connection project's\n * package.json so the `noUndeclaredDependencies` lint rule passes.\n */\nconst TS_TEMPLATE_DEPS: Record<\n string,\n (typeof AGENT_CONNECTION_DEPENDENCIES)[number]['name'][]\n> = {\n 'core-runtime-config': ['@aws-lambda-powertools/parameters'],\n 'core-auth': ['@aws-sdk/credential-providers', 'aws4fetch'],\n 'core-shared': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-mcp': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-gateway': [\n '@aws-sdk/credential-providers',\n '@modelcontextprotocol/sdk',\n ],\n 'core-a2a': ['@aws-sdk/credential-providers', '@a2a-js/sdk'],\n 'core-strands/base': ['@strands-agents/sdk'],\n 'core-strands/mcp': ['@strands-agents/sdk'],\n 'core-strands/gateway': ['@strands-agents/sdk'],\n 'core-strands/a2a': ['@strands-agents/sdk'],\n};\n\nconst emitTs = (\n tree: Tree,\n templateDir: string,\n declaration: DependencyDeclaration,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n tsCoreDir(),\n { ...esmVars(tree) },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n const deps = TS_TEMPLATE_DEPS[templateDir];\n if (deps?.length) {\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n deps,\n ),\n {},\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'package.json'),\n );\n }\n};\n\n/**\n * Ensure the shared TypeScript agent-connection project exists and has the\n * framework-agnostic core helpers (runtime-config loader, session context).\n * Per-connection generators emit their own protocol + framework client\n * templates via `addTypeScriptCoreClient`.\n */\nexport async function ensureTypeScriptAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n): Promise<void> {\n const projectJsonPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'project.json',\n );\n if (!tree.exists(projectJsonPath)) {\n await tsProjectGenerator(tree, {\n name: AGENT_CONNECTION_DIR,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n emitTs(tree, 'core-runtime-config', declaration);\n\n // Re-export session-context helpers so agent server entry points can set the\n // current session on each inbound request without pulling in internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/session-context.js',\n );\n\n // Re-export the runtime-config loader so agent server entry points can read\n // their own connected resources (e.g. session storage) without pulling in\n // internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/runtime-config.js',\n );\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the agent-connection project and re-export them. The agent\n * server entry point imports these regardless of whether any connection client\n * is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addTypeScriptCoreClient`.\n */\nexport async function addTypeScriptFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].ts;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support TypeScript agents.`,\n );\n }\n if (lang.base) {\n emitTs(tree, lang.base, declaration);\n }\n\n const indexPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'src',\n 'index.ts',\n );\n for (const reExport of lang.baseReExports) {\n await addStarExport(tree, indexPath, reExport.fromModule);\n }\n}\n\n/**\n * Emit the TypeScript client templates for a connection protocol and agent\n * framework into the agent-connection project's `src/core/` directory. Safe to\n * call multiple times — `KeepExisting` preserves customised files.\n *\n * Layers emitted:\n * - Layer 0 `core-auth` (signed fetch + endpoint resolution) — always\n * - Layer 1 `core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addTypeScriptCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'ts', protocol);\n\n emitTs(tree, 'core-auth', declaration);\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitTs(tree, 'core-shared', declaration);\n }\n emitTs(tree, TS_PROTOCOL_TEMPLATES[protocol], declaration);\n\n // Framework Layer 2: base helpers (re-exported for the agent server) + the\n // thin protocol client.\n await addTypeScriptFrameworkBase(\n tree,\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n framework,\n );\n emitTs(tree, fw.protocol, declaration);\n}\n\n/**\n * Ensure the shared Python agent-connection project exists.\n * Only creates the project shell — per-connection generators are responsible\n * for emitting their own core client templates.\n */\nexport async function ensurePythonAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n): Promise<void> {\n const projectDir = getPythonAgentConnectionProjectDir(tree);\n const moduleName = getPythonAgentConnectionModuleName(tree);\n const projectJsonPath = joinPathFragments(projectDir, 'project.json');\n\n if (!tree.exists(projectJsonPath)) {\n // Create the Python project using the standard py#project generator\n await pyProjectGenerator(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n type: 'library',\n });\n }\n\n const moduleDir = joinPathFragments(projectDir, moduleName);\n\n // Ensure core/__init__.py exists\n const coreDir = joinPathFragments(moduleDir, 'core');\n if (!tree.exists(joinPathFragments(coreDir, '__init__.py'))) {\n tree.write(joinPathFragments(coreDir, '__init__.py'), '');\n }\n\n // Ensure app/__init__.py exists\n const appInitPath = joinPathFragments(moduleDir, 'app', '__init__.py');\n if (!tree.exists(appInitPath)) {\n tree.write(appInitPath, '');\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'py-core-runtime-config'),\n coreDir,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Re-export the session id context so agent server entry points can set the\n // current session on each inbound request without importing internals.\n const moduleInitPath = joinPathFragments(moduleDir, '__init__.py');\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'get_current_session_id',\n );\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'session_id_context',\n );\n\n // The runtime-config loader reads AppConfig via aws-lambda-powertools.\n addDependenciesToPyProjectToml(\n tree,\n projectDir,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n ['aws-lambda-powertools'],\n );\n}\n\nconst pyCoreDir = (tree: Tree) =>\n joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n 'core',\n );\n\nconst emitPy = (tree: Tree, templateDir: string) =>\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n pyCoreDir(tree),\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n/**\n * Ensure the shared Python agent-connection project has\n * `s3_checkpoint_saver_langchain.py` — a vendored `S3CheckpointSaver`\n * (from `langgraph-checkpoint-s3`, MIT licensed) that LangChain agents with\n * `session: 's3'` import from directly (`.core.s3_checkpoint_saver_langchain`),\n * mirroring how they import `.core.runtime_config`. Vendored rather than\n * installed as a dependency, and shared rather than per-agent, since it has\n * no agent-specific templating.\n */\nexport function ensureLangchainS3CheckpointSaver(tree: Tree): void {\n emitPy(tree, 'py-core-langchain/s3');\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the Python agent-connection project and re-export them.\n * The agent server entry point imports these regardless of whether a connection\n * client is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addPythonCoreClient`.\n */\nexport async function addPythonFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].py;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support Python agents.`,\n );\n }\n if (lang.base) {\n emitPy(tree, lang.base);\n }\n\n const moduleInitPath = joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n '__init__.py',\n );\n for (const reExport of lang.baseReExports) {\n await addPythonReExport(\n tree,\n moduleInitPath,\n reExport.fromModule,\n reExport.importName,\n );\n }\n\n if (lang.deps.length > 0) {\n addDependenciesToPyProjectToml(\n tree,\n getPythonAgentConnectionProjectDir(tree),\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n lang.deps,\n );\n }\n}\n\n/**\n * Emit the Python client templates for a connection protocol and agent\n * framework into the agent-connection project's core directory.\n *\n * Layers emitted:\n * - Layer 0 `py-core-auth` (SigV4 httpx.Auth, session auth, endpoints) — always\n * - Layer 1 `py-core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addPythonCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'py', protocol);\n\n emitPy(tree, 'py-core-auth');\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitPy(tree, 'py-core-shared');\n }\n emitPy(tree, PY_PROTOCOL_TEMPLATES[protocol]);\n\n // Framework Layer 2: base helpers + the thin protocol client.\n await addPythonFrameworkBase(\n tree,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n framework,\n );\n emitPy(tree, fw.protocol);\n}\n\n/**\n * Patch a TypeScript agent.ts to create a connection client and register it\n * in the Agent's tools. Used by the MCP and gateway connection generators —\n * the client class must expose a static async `create()` returning a value\n * accepted by `Agent.tools` (e.g. an `McpClient`).\n */\nexport async function addTypeScriptClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n const clientCreationStmt = `const ${clientVarName} = await ${clientClassName}.create();`;\n\n // Transform the arrow function that contains `new Agent`:\n // - Expression body: wrap in block with client creation and return\n // - Block body: prepend client creation statement\n await applyGritQL(\n tree,\n agentFilePath,\n `or { \\`async ($p) => new Agent($args)\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n return new Agent($args);\n}\\` where { $program <: not contains \\`${clientClassName}.create\\` }, \\`async ($p) => { $body }\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n $body\n}\\` where { $body <: contains \\`new Agent($_)\\`, $program <: not contains \\`${clientClassName}.create\\` } }`,\n );\n\n // Prepend the client to the tools array\n await applyGritQL(\n tree,\n agentFilePath,\n `\\`tools: [$items]\\` => \\`tools: [${clientVarName}, $items]\\` where { $items <: within \\`new Agent($_)\\`, $items <: not contains \\`${clientVarName}\\` }`,\n );\n}\n\n/**\n * Patch a Python agent.py to create a context-managed connection client,\n * enter it in the `with` block around `yield Agent(...)`, and spread its\n * `list_tools_sync()` into the Agent's tools. Used by the MCP and gateway\n * connection generators — the client class must expose a static `create()`\n * returning a context manager with `list_tools_sync()` (e.g. an `MCPClient`).\n */\nasync function addPythonClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonClientTools(tree, agentFilePath, clientVarName);\n await addPythonClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Append `*<clientVarName>.list_tools_sync()` to the Agent's tools list.\n */\nconst addPythonClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(\n tree,\n filePath,\n py(`\\`${clientVarName}.list_tools_sync()\\``),\n )\n ) {\n return;\n }\n\n await appendToArrayViaGritQL(\n tree,\n filePath,\n 'tools=',\n `*${clientVarName}.list_tools_sync()`,\n { skipIfContains: clientVarName, language: 'py' },\n );\n};\n\n/**\n * Create the client in get_agent and enter it in the `with` block.\n *\n * First connection: rewrites `def get_agent` to wrap the body in a with\n * block. Subsequent connections: adds to the existing with items and\n * prepends the creation line.\n */\nconst addPythonClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n // Try the \"add to existing with block\" pattern first.\n // If it succeeds, there was already a with block from a previous connection.\n const addedToWith = await applyGritQL(\n tree,\n filePath,\n py(`\\`with ($items,): $body\\` where {\n $items <: not contains \\`${clientVarName}\\`,\n $items += \\`, ${clientVarName}\\`\n}`),\n );\n\n if (addedToWith) {\n // Subsequent connection — prepend the creation line to the function body\n // (a single anchor, so the line is inserted exactly once).\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n return;\n }\n\n // First connection — wrap the existing `def get_agent` body in a single\n // `with (<var>,):` block.\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n with (\n ${clientVarName},\n ):\n $body\\``),\n );\n};\n\n/**\n * Patch a LangChain agent.py to load connection tools and spread them into the\n * `create_agent(...)` tools list. Used by the MCP and gateway connection\n * generators when the source agent uses the `langchain` framework — the client\n * class must expose a static `create()` returning a `list[BaseTool]`. The tools\n * come from langchain-mcp-adapters' `MultiServerMCPClient`, which keeps the\n * connection config on each tool and opens a fresh MCP session per call, so the\n * tools stay usable after `get_agent` returns — no `with` block is needed.\n * Mirrors {@link addPythonClientToAgent} for the Strands shape.\n */\nasync function addPythonLangchainClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonLangchainClientTools(tree, agentFilePath, clientVarName);\n await addPythonLangchainClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Spread `*<clientVarName>` into the `create_agent(...)` tools list.\n *\n * Scoped via `$old <: within \\`create_agent($_)\\`` so only the agent's own\n * tools= keyword argument is touched (not an unrelated function with a\n * `tools=` parameter).\n */\nconst addPythonLangchainClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: within \\`create_agent($_)\\`,\n $old <: not contains \\`*${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}\\` }\n }\n}`),\n );\n};\n\n/**\n * Prepend `<clientVarName> = <clientClassName>.create()` to the get_agent body\n * (which loads the connection's tools). No `with` block — the LangChain client\n * hands langchain-mcp-adapters a connection config, so each tool opens its own\n * MCP session per call and the tools are safe to use after get_agent returns.\n * Idempotent via the `not contains <clientClassName>.create` guard.\n */\nconst addPythonLangchainClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`create_agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n};\n\n/**\n * Per-framework naming + template layout for a Python per-connection client.\n * Every py#agent connection generator (mcp, gateway, a2a) names its client\n * class `<Name>Client<suffix>`, its module `<name>_client_<suffix>`, and reads\n * the per-connection app-client template from a per-framework sub-path of its\n * own `files/` dir — all of which vary only by framework, so they live here as\n * one source of truth.\n *\n * Keyed by {@link AgentFramework} rather than a boolean so a third framework is\n * an additive entry here — never another `if (isLangchain)` branch in each\n * generator.\n */\nexport interface PyClientNaming {\n /** Class-name suffix on the per-connection app client (`<Name>Client<suffix>`). */\n clientClassSuffix: string;\n /** Module/file-name suffix on the per-connection app client (`<name>_client_<suffix>`). */\n clientModuleSuffix: string;\n /**\n * Sub-path, under a connection generator's `files/` dir, of the per-connection\n * app client template for this framework. Every connection generator lays its\n * templates out the same way, so this resolves against any of them.\n */\n appTemplateSubdir: string;\n}\n\nexport const PY_CLIENT_NAMING: Record<AgentFramework, PyClientNaming> = {\n strands: {\n clientClassSuffix: 'Strands',\n clientModuleSuffix: 'strands',\n appTemplateSubdir: joinPathFragments('agent-connection', 'app'),\n },\n langchain: {\n clientClassSuffix: 'LangChain',\n clientModuleSuffix: 'langchain',\n appTemplateSubdir: joinPathFragments(\n 'langchain',\n 'agent-connection',\n 'app',\n ),\n },\n};\n\n/**\n * How an MCP-family connection (an MCP server or an AgentCore Gateway, both of\n * which expose tools over MCP) is wired into a Python agent of a given\n * framework. The mcp-connection and gateway-connection generators share this:\n * they differ only in the metadata of the thing being connected, not in how\n * the framework's client is shaped or spliced into agent.py. A2A connections\n * wire tools differently, so they reuse only {@link PY_CLIENT_NAMING}.\n */\nexport interface PyMcpFamilyConnection extends PyClientNaming {\n /** Extra Python deps this framework's MCP-family client needs (beyond the shared transport). */\n deps: IPyDepVersion[];\n /**\n * Splice the per-connection client into the agent's `get_agent` in agent.py.\n * Strands enters a context-managed `MCPClient` and spreads `list_tools_sync()`;\n * LangChain loads `BaseTool`s and spreads them into `create_agent(...)`.\n */\n wireClientIntoAgent: (\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n ) => Promise<void>;\n}\n\nexport const PY_MCP_FAMILY_CONNECTIONS: Record<\n AgentFramework,\n PyMcpFamilyConnection\n> = {\n strands: {\n ...PY_CLIENT_NAMING.strands,\n deps: [],\n wireClientIntoAgent: addPythonClientToAgent,\n },\n langchain: {\n ...PY_CLIENT_NAMING.langchain,\n // langchain-mcp-adapters backs the LangChain client; it must not pull Strands in.\n deps: ['langchain-mcp-adapters'],\n wireClientIntoAgent: addPythonLangchainClientToAgent,\n },\n};\n\n/**\n * Add a re-export to the Python agent-connection module's __init__.py.\n * Equivalent to addStarExport for TS.\n * Uses `__all__` to mark re-exports as public (satisfies ruff F401).\n * Uses GritQL for AST-aware transforms where possible.\n */\nexport async function addPythonReExport(\n tree: Tree,\n initFilePath: string,\n fromModule: string,\n importName: string,\n): Promise<void> {\n // Check if already exported\n if (await matchGritQL(tree, initFilePath, `\\`${importName}\\``)) {\n return;\n }\n\n const importLine = `from ${fromModule} import ${importName}`;\n const allEntry = `\"${importName}\"`;\n\n // If there's already an import from the same module, merge into its name list\n // (ruff I001 rejects two `from X import ...` lines for the same module).\n const mergedImport = await applyGritQL(\n tree,\n initFilePath,\n py(`\\`from ${fromModule} import $names\\` where {\n $names <: not contains \\`${importName}\\`,\n $names += \\`, ${importName}\\`\n}`),\n );\n\n if (mergedImport) {\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // Try to append import after existing import using +=\n const appendedImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`from $mod import $name\\` as $stmt where {\n $program <: not contains \\`${importName}\\`,\n $stmt += \\`\\n${importLine}\\`\n}`,\n ),\n );\n\n if (appendedImport) {\n // Also append to existing __all__\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // No existing imports — first re-export. Try to anchor after docstring.\n const anchoredImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`\"\"\"Automatically generated by Nx.\"\"\"\\` as $doc => \\`$doc\\n${importLine}\\n\\n__all__ = [${allEntry}]\\``,\n ),\n );\n\n if (!anchoredImport) {\n // Completely empty file or no docstring — write directly\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n }\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","pyProjectGenerator","getPyProjectDetails","tsProjectGenerator","addStarExport","appendToArrayViaGritQL","applyGritQL","matchGritQL","forDependencies","addDependenciesToPackageJson","esmVars","addDependenciesToPyProjectToml","withVersions","AGENT_CONNECTION_DEPENDENCIES","name","AGENT_CONNECTION_PY_DEPENDENCIES","py","pattern","AGENT_CONNECTION_DIR","PACKAGES_DIR","COMMON_DIR","AGENT_CONNECTION_PROJECT_DIR","PY_AGENT_CONNECTION_NAME","getPythonAgentConnectionProjectDir","tree","dir","directory","getPythonAgentConnectionModuleName","normalizedModuleName","getPythonAgentConnectionProject","fullyQualifiedName","root","resolveAgentFramework","framework","TS_PROTOCOL_TEMPLATES","mcp","gateway","a2a","PY_PROTOCOL_TEMPLATES","FRAMEWORKS","strands","ts","base","baseReExports","fromModule","importName","protocols","deps","langchain","frameworkLanguage","language","protocol","lang","Error","protocolDir","MCP_TRANSPORT_PROTOCOLS","tsCoreDir","TS_TEMPLATE_DEPS","emitTs","templateDir","declaration","dirname","overwriteStrategy","KeepExisting","length","ensureTypeScriptAgentConnectionProject","projectJsonPath","exists","addTypeScriptFrameworkBase","indexPath","reExport","addTypeScriptCoreClient","fw","includes","ensurePythonAgentConnectionProject","projectDir","moduleName","type","moduleDir","coreDir","write","appInitPath","moduleInitPath","addPythonReExport","pyCoreDir","emitPy","ensureLangchainS3CheckpointSaver","addPythonFrameworkBase","addPythonCoreClient","addTypeScriptClientToAgent","agentFilePath","clientClassName","clientVarName","clientCreationStmt","addPythonClientToAgent","addPythonClientTools","addPythonClientToGetAgent","filePath","skipIfContains","addedToWith","addPythonLangchainClientToAgent","addPythonLangchainClientTools","addPythonLangchainClientToGetAgent","PY_CLIENT_NAMING","clientClassSuffix","clientModuleSuffix","appTemplateSubdir","PY_MCP_FAMILY_CONNECTIONS","wireClientIntoAgent","initFilePath","importLine","allEntry","mergedImport","appendedImport","anchoredImport"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,OAAOC,sBACLC,mBAAmB,QACd,gCAA6B;AACpC,OAAOC,wBAAwB,4BAAyB;AACxD,SACEC,aAAa,EACbC,sBAAsB,EACtBC,WAAW,EACXC,WAAW,QACN,YAAS;AAChB,SAEEC,eAAe,QAG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C3B,CAAC;IAIA,IAAIG,gBAAgB;QAClB,kCAAkC;QAClC,MAAM3G,YACJkB,MACAqF,cACA7F,GAAG,CAAC,6CAA6C,EAAE+F,SAAS,IAAI,CAAC;QAEnE;IACF;IAEA,wEAAwE;IACxE,MAAMG,iBAAiB,MAAM5G,YAC3BkB,MACAqF,cACA7F,GACE,CAAC,4DAA4D,EAAE8F,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IAI5G,IAAI,CAACG,gBAAgB;QACnB,yDAAyD;QACzD1F,KAAKwD,KAAK,CAAC6B,cAAc,GAAGC,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IACvE;AACF"}
|
package/src/utils/ast.d.ts
CHANGED
|
@@ -83,3 +83,32 @@ export declare const GRIT_INSERT_PLACEHOLDER = "__GRIT_INSERT_PLACEHOLDER__";
|
|
|
83
83
|
* file changed.
|
|
84
84
|
*/
|
|
85
85
|
export declare const insertViaGritQL: (tree: Tree, filePath: string, pattern: string, text: string) => Promise<boolean>;
|
|
86
|
+
/**
|
|
87
|
+
* Append `entry` to an array, skipping arrays that already contain it, e.g.
|
|
88
|
+
* `` appendToArrayViaGritQL(tree, file, 'tools:', 'myTool', { scope: 'new Agent($_)' }) ``
|
|
89
|
+
* turns `tools: [a, b]` into `tools: [a, b, myTool]`.
|
|
90
|
+
*
|
|
91
|
+
* `arrayPrefix` is whatever precedes the array literal, including its separator —
|
|
92
|
+
* `'tools:'` for an object property, `'tools='` for a keyword argument or
|
|
93
|
+
* assignment, `'"tools":'` for a quoted key. Which separator applies depends on
|
|
94
|
+
* the construct rather than the language, so the caller states it.
|
|
95
|
+
*
|
|
96
|
+
* Appends after the last *element* rather than rewriting the element list with
|
|
97
|
+
* `=>`. GritQL binds a `[$items]` list to its trailing comma too, so
|
|
98
|
+
* `` `[$items]` => `[$items, entry]` `` emits the sparse array `[a, b, , entry]`
|
|
99
|
+
* once the formatter has wrapped the array — a hole that is `undefined` at
|
|
100
|
+
* runtime. (Accumulating with `$items += ", entry"` is safe by comparison, since
|
|
101
|
+
* it appends within the list rather than re-emitting it; both forms appear in
|
|
102
|
+
* this repo.)
|
|
103
|
+
*
|
|
104
|
+
* `scope` limits the match to an enclosing pattern, so same-named arrays
|
|
105
|
+
* elsewhere in the file are left alone. `skipIfContains` overrides what the
|
|
106
|
+
* append dedupes on, for when the rendered entry is not the identifier to match.
|
|
107
|
+
*
|
|
108
|
+
* The caller formats afterwards. Returns true if the entry was appended.
|
|
109
|
+
*/
|
|
110
|
+
export declare const appendToArrayViaGritQL: (tree: Tree, filePath: string, arrayPrefix: string, entry: string, options?: {
|
|
111
|
+
scope?: string;
|
|
112
|
+
skipIfContains?: string;
|
|
113
|
+
language?: "py";
|
|
114
|
+
}) => Promise<boolean>;
|
package/src/utils/ast.js
CHANGED
|
@@ -300,5 +300,36 @@ export const addDestructuredImport = async (tree, filePath, variableNames, from)
|
|
|
300
300
|
tree.write(filePath, content.replace(GRIT_INSERT_PLACEHOLDER, ()=>replacement));
|
|
301
301
|
return true;
|
|
302
302
|
};
|
|
303
|
+
/**
|
|
304
|
+
* Append `entry` to an array, skipping arrays that already contain it, e.g.
|
|
305
|
+
* `` appendToArrayViaGritQL(tree, file, 'tools:', 'myTool', { scope: 'new Agent($_)' }) ``
|
|
306
|
+
* turns `tools: [a, b]` into `tools: [a, b, myTool]`.
|
|
307
|
+
*
|
|
308
|
+
* `arrayPrefix` is whatever precedes the array literal, including its separator —
|
|
309
|
+
* `'tools:'` for an object property, `'tools='` for a keyword argument or
|
|
310
|
+
* assignment, `'"tools":'` for a quoted key. Which separator applies depends on
|
|
311
|
+
* the construct rather than the language, so the caller states it.
|
|
312
|
+
*
|
|
313
|
+
* Appends after the last *element* rather than rewriting the element list with
|
|
314
|
+
* `=>`. GritQL binds a `[$items]` list to its trailing comma too, so
|
|
315
|
+
* `` `[$items]` => `[$items, entry]` `` emits the sparse array `[a, b, , entry]`
|
|
316
|
+
* once the formatter has wrapped the array — a hole that is `undefined` at
|
|
317
|
+
* runtime. (Accumulating with `$items += ", entry"` is safe by comparison, since
|
|
318
|
+
* it appends within the list rather than re-emitting it; both forms appear in
|
|
319
|
+
* this repo.)
|
|
320
|
+
*
|
|
321
|
+
* `scope` limits the match to an enclosing pattern, so same-named arrays
|
|
322
|
+
* elsewhere in the file are left alone. `skipIfContains` overrides what the
|
|
323
|
+
* append dedupes on, for when the rendered entry is not the identifier to match.
|
|
324
|
+
*
|
|
325
|
+
* The caller formats afterwards. Returns true if the entry was appended.
|
|
326
|
+
*/ export const appendToArrayViaGritQL = async (tree, filePath, arrayPrefix, entry, options = {})=>{
|
|
327
|
+
const { scope, skipIfContains, language } = options;
|
|
328
|
+
const within = (variable)=>scope ? `${variable} <: within \`${scope}\`, ` : '';
|
|
329
|
+
const pattern = `or {` + // An empty array has no last element to append after.
|
|
330
|
+
` \`${arrayPrefix}$arr\` where { $arr <: \`[]\`, ${within('$arr')}` + ` $arr => \`[${GRIT_INSERT_PLACEHOLDER}]\` },` + // Dedupe on the list, append after its last element.
|
|
331
|
+
` \`${arrayPrefix}[$items]\` where {` + ` $items <: not contains \`${skipIfContains ?? entry}\`, ${within('$items')}` + ` $items <: [$..., $last], $last += \`, ${GRIT_INSERT_PLACEHOLDER}\` }` + ` }`;
|
|
332
|
+
return insertViaGritQL(tree, filePath, language === 'py' ? `language python\n${pattern}` : pattern, entry);
|
|
333
|
+
};
|
|
303
334
|
|
|
304
335
|
//# sourceMappingURL=ast.js.map
|