@aws/nx-plugin 1.0.0-rc.46 → 1.0.0-rc.48
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 +3 -60
- package/generators.json +1 -1
- package/package.json +7 -6
- package/src/agentcore-gateway/generator.js +12 -2
- package/src/agentcore-gateway/generator.js.map +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +25 -31
- package/src/infra/app/generator.js +9 -6
- package/src/infra/app/generator.js.map +1 -1
- package/src/license/config.js +1 -1
- package/src/license/config.js.map +1 -1
- package/src/mcp-server/dev-server.d.ts +1 -0
- package/src/mcp-server/dev-server.js +18 -0
- package/src/mcp-server/dev-server.js.map +1 -0
- package/src/mcp-server/schema.d.ts +1 -1
- package/src/mcp-server/tools/general-guidance.js +5 -6
- package/src/mcp-server/tools/general-guidance.js.map +1 -1
- package/src/preset/__snapshots__/generator.spec.ts.snap +42 -7
- package/src/preset/generator.d.ts +1 -1
- package/src/preset/generator.js +4 -2
- package/src/preset/generator.js.map +1 -1
- package/src/preset/schema.d.js.map +1 -1
- package/src/preset/schema.d.ts +1 -0
- package/src/preset/schema.json +5 -0
- package/src/py/agent/generator.js +2 -1
- package/src/py/agent/generator.js.map +1 -1
- package/src/py/mcp-server/generator.js +2 -1
- package/src/py/mcp-server/generator.js.map +1 -1
- package/src/py/project/generator.js +2 -1
- package/src/py/project/generator.js.map +1 -1
- package/src/py/rdb/generator.js +2 -1
- package/src/py/rdb/generator.js.map +1 -1
- package/src/smithy/ts/api/generator.js +5 -2
- package/src/smithy/ts/api/generator.js.map +1 -1
- package/src/terraform/project/generator.js +4 -1
- package/src/terraform/project/generator.js.map +1 -1
- package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +6 -6
- package/src/trpc/backend/generator.js +7 -5
- package/src/trpc/backend/generator.js.map +1 -1
- package/src/trpc/react/generator.js +4 -4
- package/src/trpc/react/generator.js.map +1 -1
- package/src/ts/agent/__snapshots__/generator.spec.ts.snap +9 -5
- package/src/ts/agent/a2a-connection/generator.js +3 -2
- package/src/ts/agent/a2a-connection/generator.js.map +1 -1
- package/src/ts/agent/files/deploy/Dockerfile.template +7 -3
- package/src/ts/agent/gateway-connection/generator.js +4 -3
- package/src/ts/agent/gateway-connection/generator.js.map +1 -1
- package/src/ts/agent/generator.js +10 -7
- package/src/ts/agent/generator.js.map +1 -1
- package/src/ts/agent/mcp-connection/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/ts/agent/mcp-connection/generator.js +4 -3
- package/src/ts/agent/mcp-connection/generator.js.map +1 -1
- package/src/ts/agent/react-connection/generator.js +10 -19
- package/src/ts/agent/react-connection/generator.js.map +1 -1
- package/src/ts/astro-docs/generator.js +12 -3
- package/src/ts/astro-docs/generator.js.map +1 -1
- package/src/ts/dcr-proxy/generator.js +5 -5
- package/src/ts/dcr-proxy/generator.js.map +1 -1
- package/src/ts/dynamodb/generator.js +5 -2
- package/src/ts/dynamodb/generator.js.map +1 -1
- package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +4 -2
- package/src/ts/lambda-function/files/handler/__lambdaFunctionKebabCase__.ts.template +2 -1
- package/src/ts/lambda-function/generator.js +3 -2
- package/src/ts/lambda-function/generator.js.map +1 -1
- package/src/ts/lib/ts-project-utils.js +17 -10
- package/src/ts/lib/ts-project-utils.js.map +1 -1
- package/src/ts/lib/vitest.js +2 -1
- package/src/ts/lib/vitest.js.map +1 -1
- package/src/ts/mcp-server/files/Dockerfile.template +7 -3
- package/src/ts/mcp-server/generator.js +13 -13
- package/src/ts/mcp-server/generator.js.map +1 -1
- package/src/ts/nx-generator/generator.js +5 -0
- package/src/ts/nx-generator/generator.js.map +1 -1
- package/src/ts/nx-plugin/__snapshots__/generator.spec.ts.snap +5 -6
- package/src/ts/nx-plugin/files/mcp-server/resources/GENERAL_GUIDANCE.md.template +5 -6
- package/src/ts/nx-plugin/utils.js +8 -10
- package/src/ts/nx-plugin/utils.js.map +1 -1
- package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +11 -3
- package/src/ts/rdb/agent-connection/generator.js +1 -2
- package/src/ts/rdb/agent-connection/generator.js.map +1 -1
- package/src/ts/rdb/files/Dockerfile.template +5 -1
- package/src/ts/rdb/files/src/migration-handler.ts.template +3 -1
- package/src/ts/rdb/generator.js +12 -8
- package/src/ts/rdb/generator.js.map +1 -1
- package/src/ts/rdb/mcp-server-connection/generator.js +1 -2
- package/src/ts/rdb/mcp-server-connection/generator.js.map +1 -1
- package/src/ts/rdb/smithy-connection/generator.js +1 -2
- package/src/ts/rdb/smithy-connection/generator.js.map +1 -1
- package/src/ts/rdb/trpc-connection/generator.js +1 -2
- package/src/ts/rdb/trpc-connection/generator.js.map +1 -1
- package/src/ts/react-website/agui/generator.js +5 -4
- package/src/ts/react-website/agui/generator.js.map +1 -1
- package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +210 -79
- package/src/ts/react-website/app/generator.js +34 -14
- package/src/ts/react-website/app/generator.js.map +1 -1
- package/src/ts/react-website/cognito-auth/generator.js +3 -2
- package/src/ts/react-website/cognito-auth/generator.js.map +1 -1
- package/src/ts/react-website/runtime-config/generator.js +2 -2
- package/src/ts/react-website/runtime-config/generator.js.map +1 -1
- package/src/ts/sync/generator.js +81 -3
- package/src/ts/sync/generator.js.map +1 -1
- package/src/utils/agent-connection/agent-connection.d.ts +1 -1
- package/src/utils/agent-connection/agent-connection.js +50 -1
- package/src/utils/agent-connection/agent-connection.js.map +1 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js +10 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
- package/src/utils/agent-core-constructs/files/terraform/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.tf.template +19 -1
- package/src/utils/api-constructs/api-constructs.js +15 -1
- package/src/utils/api-constructs/api-constructs.js.map +1 -1
- package/src/utils/bundle/bundle.js +2 -1
- package/src/utils/bundle/bundle.js.map +1 -1
- package/src/utils/commands.d.ts +5 -3
- package/src/utils/commands.js +24 -3
- package/src/utils/commands.js.map +1 -1
- package/src/utils/config/index.d.ts +16 -0
- package/src/utils/config/index.js.map +1 -1
- package/src/utils/config/utils.d.ts +3 -2
- package/src/utils/config/utils.js +4 -3
- package/src/utils/config/utils.js.map +1 -1
- package/src/utils/connection/open-api/react.js +3 -2
- package/src/utils/connection/open-api/react.js.map +1 -1
- package/src/utils/containers.js +1 -1
- package/src/utils/containers.js.map +1 -1
- package/src/utils/dependencies.d.ts +18 -0
- package/src/utils/dependencies.js +206 -0
- package/src/utils/dependencies.js.map +1 -0
- package/src/utils/docker.d.ts +8 -0
- package/src/utils/docker.js +8 -1
- package/src/utils/docker.js.map +1 -1
- package/src/utils/files/common/shadcn/readme/README.md.template +3 -3
- package/src/utils/files/shadcn/components.json.template +1 -1
- package/src/utils/format.d.ts +20 -1
- package/src/utils/format.js +137 -74
- package/src/utils/format.js.map +1 -1
- package/src/utils/fs.d.ts +1 -1
- package/src/utils/fs.js +1 -1
- package/src/utils/fs.js.map +1 -1
- package/src/utils/iac.js +1 -1
- package/src/utils/iac.js.map +1 -1
- package/src/utils/init.d.ts +7 -1
- package/src/utils/init.js +45 -19
- package/src/utils/init.js.map +1 -1
- package/src/utils/install.js +3 -1
- package/src/utils/install.js.map +1 -1
- package/src/utils/mcp.d.ts +9 -0
- package/src/utils/mcp.js +9 -1
- package/src/utils/mcp.js.map +1 -1
- package/src/utils/module-format.d.ts +5 -8
- package/src/utils/module-format.js +29 -12
- package/src/utils/module-format.js.map +1 -1
- package/src/utils/npm-scope.d.ts +0 -4
- package/src/utils/npm-scope.js +0 -5
- package/src/utils/npm-scope.js.map +1 -1
- package/src/utils/nx.d.ts +13 -0
- package/src/utils/nx.js +24 -1
- package/src/utils/nx.js.map +1 -1
- package/src/utils/pnpm-workspace.d.ts +1 -12
- package/src/utils/pnpm-workspace.js +3 -30
- package/src/utils/pnpm-workspace.js.map +1 -1
- package/src/utils/project-package-json.d.ts +39 -0
- package/src/utils/project-package-json.js +119 -0
- package/src/utils/project-package-json.js.map +1 -0
- package/src/utils/shared-constructs.js +6 -5
- package/src/utils/shared-constructs.js.map +1 -1
- package/src/utils/shared-dynamodb-scripts.js +4 -2
- package/src/utils/shared-dynamodb-scripts.js.map +1 -1
- package/src/utils/shared-infra-scripts.js +5 -4
- package/src/utils/shared-infra-scripts.js.map +1 -1
- package/src/utils/shared-rdb-scripts.js +14 -1
- package/src/utils/shared-rdb-scripts.js.map +1 -1
- package/src/utils/shared-shadcn.js +11 -8
- package/src/utils/shared-shadcn.js.map +1 -1
- package/src/utils/test-git.d.ts +39 -0
- package/src/utils/test-git.js +117 -0
- package/src/utils/test-git.js.map +1 -0
- package/src/utils/test.js +8 -3
- package/src/utils/test.js.map +1 -1
- package/src/utils/versions.d.ts +7 -1
- package/src/utils/versions.js +13 -2
- package/src/utils/versions.js.map +1 -1
- package/src/bin/aws-nx-mcp.d.ts +0 -2
- package/src/bin/aws-nx-mcp.js +0 -14
- package/src/bin/aws-nx-mcp.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/mcp-server/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n addDependenciesToPackageJson,\n detectPackageManager,\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { ensureLicenseExceptions } from '../../license/config';\nimport { MCP_INSPECTOR_EXCEPTIONS } from '../../license/known-exceptions';\nimport { addMcpServerInfra } from '../../utils/agent-core-constructs/agent-core-constructs';\nimport { addTypeScriptBundleTarget } from '../../utils/bundle/bundle';\nimport { resolveContainers } from '../../utils/containers';\nimport { addDockerScanTarget } from '../../utils/docker';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { FsCommands } from '../../utils/fs';\nimport { resolveIac } from '../../utils/iac';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport { kebabCase, toClassName } from '../../utils/names';\nimport { getNpmScope } from '../../utils/npm-scope';\nimport {\n addComponentDevTarget,\n addComponentGeneratorMetadata,\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { assignPort } from '../../utils/port';\nimport { sharedConstructsGenerator } from '../../utils/shared-constructs';\nimport { BASE_IMAGES, TS_VERSIONS, withVersions } from '../../utils/versions';\nimport type { TsMcpServerGeneratorSchema } from './schema';\n\nexport const TS_MCP_SERVER_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsMcpServerGenerator = async (\n tree: Tree,\n options: TsMcpServerGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const project = readProjectConfigurationUnqualified(tree, options.project);\n\n if (!tree.exists(joinPathFragments(project.root, 'tsconfig.json'))) {\n throw new Error(\n `Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`,\n );\n }\n\n const defaultName = `${kebabCase(project.name.split('/').pop())}-mcp-server`;\n const name = kebabCase(options.name || defaultName);\n const mcpServerNameClassName = toClassName(name);\n const mcpTargetPrefix = options.name ? name : 'mcp-server';\n const targetSourceDirRelativeToProjectRoot = joinPathFragments(\n 'src',\n mcpTargetPrefix,\n );\n const targetSourceDir = joinPathFragments(\n project.root,\n targetSourceDirRelativeToProjectRoot,\n );\n const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');\n const distDir = joinPathFragments('dist', project.root);\n\n const infra = options.infra ?? 'agentcore';\n\n if (infra === 'none' && options.auth && options.auth !== 'iam') {\n console.warn(\n 'Warning: auth is ignored when no infrastructure is configured (no infrastructure is generated)',\n );\n }\n\n const auth = options.auth ?? 'iam';\n\n const projectPackageJsonPath = joinPathFragments(\n project.root,\n 'package.json',\n );\n\n // Generate esm if the module system is esm, otherwise commonjs. Projects\n // don't typically have their own package.json (dependencies are declared in\n // the workspace root), so fall back to the workspace format when absent.\n const esm = tree.exists(projectPackageJsonPath)\n ? readJson(tree, projectPackageJsonPath).type === 'module'\n : isEsmWorkspace(tree);\n\n // Generate example server\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n targetSourceDir,\n {\n name,\n esm,\n distDir,\n adotVersion:\n TS_VERSIONS['@aws/aws-distro-opentelemetry-node-autoinstrumentation'],\n jaegerVersion: TS_VERSIONS['@opentelemetry/propagator-jaeger'],\n nodeBaseImage: BASE_IMAGES.node,\n npmVersion: TS_VERSIONS.npm,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add dependencies\n const deps = withVersions([\n '@modelcontextprotocol/sdk',\n 'zod',\n 'express',\n '@aws-lambda-powertools/parameters',\n '@aws-sdk/client-appconfigdata',\n ]);\n const devDeps = withVersions([\n 'tsx',\n '@types/express',\n '@modelcontextprotocol/inspector',\n ]);\n\n // Add hosting based on infra\n if (infra === 'agentcore') {\n const containers = await resolveContainers(tree, 'inherit');\n const dockerImageTag = `${getNpmScope(tree)}-${name}:latest`;\n\n // Add bundle target\n await addTypeScriptBundleTarget(tree, project, {\n targetFilePath: `${targetSourceDirRelativeToProjectRoot}/http.ts`,\n bundleOutputDir: joinPathFragments('mcp', name),\n });\n\n const dockerOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'bundle',\n 'mcp',\n name,\n );\n const dockerTargetName = `${mcpTargetPrefix}-docker`;\n\n const fs = new FsCommands(tree);\n project.targets[dockerTargetName] = {\n cache: true,\n outputs: [`{workspaceRoot}/${dockerOutputDir}/Dockerfile`],\n executor: 'nx:run-commands',\n options: {\n commands: [\n fs.cp(\n `${targetSourceDir}/Dockerfile`,\n `${dockerOutputDir}/Dockerfile`,\n ),\n `${containers} build --platform linux/arm64 -t ${dockerImageTag} ${dockerOutputDir}`,\n ],\n parallel: false,\n },\n dependsOn: ['bundle'],\n };\n\n addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);\n addDependencyToTargetIfNotPresent(project, 'build', 'docker');\n\n addDockerScanTarget(tree, {\n project,\n containerEngine: containers,\n trivyTargetName: `${mcpTargetPrefix}-trivy`,\n dockerTargetName,\n imageTags: [dockerImageTag],\n });\n\n // Add shared constructs\n const iac = await resolveIac(tree, options.iac);\n await sharedConstructsGenerator(tree, { iac });\n\n // Add the construct to deploy the mcp server\n await addMcpServerInfra(tree, {\n mcpServerNameKebabCase: name,\n mcpServerNameClassName,\n projectName: project.name,\n dockerImageTag,\n dockerOutputDir,\n iac,\n auth,\n containers,\n });\n } else {\n // No Dockerfile needed for non-hosted MCP\n tree.delete(joinPathFragments(targetSourceDir, 'Dockerfile'));\n }\n\n addDependenciesToPackageJson(tree, deps, devDeps);\n // Add to the project's package.json too if it has one (e.g. nx plugins),\n // otherwise dependencies live in the workspace root only.\n if (tree.exists(projectPackageJsonPath)) {\n addDependenciesToPackageJson(tree, deps, devDeps, projectPackageJsonPath);\n }\n\n // @modelcontextprotocol/sdk declares zod as a peer dependency with a wide range\n // (^3.25 || ^4.0). Yarn does not dedupe the peer to the workspace's pinned zod, so\n // without a resolution it installs a separate zod under the SDK's own node_modules.\n // The two zod copies have structurally incompatible types, which breaks type\n // inference for registerTool inputSchema. Scope the resolution to the SDK so\n // other consumers (e.g. @tanstack/router-generator pinning zod@3) are unaffected.\n if (detectPackageManager() === 'yarn') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.resolutions = {\n ...packageJson.resolutions,\n '**/@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n };\n return packageJson;\n });\n }\n\n const localDevPort = assignPort(tree, project, 8000, {\n component: { info: TS_MCP_SERVER_GENERATOR_INFO, name: mcpTargetPrefix },\n });\n\n const mcpTargets = {\n ...project.targets,\n // Add targets for running the MCP server\n [`${mcpTargetPrefix}-serve-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/stdio.ts`],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-serve`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n },\n },\n },\n [`${mcpTargetPrefix}-dev`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n LOCAL_DEV: 'true',\n },\n },\n },\n [`${mcpTargetPrefix}-inspect`]: {\n executor: 'nx:run-commands',\n continuous: true,\n // Launch the inspector against the locally served HTTP server. The dev\n // target starts the server and any connected dependencies (e.g. a local\n // database).\n dependsOn: [`${mcpTargetPrefix}-dev`],\n options: {\n commands: [\n `mcp-inspector --transport http --server-url http://localhost:${localDevPort}/mcp`,\n ],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-inspect-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [\n `mcp-inspector -- tsx --watch ${relativeSourceDir}/stdio.ts`,\n ],\n cwd: '{projectRoot}',\n },\n },\n };\n\n // Aggregate `<mcp>-dev` under the project-level `dev` target.\n addComponentDevTarget(mcpTargets, `${mcpTargetPrefix}-dev`);\n\n updateProjectConfiguration(tree, project.name, {\n ...project,\n // Sort targets so their order is stable regardless of insertion order on\n // first run vs re-run.\n targets: sortObjectKeys(mcpTargets),\n });\n\n addComponentGeneratorMetadata(\n tree,\n project.name,\n TS_MCP_SERVER_GENERATOR_INFO,\n targetSourceDirRelativeToProjectRoot,\n mcpTargetPrefix,\n {\n port: localDevPort,\n rc: mcpServerNameClassName,\n auth,\n },\n );\n\n await addGeneratorMetricsIfApplicable(tree, [TS_MCP_SERVER_GENERATOR_INFO]);\n\n await ensureLicenseExceptions(tree, MCP_INSPECTOR_EXCEPTIONS);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default tsMcpServerGenerator;\n"],"names":["addDependenciesToPackageJson","detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readJson","updateJson","updateProjectConfiguration","ensureLicenseExceptions","MCP_INSPECTOR_EXCEPTIONS","addMcpServerInfra","addTypeScriptBundleTarget","resolveContainers","addDockerScanTarget","formatFilesInSubtree","FsCommands","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","kebabCase","toClassName","getNpmScope","addComponentDevTarget","addComponentGeneratorMetadata","addDependencyToTargetIfNotPresent","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","assignPort","sharedConstructsGenerator","BASE_IMAGES","TS_VERSIONS","withVersions","TS_MCP_SERVER_GENERATOR_INFO","filename","tsMcpServerGenerator","tree","options","project","exists","root","Error","defaultName","name","split","pop","mcpServerNameClassName","mcpTargetPrefix","targetSourceDirRelativeToProjectRoot","targetSourceDir","relativeSourceDir","replace","distDir","infra","auth","console","warn","projectPackageJsonPath","esm","type","dirname","adotVersion","jaegerVersion","nodeBaseImage","node","npmVersion","npm","overwriteStrategy","KeepExisting","deps","devDeps","containers","dockerImageTag","targetFilePath","bundleOutputDir","dockerOutputDir","dockerTargetName","fs","targets","cache","outputs","executor","commands","cp","parallel","dependsOn","containerEngine","trivyTargetName","imageTags","iac","mcpServerNameKebabCase","projectName","delete","packageJson","resolutions","localDevPort","component","info","mcpTargets","continuous","cwd","env","PORT","LOCAL_DEV","port","rc","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SACEA,4BAA4B,EAC5BC,oBAAoB,EAEpBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAAS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C;iBAAC;gBACtDkD,KAAK;gBACLC,KAAK;oBACHC,MAAM,GAAGP,cAAc;oBACvBQ,WAAW;gBACb;YACF;QACF;QACA,CAAC,GAAGxD,gBAAgB,QAAQ,CAAC,CAAC,EAAE;YAC9BkC,UAAU;YACVkB,YAAY;YACZ,uEAAuE;YACvE,wEAAwE;YACxE,aAAa;YACbd,WAAW;gBAAC,GAAGtC,gBAAgB,IAAI,CAAC;aAAC;YACrCV,SAAS;gBACP6C,UAAU;oBACR,CAAC,6DAA6D,EAAEa,aAAa,IAAI,CAAC;iBACnF;gBACDK,KAAK;YACP;QACF;QACA,CAAC,GAAGrD,gBAAgB,cAAc,CAAC,CAAC,EAAE;YACpCkC,UAAU;YACVkB,YAAY;YACZ9D,SAAS;gBACP6C,UAAU;oBACR,CAAC,6BAA6B,EAAEhC,kBAAkB,SAAS,CAAC;iBAC7D;gBACDkD,KAAK;YACP;QACF;IACF;IAEA,8DAA8D;IAC9D9E,sBAAsB4E,YAAY,GAAGnD,gBAAgB,IAAI,CAAC;IAE1DzC,2BAA2B8B,MAAME,QAAQK,IAAI,EAAE;QAC7C,GAAGL,OAAO;QACV,yEAAyE;QACzE,uBAAuB;QACvBwC,SAASnD,eAAeuE;IAC1B;IAEA3E,8BACEa,MACAE,QAAQK,IAAI,EACZV,8BACAe,sCACAD,iBACA;QACEyD,MAAMT;QACNU,IAAI3D;QACJQ;IACF;IAGF,MAAMrC,gCAAgCmB,MAAM;QAACH;KAA6B;IAE1E,MAAM1B,wBAAwB6B,MAAM5B;IAEpC,MAAMK,qBAAqBuB;IAC3B,OAAO,IACLpB,oBAAoBoB,MAAMC,QAAQqE,yBAAyB,EAAE;YAC3DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AAEF,eAAexE,qBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/mcp-server/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { ensureLicenseExceptions } from '../../license/config';\nimport { MCP_INSPECTOR_EXCEPTIONS } from '../../license/known-exceptions';\nimport { addMcpServerInfra } from '../../utils/agent-core-constructs/agent-core-constructs';\nimport { addTypeScriptBundleTarget } from '../../utils/bundle/bundle';\nimport { resolveContainers } from '../../utils/containers';\nimport { addDependenciesToPackageJson } from '../../utils/dependencies';\nimport { addDockerScanTarget, nodeImageVersions } from '../../utils/docker';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { FsCommands } from '../../utils/fs';\nimport { resolveIac } from '../../utils/iac';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport { kebabCase, toClassName } from '../../utils/names';\nimport { getNpmScope } from '../../utils/npm-scope';\nimport {\n addComponentDevTarget,\n addComponentGeneratorMetadata,\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { assignPort } from '../../utils/port';\nimport { sharedConstructsGenerator } from '../../utils/shared-constructs';\nimport { BASE_IMAGES, TS_VERSIONS, withVersions } from '../../utils/versions';\nimport type { TsMcpServerGeneratorSchema } from './schema';\n\nexport const TS_MCP_SERVER_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsMcpServerGenerator = async (\n tree: Tree,\n options: TsMcpServerGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const project = readProjectConfigurationUnqualified(tree, options.project);\n\n if (!tree.exists(joinPathFragments(project.root, 'tsconfig.json'))) {\n throw new Error(\n `Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`,\n );\n }\n\n const defaultName = `${kebabCase(project.name.split('/').pop())}-mcp-server`;\n const name = kebabCase(options.name || defaultName);\n const mcpServerNameClassName = toClassName(name);\n const mcpTargetPrefix = options.name ? name : 'mcp-server';\n const targetSourceDirRelativeToProjectRoot = joinPathFragments(\n 'src',\n mcpTargetPrefix,\n );\n const targetSourceDir = joinPathFragments(\n project.root,\n targetSourceDirRelativeToProjectRoot,\n );\n const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');\n const distDir = joinPathFragments('dist', project.root);\n\n const infra = options.infra ?? 'agentcore';\n\n if (infra === 'none' && options.auth && options.auth !== 'iam') {\n console.warn(\n 'Warning: auth is ignored when no infrastructure is configured (no infrastructure is generated)',\n );\n }\n\n const auth = options.auth ?? 'iam';\n\n const projectPackageJsonPath = joinPathFragments(\n project.root,\n 'package.json',\n );\n\n // Generate esm if the project's package.json is `type: module`, falling\n // back to the workspace format when the project has no manifest.\n const esm = tree.exists(projectPackageJsonPath)\n ? readJson(tree, projectPackageJsonPath).type === 'module'\n : isEsmWorkspace(tree);\n\n // Generate example server\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n targetSourceDir,\n {\n name,\n esm,\n distDir,\n adotVersion:\n TS_VERSIONS['@aws/aws-distro-opentelemetry-node-autoinstrumentation'],\n jaegerVersion: TS_VERSIONS['@opentelemetry/propagator-jaeger'],\n nodeBaseImage: BASE_IMAGES.node,\n ...nodeImageVersions(),\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add dependencies\n const deps = withVersions([\n '@modelcontextprotocol/sdk',\n 'zod',\n 'express',\n '@aws-lambda-powertools/parameters',\n '@aws-sdk/client-appconfigdata',\n ]);\n const devDeps = withVersions(['@types/express']);\n // tsx (local dev) and the MCP inspector are shared tooling.\n const rootDevDeps = withVersions(['tsx', '@modelcontextprotocol/inspector']);\n\n // Add hosting based on infra\n if (infra === 'agentcore') {\n const containers = await resolveContainers(tree, 'inherit');\n const dockerImageTag = `${getNpmScope(tree)}-${name}:latest`;\n\n // Add bundle target\n await addTypeScriptBundleTarget(tree, project, {\n targetFilePath: `${targetSourceDirRelativeToProjectRoot}/http.ts`,\n bundleOutputDir: joinPathFragments('mcp', name),\n });\n\n const dockerOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'bundle',\n 'mcp',\n name,\n );\n const dockerTargetName = `${mcpTargetPrefix}-docker`;\n\n const fs = new FsCommands(tree);\n project.targets[dockerTargetName] = {\n cache: true,\n outputs: [`{workspaceRoot}/${dockerOutputDir}/Dockerfile`],\n executor: 'nx:run-commands',\n options: {\n commands: [\n fs.cp(\n `${targetSourceDir}/Dockerfile`,\n `${dockerOutputDir}/Dockerfile`,\n ),\n `${containers} build --platform linux/arm64 -t ${dockerImageTag} ${dockerOutputDir}`,\n ],\n parallel: false,\n },\n dependsOn: ['bundle'],\n };\n\n addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);\n addDependencyToTargetIfNotPresent(project, 'build', 'docker');\n\n addDockerScanTarget(tree, {\n project,\n containerEngine: containers,\n trivyTargetName: `${mcpTargetPrefix}-trivy`,\n dockerTargetName,\n imageTags: [dockerImageTag],\n });\n\n // Add shared constructs\n const iac = await resolveIac(tree, options.iac);\n await sharedConstructsGenerator(tree, { iac });\n\n // Add the construct to deploy the mcp server\n await addMcpServerInfra(tree, {\n mcpServerNameKebabCase: name,\n mcpServerNameClassName,\n projectName: project.name,\n dockerImageTag,\n dockerOutputDir,\n iac,\n auth,\n containers,\n });\n } else {\n // No Dockerfile needed for non-hosted MCP\n tree.delete(joinPathFragments(targetSourceDir, 'Dockerfile'));\n }\n\n // Runtime deps go in the project manifest; shared tooling goes to the root.\n addDependenciesToPackageJson(tree, deps, devDeps, projectPackageJsonPath);\n addDependenciesToPackageJson(tree, {}, rootDevDeps);\n\n // @modelcontextprotocol/sdk declares zod as a peer dependency with a wide range\n // (^3.25 || ^4.0). Yarn does not dedupe the peer to the workspace's pinned zod, so\n // without a resolution it installs a separate zod under the SDK's own node_modules.\n // The two zod copies have structurally incompatible types, which breaks type\n // inference for registerTool inputSchema. Scope the resolution to the SDK so\n // other consumers (e.g. @tanstack/router-generator pinning zod@3) are unaffected.\n if (detectPackageManager() === 'yarn') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.resolutions = {\n ...packageJson.resolutions,\n '**/@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n };\n return packageJson;\n });\n }\n\n const localDevPort = assignPort(tree, project, 8000, {\n component: { info: TS_MCP_SERVER_GENERATOR_INFO, name: mcpTargetPrefix },\n });\n\n const mcpTargets = {\n ...project.targets,\n // Add targets for running the MCP server\n [`${mcpTargetPrefix}-serve-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/stdio.ts`],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-serve`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n },\n },\n },\n [`${mcpTargetPrefix}-dev`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n LOCAL_DEV: 'true',\n },\n },\n },\n [`${mcpTargetPrefix}-inspect`]: {\n executor: 'nx:run-commands',\n continuous: true,\n // Launch the inspector against the locally served HTTP server. The dev\n // target starts the server and any connected dependencies (e.g. a local\n // database).\n dependsOn: [`${mcpTargetPrefix}-dev`],\n options: {\n commands: [\n `mcp-inspector --transport http --server-url http://localhost:${localDevPort}/mcp`,\n ],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-inspect-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [\n `mcp-inspector -- tsx --watch ${relativeSourceDir}/stdio.ts`,\n ],\n cwd: '{projectRoot}',\n },\n },\n };\n\n // Aggregate `<mcp>-dev` under the project-level `dev` target.\n addComponentDevTarget(mcpTargets, `${mcpTargetPrefix}-dev`);\n\n updateProjectConfiguration(tree, project.name, {\n ...project,\n // Sort targets so their order is stable regardless of insertion order on\n // first run vs re-run.\n targets: sortObjectKeys(mcpTargets),\n });\n\n addComponentGeneratorMetadata(\n tree,\n project.name,\n TS_MCP_SERVER_GENERATOR_INFO,\n targetSourceDirRelativeToProjectRoot,\n mcpTargetPrefix,\n {\n port: localDevPort,\n rc: mcpServerNameClassName,\n auth,\n },\n );\n\n await addGeneratorMetricsIfApplicable(tree, [TS_MCP_SERVER_GENERATOR_INFO]);\n\n await ensureLicenseExceptions(tree, MCP_INSPECTOR_EXCEPTIONS);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default tsMcpServerGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readJson","updateJson","updateProjectConfiguration","ensureLicenseExceptions","MCP_INSPECTOR_EXCEPTIONS","addMcpServerInfra","addTypeScriptBundleTarget","resolveContainers","addDependenciesToPackageJson","addDockerScanTarget","nodeImageVersions","formatFilesInSubtree","FsCommands","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","kebabCase","toClassName","getNpmScope","addComponentDevTarget","addComponentGeneratorMetadata","addDependencyToTargetIfNotPresent","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","assignPort","sharedConstructsGenerator","BASE_IMAGES","TS_VERSIONS","withVersions","TS_MCP_SERVER_GENERATOR_INFO","filename","tsMcpServerGenerator","tree","options","project","exists","root","Error","defaultName","name","split","pop","mcpServerNameClassName","mcpTargetPrefix","targetSourceDirRelativeToProjectRoot","targetSourceDir","relativeSourceDir","replace","distDir","infra","auth","console","warn","projectPackageJsonPath","esm","type","dirname","adotVersion","jaegerVersion","nodeBaseImage","node","overwriteStrategy","KeepExisting","deps","devDeps","rootDevDeps","containers","dockerImageTag","targetFilePath","bundleOutputDir","dockerOutputDir","dockerTargetName","fs","targets","cache","outputs","executor","commands","cp","parallel","dependsOn","containerEngine","trivyTargetName","imageTags","iac","mcpServerNameKebabCase","projectName","delete","packageJson","resolutions","localDevPort","component","info","mcpTargets","continuous","cwd","env","PORT","LOCAL_DEV","port","rc","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EAEpBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,uBAAuB,QAAQ,0BAAuB;AAC/D,SAASC,wBAAwB,QAAQ,oCAAiC;AAC1E,SAASC,iBAAiB,QAAQ,6DAA0D;AAC5F,SAASC,yBAAyB,QAAQ,+BAA4B;AACtE,SAASC,iBAAiB,QAAQ,4BAAyB;AAC3D,SAASC,4BAA4B,QAAQ,8BAA2B;AACxE,SAASC,mBAAmB,EAAEC,iBAAiB,QAAQ,wBAAqB;AAC5E,SAASC,oBAAoB,QAAQ,wBAAqB;AAC1D,SAASC,UAAU,QAAQ,oBAAiB;AAC5C,SAASC,UAAU,QAAQ,qBAAkB;AAC7C,SAASC,mBAAmB,QAAQ,yBAAsB;AAC1D,SAASC,+BAA+B,QAAQ,yBAAsB;AACtE,SAASC,cAAc,QAAQ,+BAA4B;AAC3D,SAASC,SAAS,EAAEC,WAAW,QAAQ,uBAAoB;AAC3D,SAASC,WAAW,QAAQ,2BAAwB;AACpD,SACEC,qBAAqB,EACrBC,6BAA6B,EAC7BC,iCAAiC,EACjCC,gBAAgB,EAEhBC,mCAAmC,QAC9B,oBAAiB;AACxB,SAASC,cAAc,QAAQ,wBAAqB;AACpD,SAASC,UAAU,QAAQ,sBAAmB;AAC9C,SAASC,yBAAyB,QAAQ,mCAAgC;AAC1E,SAASC,WAAW,EAAEC,WAAW,EAAEC,YAAY,QAAQ,0BA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AAI,EACZV,8BACAe,sCACAD,iBACA;QACEwD,MAAMT;QACNU,IAAI1D;QACJQ;IACF;IAGF,MAAMrC,gCAAgCmB,MAAM;QAACH;KAA6B;IAE1E,MAAM5B,wBAAwB+B,MAAM9B;IAEpC,MAAMO,qBAAqBuB;IAC3B,OAAO,IACLpB,oBAAoBoB,MAAMC,QAAQoE,yBAAyB,EAAE;YAC3DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AAEF,eAAevE,qBAAqB"}
|
|
@@ -116,9 +116,14 @@ export const tsNxGeneratorGenerator = async (tree, options)=>{
|
|
|
116
116
|
NX_GENERATOR_GENERATOR_INFO
|
|
117
117
|
]);
|
|
118
118
|
await formatFilesInSubtree(tree);
|
|
119
|
+
// The generated generator.ts imports @nx/devkit, which must resolve for
|
|
120
|
+
// Nx to run it (bun's isolated layout doesn't hoist it from @nx/js).
|
|
119
121
|
return ()=>installDependencies(tree, options.preferInstallDependencies, {
|
|
120
122
|
languages: [
|
|
121
123
|
'typescript'
|
|
124
|
+
],
|
|
125
|
+
ensureResolvable: [
|
|
126
|
+
'@nx/devkit'
|
|
122
127
|
]
|
|
123
128
|
});
|
|
124
129
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/nx-generator/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n writeJson,\n} from '@nx/devkit';\nimport camelCase from 'lodash.camelcase';\nimport PackageJson from '../../../package.json' with { type: 'json' };\nimport { addStarExport, applyGritQL } from '../../utils/ast';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { esmVars } from '../../utils/module-format';\nimport { kebabCase, pascalCase, snakeCase } from '../../utils/names';\nimport {\n addComponentGeneratorMetadata,\n getGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { getRelativePathToRootByDirectory } from '../../utils/paths';\nimport { configureTsProjectAsNxPlugin } from '../nx-plugin/utils';\nimport type { TsNxGeneratorGeneratorSchema } from './schema';\n\nexport const NX_GENERATOR_GENERATOR_INFO = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsNxGeneratorGenerator = async (\n tree: Tree,\n options: TsNxGeneratorGeneratorSchema,\n): Promise<GeneratorCallback | void> => {\n const { name, directory, project: pluginProject, description } = options;\n\n const plugin = readProjectConfigurationUnqualified(tree, pluginProject);\n const sourceRoot = plugin.sourceRoot ?? joinPathFragments(plugin.root, 'src');\n const sourceRootParts = sourceRoot.split('/');\n const srcDir = sourceRootParts[sourceRootParts.length - 1];\n const generatorSubDir = directory ?? kebabCase(name);\n const generatorDir = joinPathFragments(sourceRoot, generatorSubDir);\n\n const rootPackageJson = tree.exists('package.json')\n ? readJson(tree, 'package.json')\n : undefined;\n const isNxPluginForAws = rootPackageJson?.name === '@aws/nx-plugin-source';\n\n // Configure the targeted project as an Nx Plugin\n configureTsProjectAsNxPlugin(tree, pluginProject);\n\n const enhancedOptions = {\n name,\n description,\n namePascalCase: pascalCase(name),\n nameCamelCase: camelCase(name),\n nameKebabCase: kebabCase(name),\n nameUpperSnakeCase: snakeCase(name).toUpperCase(),\n isNxPluginForAws,\n pathToProjectSourceRoot: getRelativePathToRootByDirectory(generatorSubDir),\n generatorDir,\n generatorSubDir,\n ...esmVars(tree),\n };\n\n // Add the common files, preserving any the user has already implemented\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'common'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add the files specific to this repo vs a local generator in another project\n if (isNxPluginForAws) {\n // Generators should be in the @aws/nx-plugin project\n if (pluginProject !== PackageJson.name) {\n throw new Error(\n `Generators should be added to the ${PackageJson.name} project.`,\n );\n }\n\n // Add the generator\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'generator',\n ),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Generate guide page in docs\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'docs',\n ),\n joinPathFragments('docs', 'src', 'content', 'docs', 'en', 'guides'),\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Update the docs config to add the page entry to the Generator guides sidebar section\n await applyGritQL(\n tree,\n joinPathFragments('docs', 'astro.config.mjs'),\n `\\`items: [$items]\\` where { $items <: within \\`sidebar: [$_]\\`, $items <: contains \\`'ts#project'\\`, $items <: not contains \\`'/guides/${enhancedOptions.nameKebabCase}'\\`, $items += \\`, { label: '${name}', link: '/guides/${enhancedOptions.nameKebabCase}' }\\` }`,\n );\n\n // Expose the generator from the SDK for known prefixes (ts# / py#)\n addSdkExport(tree, plugin.root, name, generatorSubDir, enhancedOptions);\n } else {\n // Local generator in a project other than nx-plugin-for-aws\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'local'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n const indexPath = joinPathFragments(sourceRoot, 'index.ts');\n if (tree.exists(indexPath)) {\n // ESM projects require the explicit `.js` extension; `addStarExport`\n // strips it for CommonJS workspaces.\n await addStarExport(tree, indexPath, `./${generatorSubDir}/generator.js`);\n }\n\n addComponentGeneratorMetadata(\n tree,\n plugin.name,\n NX_GENERATOR_GENERATOR_INFO,\n joinPathFragments(srcDir, generatorSubDir),\n name,\n );\n }\n\n const factoryBasePath = `./${srcDir}/${generatorSubDir}`;\n\n // Update generators.json\n const generatorsJsonPath = joinPathFragments(plugin.root, 'generators.json');\n const generatorsJson = tree.exists(generatorsJsonPath)\n ? readJson(tree, generatorsJsonPath)\n : { generators: {} };\n // Metrics are only tracked within the @aws/nx-plugin repo. Reuse the existing\n // metric for a same-name re-run, otherwise allocate a new one.\n let metric: string | undefined;\n if (isNxPluginForAws) {\n const existingMetrics = Object.values(generatorsJson?.generators ?? {})\n .map((g: any) => g.metric)\n .filter((m): m is string => typeof m === 'string');\n metric =\n generatorsJson?.generators?.[name]?.metric ??\n (existingMetrics.length > 0 ? incrementMetric(existingMetrics) : 'g1');\n }\n writeJson(tree, generatorsJsonPath, {\n ...generatorsJson,\n generators: sortObjectKeys({\n ...generatorsJson?.generators,\n [name]: {\n factory: `${factoryBasePath}/generator`,\n schema: `${factoryBasePath}/schema.json`,\n description:\n description ?? 'TODO: Add short description of the generator',\n ...(isNxPluginForAws ? { metric } : {}),\n },\n }),\n });\n\n await addGeneratorMetricsIfApplicable(tree, [NX_GENERATOR_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nconst incrementMetric = (metrics: string[]): string => {\n const maxMetric = Math.max(...metrics.map((m) => Number(m.slice(1))));\n return `g${maxMetric + 1}`;\n};\n\n// Maps a generator name prefix to the SDK entry point that should re-export it\nconst SDK_EXPORT_PREFIXES: Record<string, string> = {\n 'ts#': 'ts',\n 'py#': 'py',\n};\n\n// Re-exports a generated generator from the matching SDK entry point so it is\n// available programmatically as part of @aws/nx-plugin's SDK\nconst addSdkExport = (\n tree: Tree,\n pluginRoot: string,\n name: string,\n generatorSubDir: string,\n options: { nameCamelCase: string; namePascalCase: string },\n): void => {\n const prefix = Object.keys(SDK_EXPORT_PREFIXES).find((p) =>\n name.startsWith(p),\n );\n if (!prefix) {\n return;\n }\n\n const sdkPath = joinPathFragments(\n pluginRoot,\n 'src',\n 'sdk',\n `${SDK_EXPORT_PREFIXES[prefix]}.ts`,\n );\n const generatorExport = `${options.nameCamelCase}Generator`;\n const schemaExport = `${options.namePascalCase}GeneratorSchema`;\n const moduleBase = `../${generatorSubDir}`;\n\n const contents = tree.exists(sdkPath) ? tree.read(sdkPath).toString() : '';\n // Idempotent: skip if this generator is already exported\n if (contents.includes(`${moduleBase}/generator`)) {\n return;\n }\n\n const block = `// ${options.namePascalCase} Generator\\nexport { ${generatorExport} } from '${moduleBase}/generator';\\nexport type { ${schemaExport} } from '${moduleBase}/schema';\\n`;\n\n const prefixContents = contents.trim()\n ? `${contents.replace(/\\s*$/, '')}\\n\\n`\n : '';\n tree.write(sdkPath, `${prefixContents}${block}`);\n};\n\nexport default tsNxGeneratorGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readJson","writeJson","camelCase","PackageJson","type","addStarExport","applyGritQL","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","esmVars","kebabCase","pascalCase","snakeCase","addComponentGeneratorMetadata","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","getRelativePathToRootByDirectory","configureTsProjectAsNxPlugin","NX_GENERATOR_GENERATOR_INFO","filename","tsNxGeneratorGenerator","tree","options","name","directory","project","pluginProject","description","plugin","sourceRoot","root","sourceRootParts","split","srcDir","length","generatorSubDir","generatorDir","rootPackageJson","exists","undefined","isNxPluginForAws","enhancedOptions","namePascalCase","nameCamelCase","nameKebabCase","nameUpperSnakeCase","toUpperCase","pathToProjectSourceRoot","dirname","overwriteStrategy","KeepExisting","Error","addSdkExport","indexPath","factoryBasePath","generatorsJsonPath","generatorsJson","generators","metric","existingMetrics","Object","values","map","g","filter","m","incrementMetric","factory","schema","preferInstallDependencies","languages","metrics","maxMetric","Math","max","Number","slice","SDK_EXPORT_PREFIXES","pluginRoot","prefix","keys","find","p","startsWith","sdkPath","generatorExport","schemaExport","moduleBase","contents","read","toString","includes","block","prefixContents","trim","replace","write"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,a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AAE2C,gBAAgB,SAAS,EAAEE,WAAW,4BAA4B,EAAED,aAAa,SAAS,EAAEC,WAAW,WAAW,CAAC;IAErL,MAAMM,iBAAiBL,SAASM,IAAI,KAChC,GAAGN,SAASO,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,GACrC;IACJ1E,KAAK2E,KAAK,CAACZ,SAAS,GAAGS,iBAAiBD,OAAO;AACjD;AAEA,eAAexE,uBAAuB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/nx-generator/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n writeJson,\n} from '@nx/devkit';\nimport camelCase from 'lodash.camelcase';\nimport PackageJson from '../../../package.json' with { type: 'json' };\nimport { addStarExport, applyGritQL } from '../../utils/ast';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { esmVars } from '../../utils/module-format';\nimport { kebabCase, pascalCase, snakeCase } from '../../utils/names';\nimport {\n addComponentGeneratorMetadata,\n getGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { getRelativePathToRootByDirectory } from '../../utils/paths';\nimport { configureTsProjectAsNxPlugin } from '../nx-plugin/utils';\nimport type { TsNxGeneratorGeneratorSchema } from './schema';\n\nexport const NX_GENERATOR_GENERATOR_INFO = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsNxGeneratorGenerator = async (\n tree: Tree,\n options: TsNxGeneratorGeneratorSchema,\n): Promise<GeneratorCallback | void> => {\n const { name, directory, project: pluginProject, description } = options;\n\n const plugin = readProjectConfigurationUnqualified(tree, pluginProject);\n const sourceRoot = plugin.sourceRoot ?? joinPathFragments(plugin.root, 'src');\n const sourceRootParts = sourceRoot.split('/');\n const srcDir = sourceRootParts[sourceRootParts.length - 1];\n const generatorSubDir = directory ?? kebabCase(name);\n const generatorDir = joinPathFragments(sourceRoot, generatorSubDir);\n\n const rootPackageJson = tree.exists('package.json')\n ? readJson(tree, 'package.json')\n : undefined;\n const isNxPluginForAws = rootPackageJson?.name === '@aws/nx-plugin-source';\n\n // Configure the targeted project as an Nx Plugin\n configureTsProjectAsNxPlugin(tree, pluginProject);\n\n const enhancedOptions = {\n name,\n description,\n namePascalCase: pascalCase(name),\n nameCamelCase: camelCase(name),\n nameKebabCase: kebabCase(name),\n nameUpperSnakeCase: snakeCase(name).toUpperCase(),\n isNxPluginForAws,\n pathToProjectSourceRoot: getRelativePathToRootByDirectory(generatorSubDir),\n generatorDir,\n generatorSubDir,\n ...esmVars(tree),\n };\n\n // Add the common files, preserving any the user has already implemented\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'common'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add the files specific to this repo vs a local generator in another project\n if (isNxPluginForAws) {\n // Generators should be in the @aws/nx-plugin project\n if (pluginProject !== PackageJson.name) {\n throw new Error(\n `Generators should be added to the ${PackageJson.name} project.`,\n );\n }\n\n // Add the generator\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'generator',\n ),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Generate guide page in docs\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'docs',\n ),\n joinPathFragments('docs', 'src', 'content', 'docs', 'en', 'guides'),\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Update the docs config to add the page entry to the Generator guides sidebar section\n await applyGritQL(\n tree,\n joinPathFragments('docs', 'astro.config.mjs'),\n `\\`items: [$items]\\` where { $items <: within \\`sidebar: [$_]\\`, $items <: contains \\`'ts#project'\\`, $items <: not contains \\`'/guides/${enhancedOptions.nameKebabCase}'\\`, $items += \\`, { label: '${name}', link: '/guides/${enhancedOptions.nameKebabCase}' }\\` }`,\n );\n\n // Expose the generator from the SDK for known prefixes (ts# / py#)\n addSdkExport(tree, plugin.root, name, generatorSubDir, enhancedOptions);\n } else {\n // Local generator in a project other than nx-plugin-for-aws\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'local'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n const indexPath = joinPathFragments(sourceRoot, 'index.ts');\n if (tree.exists(indexPath)) {\n // ESM projects require the explicit `.js` extension; `addStarExport`\n // strips it for CommonJS workspaces.\n await addStarExport(tree, indexPath, `./${generatorSubDir}/generator.js`);\n }\n\n addComponentGeneratorMetadata(\n tree,\n plugin.name,\n NX_GENERATOR_GENERATOR_INFO,\n joinPathFragments(srcDir, generatorSubDir),\n name,\n );\n }\n\n const factoryBasePath = `./${srcDir}/${generatorSubDir}`;\n\n // Update generators.json\n const generatorsJsonPath = joinPathFragments(plugin.root, 'generators.json');\n const generatorsJson = tree.exists(generatorsJsonPath)\n ? readJson(tree, generatorsJsonPath)\n : { generators: {} };\n // Metrics are only tracked within the @aws/nx-plugin repo. Reuse the existing\n // metric for a same-name re-run, otherwise allocate a new one.\n let metric: string | undefined;\n if (isNxPluginForAws) {\n const existingMetrics = Object.values(generatorsJson?.generators ?? {})\n .map((g: any) => g.metric)\n .filter((m): m is string => typeof m === 'string');\n metric =\n generatorsJson?.generators?.[name]?.metric ??\n (existingMetrics.length > 0 ? incrementMetric(existingMetrics) : 'g1');\n }\n writeJson(tree, generatorsJsonPath, {\n ...generatorsJson,\n generators: sortObjectKeys({\n ...generatorsJson?.generators,\n [name]: {\n factory: `${factoryBasePath}/generator`,\n schema: `${factoryBasePath}/schema.json`,\n description:\n description ?? 'TODO: Add short description of the generator',\n ...(isNxPluginForAws ? { metric } : {}),\n },\n }),\n });\n\n await addGeneratorMetricsIfApplicable(tree, [NX_GENERATOR_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n\n // The generated generator.ts imports @nx/devkit, which must resolve for\n // Nx to run it (bun's isolated layout doesn't hoist it from @nx/js).\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: ['@nx/devkit'],\n });\n};\n\nconst incrementMetric = (metrics: string[]): string => {\n const maxMetric = Math.max(...metrics.map((m) => Number(m.slice(1))));\n return `g${maxMetric + 1}`;\n};\n\n// Maps a generator name prefix to the SDK entry point that should re-export it\nconst SDK_EXPORT_PREFIXES: Record<string, string> = {\n 'ts#': 'ts',\n 'py#': 'py',\n};\n\n// Re-exports a generated generator from the matching SDK entry point so it is\n// available programmatically as part of @aws/nx-plugin's SDK\nconst addSdkExport = (\n tree: Tree,\n pluginRoot: string,\n name: string,\n generatorSubDir: string,\n options: { nameCamelCase: string; namePascalCase: string },\n): void => {\n const prefix = Object.keys(SDK_EXPORT_PREFIXES).find((p) =>\n name.startsWith(p),\n );\n if (!prefix) {\n return;\n }\n\n const sdkPath = joinPathFragments(\n pluginRoot,\n 'src',\n 'sdk',\n `${SDK_EXPORT_PREFIXES[prefix]}.ts`,\n );\n const generatorExport = `${options.nameCamelCase}Generator`;\n const schemaExport = `${options.namePascalCase}GeneratorSchema`;\n const moduleBase = `../${generatorSubDir}`;\n\n const contents = tree.exists(sdkPath) ? tree.read(sdkPath).toString() : '';\n // Idempotent: skip if this generator is already exported\n if (contents.includes(`${moduleBase}/generator`)) {\n return;\n }\n\n const block = `// ${options.namePascalCase} Generator\\nexport { ${generatorExport} } from '${moduleBase}/generator';\\nexport type { ${schemaExport} } from '${moduleBase}/schema';\\n`;\n\n const prefixContents = contents.trim()\n ? `${contents.replace(/\\s*$/, '')}\\n\\n`\n : '';\n tree.write(sdkPath, `${prefixContents}${block}`);\n};\n\nexport default tsNxGeneratorGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readJson","writeJson","camelCase","PackageJson","type","addStarExport","applyGritQL","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","esmVars","kebabCase","pascalCase","snakeCase","addComponentGeneratorMetadata","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","getRelativePathToRootByDirectory","configureTsProjectAsNxPlugin","NX_GENERATOR_GENERATOR_INFO","filename","tsNxGeneratorGenerator","tree","options","name","directory","project","pluginProject","description","plugin","sourceRoot","root","sourceRootParts","split","srcDir","length","generatorSubDir","generatorDir","rootPackageJson","exists","undefined","isNxPluginForAws","enhancedOptions","namePascalCase","nameCamelCase","nameKebabCase","nameUpperSnakeCase","toUpperCase","pathToProjectSourceRoot","dirname","overwriteStrategy","KeepExisting","Error","addSdkExport","indexPath","factoryBasePath","generatorsJsonPath","generatorsJson","generators","metric","existingMetrics","Object","values","map","g","filter","m","incrementMetric","factory","schema","preferInstallDependencies","languages","ensureResolvable","metrics","maxMetric","Math","max","Number","slice","SDK_EXPORT_PREFIXES","pluginRoot","prefix","keys","find","p","startsWith","sdkPath","generatorExport","schemaExport","moduleBase","contents","read","toString","includes","block","prefixContents","trim","replace","write"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,SAAS,QACJ,aAAa;AACpB,OAAOC,eAAe,mBAAmB;AACzC,OAAOC,iBAAiB,6BAA6B;IAAEC,MAAM;AAAO,EAAE;AACtE,SAASC,aAAa,EAAEC,WAAW,QAAQ,qBAAkB;AAC7D,SAASC,oBAAoB,QAAQ,wBAAqB;AAC1D,SAASC,mBAAmB,QAAQ,yBAAsB;AAC1D,SAASC,+BAA+B,QAAQ,yBAAsB;AACtE,SAASC,OAAO,QAAQ,+BAA4B;AACpD,SAASC,SAAS,EAAEC,UA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server files > test-plugin
|
|
|
123
123
|
|
|
124
124
|
## General Instructions
|
|
125
125
|
|
|
126
|
-
-
|
|
127
|
-
- pnpm add -w
|
|
128
|
-
- yarn add -D <package
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
- (Omit -D for production dependencies)
|
|
126
|
+
- Each project declares the third-party runtime dependencies its source imports in its own \`package.json\`; shared build/test tooling is declared in the root \`package.json\` \`devDependencies\`. Versions follow a single version policy, recorded in the package manager's dependency catalog where supported (referenced as \`catalog:\`). Install with the appropriate command for your package manager:
|
|
127
|
+
- Add a project runtime dependency: \`pnpm add <package> --filter <project>\` / \`yarn workspace <project> add <package>\` / \`npm install <package> -w <project>\` / \`bun add <package> --cwd <project-directory>\`
|
|
128
|
+
- Add a shared dev tool at the root: \`pnpm add -Dw <package>\` / \`yarn add -D <package>\` / \`npm install --legacy-peer-deps -D <package>\` / \`bun install -D <package>\`
|
|
129
|
+
- The \`noUndeclaredDependencies\` lint rule enforces that a project's source only imports packages declared in its own \`package.json\`
|
|
130
|
+
- Projects in the same workspace can import one another directly by package name (eg \`@workspace-name/project-name\`) without declaring a dependency in \`package.json\` — TypeScript path aliases in \`tsconfig.base.json\` resolve these imports
|
|
132
131
|
- When specifying project names as arguments to generators, prefer the _fully qualified_ project name, for example \`@workspace-name/project-name\`. Check the \`project.json\` file for the specific package to find its fully qualified name
|
|
133
132
|
- When no generator exists for a specific framework required, look for more generic project generators if availalbe and build on top of these.
|
|
134
133
|
|
|
@@ -26,12 +26,11 @@
|
|
|
26
26
|
|
|
27
27
|
## General Instructions
|
|
28
28
|
|
|
29
|
-
-
|
|
30
|
-
- pnpm add -w
|
|
31
|
-
- yarn add -D <package
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
- (Omit -D for production dependencies)
|
|
29
|
+
- Each project declares the third-party runtime dependencies its source imports in its own `package.json`; shared build/test tooling is declared in the root `package.json` `devDependencies`. Versions follow a single version policy, recorded in the package manager's dependency catalog where supported (referenced as `catalog:`). Install with the appropriate command for your package manager:
|
|
30
|
+
- Add a project runtime dependency: `pnpm add <package> --filter <project>` / `yarn workspace <project> add <package>` / `npm install <package> -w <project>` / `bun add <package> --cwd <project-directory>`
|
|
31
|
+
- Add a shared dev tool at the root: `pnpm add -Dw <package>` / `yarn add -D <package>` / `npm install --legacy-peer-deps -D <package>` / `bun install -D <package>`
|
|
32
|
+
- The `noUndeclaredDependencies` lint rule enforces that a project's source only imports packages declared in its own `package.json`
|
|
33
|
+
- Projects in the same workspace can import one another directly by package name (eg `@workspace-name/project-name`) without declaring a dependency in `package.json` — TypeScript path aliases in `tsconfig.base.json` resolve these imports
|
|
35
34
|
- When specifying project names as arguments to generators, prefer the _fully qualified_ project name, for example `@workspace-name/project-name`. Check the `project.json` file for the specific package to find its fully qualified name
|
|
36
35
|
- When no generator exists for a specific framework required, look for more generic project generators if availalbe and build on top of these.
|
|
37
36
|
|
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
*/ import {
|
|
5
|
-
import
|
|
6
|
-
type: 'json'
|
|
7
|
-
};
|
|
4
|
+
*/ import { joinPathFragments, updateJson, writeJson } from "@nx/devkit";
|
|
5
|
+
import { addDependenciesToPackageJson } from "../../utils/dependencies.js";
|
|
8
6
|
import { isEsmWorkspace } from "../../utils/module-format.js";
|
|
9
|
-
import { readProjectConfigurationUnqualified } from "../../utils/nx.js";
|
|
7
|
+
import { nxPluginSelfDependency, readProjectConfigurationUnqualified } from "../../utils/nx.js";
|
|
10
8
|
import { withVersions } from "../../utils/versions.js";
|
|
11
9
|
/**
|
|
12
10
|
* Configures a TypeScript project as an Nx Plugin
|
|
@@ -41,16 +39,16 @@ import { withVersions } from "../../utils/versions.js";
|
|
|
41
39
|
pkg.generators ??= './generators.json';
|
|
42
40
|
return pkg;
|
|
43
41
|
});
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
const selfDependency = nxPluginSelfDependency(tree);
|
|
43
|
+
// Empty inside the plugin's own monorepo, where the plugin is the source
|
|
44
|
+
// rather than a dependency.
|
|
45
|
+
if (Object.keys(selfDependency).length > 0) {
|
|
47
46
|
// Add the required dependencies to the root package.json, and project's package.json
|
|
48
47
|
const deps = {
|
|
49
48
|
...withVersions([
|
|
50
49
|
'@nx/devkit'
|
|
51
50
|
]),
|
|
52
|
-
|
|
53
|
-
[PackageJson.name]: `^${PackageJson.version}`
|
|
51
|
+
...selfDependency
|
|
54
52
|
};
|
|
55
53
|
// Generated workspaces are `"type": "module"`, so Nx loads the plugin's
|
|
56
54
|
// `.ts` generators as ESM via Node's native type stripping — no swc/ts-node
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/nx-plugin/utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/nx-plugin/utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n joinPathFragments,\n type Tree,\n updateJson,\n writeJson,\n} from '@nx/devkit';\nimport { addDependenciesToPackageJson } from '../../utils/dependencies';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport {\n nxPluginSelfDependency,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { withVersions } from '../../utils/versions';\n\n/**\n * Configures a TypeScript project as an Nx Plugin\n */\nexport const configureTsProjectAsNxPlugin = (\n tree: Tree,\n projectName: string,\n) => {\n const project = readProjectConfigurationUnqualified(tree, projectName);\n\n const tsConfigPath = joinPathFragments(project.root, 'tsconfig.json');\n if (!tree.exists(tsConfigPath)) {\n throw new Error(\n `Selected plugin project ${projectName} is not a TypeScript project`,\n );\n }\n\n // Create an empty generators.json if one dosn't exist\n const generatorsJsonPath = joinPathFragments(project.root, 'generators.json');\n if (!tree.exists(generatorsJsonPath)) {\n writeJson(tree, generatorsJsonPath, {\n generators: {},\n });\n }\n\n // Create a package.json if one doesn't exist, and configure \"type\", \"main\"\n // and \"generators\"\n const pluginPackageJsonPath = joinPathFragments(project.root, 'package.json');\n if (!tree.exists(pluginPackageJsonPath)) {\n writeJson(tree, pluginPackageJsonPath, {\n name: project.name,\n });\n }\n const esm = isEsmWorkspace(tree);\n updateJson(tree, pluginPackageJsonPath, (pkg) => {\n // Match the plugin's module system to the workspace. Nx loads `.ts`\n // generators via Node's native type stripping, as ESM (workspace root is\n // `type: module`) or CommonJS accordingly.\n pkg.type ??= esm ? 'module' : 'commonjs';\n pkg.main ??= esm ? './src/index.js' : './src/index';\n pkg.generators ??= './generators.json';\n return pkg;\n });\n\n const selfDependency = nxPluginSelfDependency(tree);\n\n // Empty inside the plugin's own monorepo, where the plugin is the source\n // rather than a dependency.\n if (Object.keys(selfDependency).length > 0) {\n // Add the required dependencies to the root package.json, and project's package.json\n const deps = {\n ...withVersions(['@nx/devkit']),\n ...selfDependency,\n };\n // Generated workspaces are `\"type\": \"module\"`, so Nx loads the plugin's\n // `.ts` generators as ESM via Node's native type stripping — no swc/ts-node\n // transpiler is required.\n addDependenciesToPackageJson(tree, {}, deps);\n addDependenciesToPackageJson(tree, deps, {}, pluginPackageJsonPath);\n }\n};\n"],"names":["joinPathFragments","updateJson","writeJson","addDependenciesToPackageJson","isEsmWorkspace","nxPluginSelfDependency","readProjectConfigurationUnqualified","withVersions","configureTsProjectAsNxPlugin","tree","projectName","project","tsConfigPath","root","exists","Error","generatorsJsonPath","generators","pluginPackageJsonPath","name","esm","pkg","type","main","selfDependency","Object","keys","length","deps"],"mappings":"AAAA;;;CAGC,GACD,SACEA,iBAAiB,EAEjBC,UAAU,EACVC,SAAS,QACJ,aAAa;AACpB,SAASC,4BAA4B,QAAQ,8BA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,wEAAwE;QACxE,4EAA4E;QAC5E,0BAA0B;QAC1BrB,6BAA6BM,MAAM,CAAC,GAAGmB;QACvCzB,6BAA6BM,MAAMmB,MAAM,CAAC,GAAGV;IAC/C;AACF,EAAE"}
|
|
@@ -105,6 +105,7 @@ exports[`ts#rdb generator > should add mysql prisma dependencies when engine is
|
|
|
105
105
|
|
|
106
106
|
exports[`ts#rdb generator > should add mysql prisma dependencies when engine is MySQL > packages/db/src/migration-handler.ts 1`] = `
|
|
107
107
|
"import { execFile } from 'node:child_process';
|
|
108
|
+
import { join } from 'node:path';
|
|
108
109
|
import { promisify } from 'node:util';
|
|
109
110
|
import { getDatabaseSecret, withConnectionRetry } from './utils.js';
|
|
110
111
|
|
|
@@ -122,7 +123,8 @@ const buildDatabaseUrl = async (): Promise<string> => {
|
|
|
122
123
|
export const handler = async () => {
|
|
123
124
|
await withConnectionRetry(async () => {
|
|
124
125
|
const databaseUrl = await buildDatabaseUrl();
|
|
125
|
-
|
|
126
|
+
const prisma = join(__dirname, 'node_modules', '.bin', 'prisma');
|
|
127
|
+
await promisify(execFile)(prisma, ['migrate', 'deploy'], {
|
|
126
128
|
cwd: __dirname,
|
|
127
129
|
env: {
|
|
128
130
|
...process.env,
|
|
@@ -3882,6 +3884,7 @@ exports[`ts#rdb generator > should generate the aurora shared construct > packag
|
|
|
3882
3884
|
|
|
3883
3885
|
exports[`ts#rdb generator > should generate the aurora shared construct > packages/db/src/migration-handler.ts 1`] = `
|
|
3884
3886
|
"import { execFile } from 'node:child_process';
|
|
3887
|
+
import { join } from 'node:path';
|
|
3885
3888
|
import { promisify } from 'node:util';
|
|
3886
3889
|
import { getDatabaseSecret, withConnectionRetry } from './utils.js';
|
|
3887
3890
|
|
|
@@ -3899,7 +3902,8 @@ const buildDatabaseUrl = async (): Promise<string> => {
|
|
|
3899
3902
|
export const handler = async () => {
|
|
3900
3903
|
await withConnectionRetry(async () => {
|
|
3901
3904
|
const databaseUrl = await buildDatabaseUrl();
|
|
3902
|
-
|
|
3905
|
+
const prisma = join(__dirname, 'node_modules', '.bin', 'prisma');
|
|
3906
|
+
await promisify(execFile)(prisma, ['migrate', 'deploy'], {
|
|
3903
3907
|
cwd: __dirname,
|
|
3904
3908
|
env: {
|
|
3905
3909
|
...process.env,
|
|
@@ -4680,9 +4684,13 @@ WORKDIR \${LAMBDA_TASK_ROOT}
|
|
|
4680
4684
|
|
|
4681
4685
|
# npm blocks dependency install scripts by default; allow prisma's so its
|
|
4682
4686
|
# postinstall downloads the schema-engine binary needed to run migrations.
|
|
4687
|
+
# npm is removed once prisma is installed — the handler runs prisma's own
|
|
4688
|
+
# binary directly, and npm's bundled dependencies would otherwise carry known
|
|
4689
|
+
# HIGH/CRITICAL vulnerabilities into the image.
|
|
4683
4690
|
RUN printf 'allow-scripts[]=prisma\\nallow-scripts[]=@prisma/engines\\n' > .npmrc \\
|
|
4684
4691
|
&& npm install prisma@7.8.0 \\
|
|
4685
|
-
&& rm .npmrc
|
|
4692
|
+
&& rm .npmrc \\
|
|
4693
|
+
&& npm uninstall -g npm
|
|
4686
4694
|
|
|
4687
4695
|
COPY index.js ./index.js
|
|
4688
4696
|
COPY prisma ./prisma
|
|
@@ -7,7 +7,6 @@ import { addDestructuredImport, applyGritQL } from "../../../utils/ast.js";
|
|
|
7
7
|
import { formatFilesInSubtree } from "../../../utils/format.js";
|
|
8
8
|
import { addGeneratorMetricsIfApplicable } from "../../../utils/metrics.js";
|
|
9
9
|
import { pascalCase } from "../../../utils/names.js";
|
|
10
|
-
import { toScopeAlias } from "../../../utils/npm-scope.js";
|
|
11
10
|
import { addDependencyToTargetIfNotPresent, getGeneratorInfo, readProjectConfigurationUnqualified } from "../../../utils/nx.js";
|
|
12
11
|
import { injectRdsCaBundleIntoDockerfile } from "../utils.js";
|
|
13
12
|
export const TS_RDB_AGENT_CONNECTION_GENERATOR_INFO = getGeneratorInfo(import.meta.filename);
|
|
@@ -28,7 +27,7 @@ export const tsRdbAgentConnectionGenerator = async (tree, options)=>{
|
|
|
28
27
|
const rdbBaseName = targetProject.name.split('/').pop();
|
|
29
28
|
const rdbNameCamel = camelCase(rdbBaseName);
|
|
30
29
|
const rdbNamePascal = pascalCase(rdbBaseName);
|
|
31
|
-
const rdbPackageAlias =
|
|
30
|
+
const rdbPackageAlias = targetProject.name;
|
|
32
31
|
const getterAlias = `getPrisma as get${rdbNamePascal}`;
|
|
33
32
|
const agentSourceDir = joinPathFragments(sourceProject.root, 'src', agentName);
|
|
34
33
|
const agentPath = joinPathFragments(agentSourceDir, 'agent.ts');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/ts/rdb/agent-connection/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n joinPathFragments,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport camelCase from 'lodash.camelcase';\nimport { addDestructuredImport, applyGritQL } from '../../../utils/ast';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics';\nimport { pascalCase } from '../../../utils/names';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/ts/rdb/agent-connection/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n joinPathFragments,\n type Tree,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport camelCase from 'lodash.camelcase';\nimport { addDestructuredImport, applyGritQL } from '../../../utils/ast';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics';\nimport { pascalCase } from '../../../utils/names';\nimport {\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../../utils/nx';\nimport { injectRdsCaBundleIntoDockerfile } from '../utils';\nimport type { TsRdbAgentConnectionGeneratorSchema } from './schema';\n\nexport const TS_RDB_AGENT_CONNECTION_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport const tsRdbAgentConnectionGenerator = async (\n tree: Tree,\n options: TsRdbAgentConnectionGeneratorSchema,\n): Promise<void> => {\n const sourceProject = readProjectConfigurationUnqualified(\n tree,\n options.sourceProject,\n );\n const targetProject = readProjectConfigurationUnqualified(\n tree,\n options.targetProject,\n );\n\n const agentName = options.sourceComponent?.name ?? 'agent';\n const devTarget = `${agentName}-dev`;\n\n if (sourceProject.targets?.[devTarget]) {\n addDependencyToTargetIfNotPresent(sourceProject, devTarget, {\n projects: [targetProject.name],\n target: 'dev',\n });\n updateProjectConfiguration(tree, sourceProject.name, sourceProject);\n }\n\n const rdbBaseName = targetProject.name.split('/').pop();\n const rdbNameCamel = camelCase(rdbBaseName);\n const rdbNamePascal = pascalCase(rdbBaseName);\n const rdbPackageAlias = targetProject.name;\n const getterAlias = `getPrisma as get${rdbNamePascal}`;\n\n const agentSourceDir = joinPathFragments(\n sourceProject.root,\n 'src',\n agentName,\n );\n const agentPath = joinPathFragments(agentSourceDir, 'agent.ts');\n\n // Dockerfile: install RDS CA bundle for direct Aurora SSL connections\n const dockerfilePath = joinPathFragments(agentSourceDir, 'Dockerfile');\n injectRdsCaBundleIntoDockerfile(tree, dockerfilePath);\n\n if (tree.exists(agentPath)) {\n await addDestructuredImport(\n tree,\n agentPath,\n [getterAlias],\n rdbPackageAlias,\n );\n\n // Block body form: export const getAgent = async () => { ... }\n await applyGritQL(\n tree,\n agentPath,\n `\\`export const getAgent = async () => { $body }\\` => raw\\`export const getAgent = async () => {\n const ${rdbNameCamel} = await get${rdbNamePascal}();\n $body\n}\\` where { $body <: not some \\`const ${rdbNameCamel} = await get${rdbNamePascal}()\\` }`,\n );\n\n // Expression body form: export const getAgent = async () => expr\n await applyGritQL(\n tree,\n agentPath,\n `\\`export const getAgent = async () => $expr\\` => raw\\`export const getAgent = async () => {\n const ${rdbNameCamel} = await get${rdbNamePascal}();\n return $expr;\n}\\` where { $expr <: not \\`{ $_ }\\` }`,\n );\n\n // Add $on error handler after the db declaration.\n // Done via string replacement because GritQL treats $on as a metavariable.\n const dbDecl = `const ${rdbNameCamel} = await get${rdbNamePascal}();`;\n const onCall = `${rdbNameCamel}.$on('error', console.error);`;\n const content = tree.read(agentPath, 'utf-8')!;\n if (content.includes(dbDecl) && !content.includes(`${rdbNameCamel}.$on`)) {\n tree.write(agentPath, content.replace(dbDecl, `${dbDecl}\\n ${onCall}`));\n }\n }\n\n await addGeneratorMetricsIfApplicable(tree, [\n TS_RDB_AGENT_CONNECTION_GENERATOR_INFO,\n ]);\n await formatFilesInSubtree(tree);\n};\n\nexport default tsRdbAgentConnectionGenerator;\n"],"names":["joinPathFragments","updateProjectConfiguration","camelCase","addDestructuredImport","applyGritQL","formatFilesInSubtree","addGeneratorMetricsIfApplicable","pascalCase","addDependencyToTargetIfNotPresent","getGeneratorInfo","readProjectConfigurationUnqualified","injectRdsCaBundleIntoDockerfile","TS_RDB_AGENT_CONNECTION_GENERATOR_INFO","filename","tsRdbAgentConnectionGenerator","tree","options","sourceProject","targetProject","agentName","sourceComponent","name","devTarget","targets","projects","target","rdbBaseName","split","pop","rdbNameCamel","rdbNamePascal","rdbPackageAlias","getterAlias","agentSourceDir","root","agentPath","dockerfilePath","exists","dbDecl","onCall","content","read","includes","write","replace"],"mappings":"AAAA;;;CAGC,GACD,SACEA,iBAAiB,EAEjBC,0BAA0B,QACrB,aAAa;AACpB,OAAOC,eAAe,mBAAmB;AACzC,SAASC,qBAAqB,EAAEC,WAAW,QAAQ,wBAAqB;AACxE,SAASC,oBAAoB,QAAQ,2BAAwB;AAC7D,SAASC,+BAA+B,QAAQ,4BAAyB;AACzE,SAASC,UAAU,QAAQ,0BAAuB;AAClD,SACEC,iCAAiC,EACjCC,gBAAgB,EAEhBC,mCAAmC,QAC9B,uB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AEN,aAAa,YAAY,EAAEC,cAAc;;qCAEd,CAAC;QAGlC,kDAAkD;QAClD,2EAA2E;QAC3E,MAAMQ,SAAS,CAAC,MAAM,EAAET,aAAa,YAAY,EAAEC,cAAc,GAAG,CAAC;QACrE,MAAMS,SAAS,GAAGV,aAAa,6BAA6B,CAAC;QAC7D,MAAMW,UAAUzB,KAAK0B,IAAI,CAACN,WAAW;QACrC,IAAIK,QAAQE,QAAQ,CAACJ,WAAW,CAACE,QAAQE,QAAQ,CAAC,GAAGb,aAAa,IAAI,CAAC,GAAG;YACxEd,KAAK4B,KAAK,CAACR,WAAWK,QAAQI,OAAO,CAACN,QAAQ,GAAGA,OAAO,IAAI,EAAEC,QAAQ;QACxE;IACF;IAEA,MAAMjC,gCAAgCS,MAAM;QAC1CH;KACD;IACD,MAAMP,qBAAqBU;AAC7B,EAAE;AAEF,eAAeD,8BAA8B"}
|
|
@@ -14,9 +14,13 @@ WORKDIR ${LAMBDA_TASK_ROOT}
|
|
|
14
14
|
|
|
15
15
|
# npm blocks dependency install scripts by default; allow prisma's so its
|
|
16
16
|
# postinstall downloads the schema-engine binary needed to run migrations.
|
|
17
|
+
# npm is removed once prisma is installed — the handler runs prisma's own
|
|
18
|
+
# binary directly, and npm's bundled dependencies would otherwise carry known
|
|
19
|
+
# HIGH/CRITICAL vulnerabilities into the image.
|
|
17
20
|
RUN printf 'allow-scripts[]=prisma\nallow-scripts[]=@prisma/engines\n' > .npmrc \
|
|
18
21
|
&& npm install prisma@<%= prismaVersion %> \
|
|
19
|
-
&& rm .npmrc
|
|
22
|
+
&& rm .npmrc \
|
|
23
|
+
&& npm uninstall -g npm
|
|
20
24
|
|
|
21
25
|
COPY index.js ./index.js
|
|
22
26
|
COPY prisma ./prisma
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
|
+
import { join } from 'node:path';
|
|
2
3
|
import { promisify } from 'node:util';
|
|
3
4
|
import { getDatabaseSecret, withConnectionRetry } from './utils<% if (esm) { %>.js<% } %>';
|
|
4
5
|
|
|
@@ -16,7 +17,8 @@ const buildDatabaseUrl = async (): Promise<string> => {
|
|
|
16
17
|
export const handler = async () => {
|
|
17
18
|
await withConnectionRetry(async () => {
|
|
18
19
|
const databaseUrl = await buildDatabaseUrl();
|
|
19
|
-
|
|
20
|
+
const prisma = join(__dirname, 'node_modules', '.bin', 'prisma');
|
|
21
|
+
await promisify(execFile)(prisma, ['migrate', 'deploy'], {
|
|
20
22
|
cwd: __dirname,
|
|
21
23
|
env: {
|
|
22
24
|
...process.env,
|
package/src/ts/rdb/generator.js
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
*/ import { relative } from "node:path";
|
|
5
|
-
import {
|
|
5
|
+
import { generateFiles, joinPathFragments, readProjectConfiguration, updateJson, updateProjectConfiguration } from "@nx/devkit";
|
|
6
6
|
import { addTypeScriptBundleTarget } from "../../utils/bundle/bundle.js";
|
|
7
7
|
import { resolveContainers } from "../../utils/containers.js";
|
|
8
|
-
import {
|
|
8
|
+
import { addDependenciesToPackageJson } from "../../utils/dependencies.js";
|
|
9
|
+
import { addDockerScanTarget, nodeImageVersions } from "../../utils/docker.js";
|
|
9
10
|
import { formatFilesInSubtree } from "../../utils/format.js";
|
|
10
11
|
import { FsCommands } from "../../utils/fs.js";
|
|
11
12
|
import { updateGitIgnore } from "../../utils/git.js";
|
|
@@ -14,7 +15,7 @@ import { installDependencies } from "../../utils/install.js";
|
|
|
14
15
|
import { addGeneratorMetricsIfApplicable } from "../../utils/metrics.js";
|
|
15
16
|
import { esmVars } from "../../utils/module-format.js";
|
|
16
17
|
import { kebabCase, snakeCase, toClassName } from "../../utils/names.js";
|
|
17
|
-
import { getNpmScope
|
|
18
|
+
import { getNpmScope } from "../../utils/npm-scope.js";
|
|
18
19
|
import { addDependencyToTargetIfNotPresent, addGeneratorMetadata, getGeneratorInfo } from "../../utils/nx.js";
|
|
19
20
|
import { getRelativePathToRootByDirectory } from "../../utils/paths.js";
|
|
20
21
|
import { registerPnpmBuiltDependencies } from "../../utils/pnpm-workspace.js";
|
|
@@ -68,10 +69,10 @@ export const tsRdbGenerator = async (tree, options)=>{
|
|
|
68
69
|
const templateOptions = {
|
|
69
70
|
engine: options.engine,
|
|
70
71
|
runtimeConfigKey: nameClassName,
|
|
71
|
-
databasePackageAlias:
|
|
72
|
+
databasePackageAlias: fullyQualifiedName,
|
|
72
73
|
databaseProvider: options.engine === 'mysql' ? 'mysql' : 'postgresql',
|
|
73
74
|
prismaVersion: TS_VERSIONS.prisma,
|
|
74
|
-
|
|
75
|
+
...nodeImageVersions(),
|
|
75
76
|
prismaAdapterPackage: options.engine === 'mysql' ? '@prisma/adapter-mariadb' : '@prisma/adapter-pg',
|
|
76
77
|
prismaAdapterClassName: options.engine === 'mysql' ? 'PrismaMariaDb' : 'PrismaPg',
|
|
77
78
|
localDbPort,
|
|
@@ -217,7 +218,7 @@ export const tsRdbGenerator = async (tree, options)=>{
|
|
|
217
218
|
projectRoot: dir,
|
|
218
219
|
nameClassName,
|
|
219
220
|
nameKebabCase,
|
|
220
|
-
databasePackageAlias:
|
|
221
|
+
databasePackageAlias: fullyQualifiedName,
|
|
221
222
|
databaseName,
|
|
222
223
|
adminUser: databaseUser,
|
|
223
224
|
engine: options.engine,
|
|
@@ -242,12 +243,15 @@ export const tsRdbGenerator = async (tree, options)=>{
|
|
|
242
243
|
'pg'
|
|
243
244
|
]
|
|
244
245
|
]), withVersions([
|
|
245
|
-
'prisma',
|
|
246
|
-
'tsx',
|
|
247
246
|
'@types/aws-lambda',
|
|
248
247
|
...options.engine === 'mysql' ? [] : [
|
|
249
248
|
'@types/pg'
|
|
250
249
|
]
|
|
250
|
+
]), joinPathFragments(projectConfig.root, 'package.json'));
|
|
251
|
+
// The prisma CLI and tsx run migration/seed scripts from the root.
|
|
252
|
+
addDependenciesToPackageJson(tree, {}, withVersions([
|
|
253
|
+
'prisma',
|
|
254
|
+
'tsx'
|
|
251
255
|
]));
|
|
252
256
|
registerPnpmBuiltDependencies(tree, {
|
|
253
257
|
'@prisma/engines': false,
|