@aws/nx-plugin 1.0.0-rc.86 → 1.0.0-rc.87
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/migrations.json +11 -1
- package/package.json +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +34 -8
- package/src/infra/app/files/app/README.md.template +14 -0
- package/src/infra/app/generator.js +15 -2
- package/src/infra/app/generator.js.map +1 -1
- package/src/mcp-server/tools/general-guidance.js +1 -1
- package/src/mcp-server/tools/general-guidance.js.map +1 -1
- package/src/migrations/latest/add-destroy-sandbox-target/metadata.json +3 -0
- package/src/migrations/latest/add-destroy-sandbox-target/migration.d.ts +6 -0
- package/src/migrations/latest/add-destroy-sandbox-target/migration.js +150 -0
- package/src/migrations/latest/add-destroy-sandbox-target/migration.js.map +1 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/__snapshots__/migration.spec.ts.snap +23 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/metadata.json +3 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration.d.ts +6 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration.js +88 -0
- package/src/migrations/latest/terraform-rdb-proxy-iam-connect-grant/migration.js.map +1 -0
- package/src/open-api/ts-client/generator.js.map +1 -1
- package/src/open-api/ts-hooks/generator.spec.tsx +1 -1
- package/src/py/project/generator.js +5 -5
- package/src/py/project/generator.js.map +1 -1
- package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +8 -8
- package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +16 -16
- package/src/ts/dcr-proxy/__snapshots__/generator.spec.ts.snap +3 -3
- package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +3 -3
- package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +4 -11
- package/src/ts/react-website/cognito-auth/generator.js +1 -1
- package/src/ts/react-website/cognito-auth/generator.js.map +1 -1
- package/src/ts/react-website/runtime-config/generator.js +1 -1
- package/src/ts/react-website/runtime-config/generator.js.map +1 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js +3 -2
- package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
- package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +1 -1
- package/src/utils/api-constructs/api-constructs.js +7 -4
- package/src/utils/api-constructs/api-constructs.js.map +1 -1
- package/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template +4 -4
- package/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template +4 -4
- package/src/utils/api-constructs/files/cdk/core/api/rest/api-gateway-account.ts.template +1 -1
- package/src/utils/api-constructs/files/terraform/app/apis/http/__apiNameKebabCase__/__apiNameKebabCase__.tf.template +4 -4
- package/src/utils/api-constructs/files/terraform/app/apis/rest/__apiNameKebabCase__/__apiNameKebabCase__.tf.template +4 -4
- package/src/utils/ast.d.ts +13 -0
- package/src/utils/ast.js +36 -0
- package/src/utils/ast.js.map +1 -1
- package/src/utils/bundle/bundle.js +5 -2
- package/src/utils/bundle/bundle.js.map +1 -1
- package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js +5 -3
- package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js.map +1 -1
- package/src/utils/dcr-proxy-constructs/files/cdk/app/dcr-proxies/__nameKebabCase__/__nameKebabCase__.ts.template +1 -1
- package/src/utils/dcr-proxy-constructs/files/terraform/app/dcr-proxies/__nameKebabCase__/__nameKebabCase__.tf.template +2 -2
- package/src/utils/files/common/scripts/src/infra/stage-credentials/cdk-command.ts.template +7 -3
- package/src/utils/function-constructs/function-constructs.js +3 -3
- package/src/utils/function-constructs/function-constructs.js.map +1 -1
- package/src/utils/lambda-runtime-resolution.d.ts +74 -0
- package/src/utils/lambda-runtime-resolution.js +97 -0
- package/src/utils/lambda-runtime-resolution.js.map +1 -0
- package/src/utils/rdb-constructs/files/cdk/app/dbs/__nameKebabCase__.ts.template +3 -3
- package/src/utils/rdb-constructs/files/terraform/app/dbs/__nameKebabCase__/__nameKebabCase__.tf.template +4 -21
- package/src/utils/rdb-constructs/rdb-constructs.js +5 -3
- package/src/utils/rdb-constructs/rdb-constructs.js.map +1 -1
- package/src/utils/version-upgrade-migration/sync-lambda-runtimes.d.ts +28 -0
- package/src/utils/version-upgrade-migration/sync-lambda-runtimes.js +148 -0
- package/src/utils/version-upgrade-migration/sync-lambda-runtimes.js.map +1 -0
- package/src/utils/version-upgrade-migration/sync-python-language-version.d.ts +31 -0
- package/src/utils/version-upgrade-migration/sync-python-language-version.js +110 -0
- package/src/utils/version-upgrade-migration/sync-python-language-version.js.map +1 -0
- package/src/utils/version-upgrade-migration/sync-vended-versions.js +36 -7
- package/src/utils/version-upgrade-migration/sync-vended-versions.js.map +1 -1
- package/src/utils/versions.d.ts +60 -0
- package/src/utils/versions.js +51 -0
- package/src/utils/versions.js.map +1 -1
package/src/utils/ast.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/ast.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { QueryBuilder } from '@getgrit/gritql';\nimport type { Tree } from '@nx/devkit';\nimport * as path from 'path';\nimport { updateGitIgnore } from './git.js';\nimport { isEsmWorkspace } from './module-format.js';\n\nconst GRIT_DIR = '.grit';\n\n/**\n * Normalize a relative module specifier for the workspace's module format.\n * ESM (`nodenext`) requires an explicit `.js` extension on relative imports;\n * CommonJS (`node16`) resolves them extensionless. Callers always pass the ESM\n * form (with `.js`); this strips the extension for CommonJS workspaces.\n */\nconst normalizeModuleSpecifier = (tree: Tree, from: string): string => {\n if (isEsmWorkspace(tree)) {\n return from;\n }\n const isRelative = from.startsWith('./') || from.startsWith('../');\n return isRelative && from.endsWith('.js')\n ? from.slice(0, -'.js'.length)\n : from;\n};\n\n// Pin the gritql native library's \"global\" stdlib directory to <workspace>/.grit so it doesn't try to write to /usr/local/.grit (or wherever node's grandparent resolves to).\nconst ensureGritDir = (tree: Tree) => {\n process.env.GRIT_GLOBAL_DIR ??= path.join(tree.root, GRIT_DIR);\n updateGitIgnore(tree, '.', (patterns) => [...patterns, GRIT_DIR]);\n};\n\nconst assertFilePath = (tree: Tree, filePath: string) => {\n if (!tree.exists(filePath)) {\n throw new Error(`No file located at ${filePath}`);\n }\n};\n\nexport const addDestructuredImport = async (\n tree: Tree,\n filePath: string,\n variableNames: string[],\n from: string,\n) => {\n assertFilePath(tree, filePath);\n from = normalizeModuleSpecifier(tree, from);\n\n // Check if there's an existing import from this module\n const hasExistingImport = await matchGritQL(\n tree,\n filePath,\n `\\`import { $_ } from '${from}'\\``,\n );\n\n if (hasExistingImport) {\n // For each new variable, use GritQL rewrite to add it if not already present\n for (const variableName of variableNames) {\n const localName = variableName.includes(' as ')\n ? variableName.split(' as ')[1]\n : variableName;\n // Use rewrite (=>) which correctly handles comma-separated import specifier lists\n await applyGritQL(\n tree,\n filePath,\n `\\`import { $imports } from '${from}'\\` => \\`import { $imports, ${variableName} } from '${from}'\\` where { $imports <: not contains \\`${localName}\\` }`,\n );\n }\n } else {\n // No existing import — prepend a new one (after shebang if present)\n const specifiers = variableNames.join(', ');\n const contents = tree.read(filePath)!.toString();\n const newImport = `import { ${specifiers} } from '${from}';\\n`;\n if (contents.startsWith('#!')) {\n const newlineIndex = contents.indexOf('\\n');\n tree.write(\n filePath,\n `${contents.substring(0, newlineIndex + 1)}${newImport}${contents.substring(newlineIndex + 1)}`,\n );\n } else {\n tree.write(filePath, `${newImport}${contents}`);\n }\n }\n};\n\n/**\n * Ensure a Python `from <module> import <name1>, <name2>, ...` statement\n * exists in the given file. If the module already has a `from <module> import`\n * line, any missing names are appended; otherwise a fresh import statement is\n * prepended to the file (ruff's import sorter will reorder it into place on\n * the next format pass).\n *\n * We try to append first (which only succeeds if an import-from for the\n * module already exists AND the name isn't yet in the list). If nothing\n * was rewritten after trying every requested name, we fall back to checking\n * whether the module is imported at all; if not, we prepend a fresh\n * `from <module> import ...` line.\n */\nexport const addPythonDestructuredImport = async (\n tree: Tree,\n filePath: string,\n variableNames: string[],\n from: string,\n) => {\n assertFilePath(tree, filePath);\n\n // Determine whether there's any `from <module> import ...` line in the file.\n // We detect this by attempting a no-op transformation — the file is unchanged,\n // but a successful match tells us the line exists.\n const beforeContents = tree.read(filePath)!.toString();\n let moduleAlreadyImported = false;\n for (const variableName of variableNames) {\n // Appends the name if the import-from exists and the name isn't already there.\n const appended = await applyGritQL(\n tree,\n filePath,\n `language python\\n\\`from ${from} import $names\\` where { $names <: not contains \\`${variableName}\\`, $names += \\`, ${variableName}\\` }`,\n );\n if (appended) {\n moduleAlreadyImported = true;\n }\n }\n\n // If the append succeeded for at least one name, we know the module line\n // exists; we're done. If nothing was appended we need to distinguish\n // between \"module not imported\" (need to add a new line) and \"module\n // imported but all names already present\" (no-op).\n if (moduleAlreadyImported) {\n return;\n }\n\n const allAlreadyPresent = await matchGritQL(\n tree,\n filePath,\n `language python\\n\\`from ${from} import $names\\` where { ${variableNames\n .map((n) => `$names <: contains \\`${n}\\``)\n .join(', ')} }`,\n );\n if (allAlreadyPresent) {\n return;\n }\n\n // No existing `from <module> import` line — prepend one. Ruff's import\n // sorter will place it in the right group on the next formatter pass.\n const specifiers = variableNames.join(', ');\n tree.write(filePath, `from ${from} import ${specifiers}\\n${beforeContents}`);\n};\n\n/**\n * Adds an `import <variableName> from '<from>'; statement to the beginning of the file,\n * if it doesn't already exist\n */\nexport const addSingleImport = async (\n tree: Tree,\n filePath: string,\n variableName: string,\n from: string,\n) => {\n assertFilePath(tree, filePath);\n from = normalizeModuleSpecifier(tree, from);\n\n // Check if default import already exists using GritQL\n const alreadyImported = await matchGritQL(\n tree,\n filePath,\n `\\`import ${variableName} from '${from}'\\``,\n );\n if (alreadyImported) {\n return;\n }\n\n // The same identifier bound to a different module would be a duplicate\n // declaration, so refuse rather than emit a file that cannot compile.\n const identifierTaken = await matchGritQL(\n tree,\n filePath,\n `\\`import ${variableName} from $module\\``,\n );\n if (identifierTaken) {\n throw new Error(\n `Cannot import ${variableName} from '${from}' in ${filePath}: ${variableName} is already imported from a different module. Rename the project so its generated identifier does not collide.`,\n );\n }\n\n // Prepend new import to file\n const contents = tree.read(filePath)!.toString();\n tree.write(filePath, `import ${variableName} from '${from}';\\n${contents}`);\n};\n\n/**\n * Adds an `export * from '<from>'; statement to the given TypeScript file.\n * Note that this will create the file if it does not exist in the tree.\n */\nexport const addStarExport = async (\n tree: Tree,\n filePath: string,\n from: string,\n) => {\n from = normalizeModuleSpecifier(tree, from);\n const contents = tree.read(filePath)?.toString() ?? '';\n\n // For empty/non-existent files, just write the export\n if (!contents.trim()) {\n tree.write(filePath, `export * from '${from}';\\n`);\n return;\n }\n\n // Check if already exported using GritQL\n const alreadyExported = await matchGritQL(\n tree,\n filePath,\n `\\`export * from '${from}'\\``,\n );\n if (alreadyExported) {\n return;\n }\n\n // Prepend new export to file\n tree.write(filePath, `export * from '${from}';\\n${contents}`);\n};\n\n/**\n * Return whether or not the given identifier is exported in the source file.\n * Checks for both `export { Identifier }` and `export type Identifier = ...`.\n */\nexport const hasExportDeclaration = async (\n tree: Tree,\n source: string,\n identifierName: string,\n): Promise<boolean> => {\n ensureGritDir(tree);\n const patterns = [\n `\\`export type ${identifierName} = $_\\``,\n `\\`export { ${identifierName} }\\``,\n `\\`export type { ${identifierName} } from $_\\``,\n ];\n\n for (const pattern of patterns) {\n try {\n const q = new QueryBuilder(`$p => $p where { $p <: ${pattern} }`);\n const result = await q.applyToFile({\n path: 'check.ts',\n content: source,\n });\n if (result !== null) return true;\n } catch {\n // Pattern didn't match, try next\n }\n }\n\n return false;\n};\n\n/**\n * Apply a GritQL pattern to a file in the Nx tree.\n */\nexport const applyGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<boolean> => {\n if (!tree.exists(filePath)) throw new Error(`No file at ${filePath}`);\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n const query = new QueryBuilder(pattern);\n const result = await query.applyToFile({ path: filePath, content: source });\n if (result && result.content !== source) {\n tree.write(filePath, result.content);\n return true;\n }\n return false;\n};\n\n/**\n * Check whether a GritQL pattern matches anywhere in a file.\n * Returns true if the pattern matches at least once.\n *\n * Accepts raw GritQL, including patterns that start with a `language <name>`\n * header (e.g. `language python\\n\\`print($_)\\``) — the pattern is passed\n * straight through to QueryBuilder without any wrapping rewrite.\n */\nexport const matchGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<boolean> => {\n if (!tree.exists(filePath)) return false;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n let matched = false;\n try {\n const query = new QueryBuilder(pattern);\n query.filter(() => {\n matched = true;\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return false;\n }\n return matched;\n};\n\n/**\n * Capture the source text of the first match of a GritQL pattern.\n *\n * For example `` `dependencyCheck: $_` `` returns the whole\n * `dependencyCheck: { ... }` property text. Returns undefined if nothing\n * matches. The file is not modified.\n */\nexport const captureGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<string | undefined> => {\n if (!tree.exists(filePath)) return undefined;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n let captured: string | undefined;\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n captured ??= node.text();\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return undefined;\n }\n return captured;\n};\n\n/**\n * Like `captureGritQL`, but returns one metavariable's binding (e.g. `mod`\n * for `$mod`) instead of the whole matched node.\n */\nexport const captureGritQLVariable = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n variableName: string,\n): Promise<string | undefined> => {\n if (!tree.exists(filePath)) return undefined;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n // The underlying binding lookup requires the `$` sigil.\n const name = variableName.startsWith('$') ? variableName : `$${variableName}`;\n let captured: string | undefined;\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n captured ??= node.var(name) ?? undefined;\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return undefined;\n }\n return captured;\n};\n\n/**\n * Return the text of every node matching the GritQL pattern, in document order.\n */\nexport const captureAllGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<string[]> => {\n if (!tree.exists(filePath)) return [];\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n const captured: string[] = [];\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n captured.push(node.text());\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return [];\n }\n return captured;\n};\n\n/**\n * A unique token that is a valid identifier, so it can stand in for an array\n * element or object property inside a GritQL rewrite.\n */\nexport const GRIT_INSERT_PLACEHOLDER = '__GRIT_INSERT_PLACEHOLDER__';\n\n/**\n * Apply a GritQL rewrite that inserts {@link GRIT_INSERT_PLACEHOLDER}, then\n * replace the placeholder with `text`. Routing user-provided text through a\n * placeholder keeps it out of the GritQL pattern, where quotes, backticks or\n * `${...}` would otherwise break parsing.\n *\n * Any separator (e.g. a leading `, ` when appending to an array) must be part\n * of the GritQL pattern, not `text`. The one adjustment made here: if the\n * placeholder lands after a trailing line comment (`// ...`) — which would\n * comment out the text — the text is moved to its own line.\n *\n * The caller formats afterwards. Returns true if the pattern matched and the\n * file changed.\n */\nexport const insertViaGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n text: string,\n): Promise<boolean> => {\n if (!(await applyGritQL(tree, filePath, pattern))) return false;\n const content = tree.read(filePath)!.toString();\n const at = content.indexOf(GRIT_INSERT_PLACEHOLDER);\n const lineSoFar = content.slice(content.lastIndexOf('\\n', at) + 1, at);\n const replacement = lineSoFar.includes('//') ? `\\n${text}` : text;\n\n // Function replacer so `$` in `text` isn't treated as a replacement pattern.\n tree.write(\n filePath,\n content.replace(GRIT_INSERT_PLACEHOLDER, () => replacement),\n );\n return true;\n};\n\n/**\n * Append `entry` to an array, skipping arrays that already contain it, e.g.\n * `` appendToArrayViaGritQL(tree, file, 'tools:', 'myTool', { scope: 'new Agent($_)' }) ``\n * turns `tools: [a, b]` into `tools: [a, b, myTool]`.\n *\n * `arrayPrefix` is whatever precedes the array literal, including its separator —\n * `'tools:'` for an object property, `'tools='` for a keyword argument or\n * assignment, `'\"tools\":'` for a quoted key. Which separator applies depends on\n * the construct rather than the language, so the caller states it.\n *\n * Appends after the last *element* rather than rewriting the element list with\n * `=>`. GritQL binds a `[$items]` list to its trailing comma too, so\n * `` `[$items]` => `[$items, entry]` `` emits the sparse array `[a, b, , entry]`\n * once the formatter has wrapped the array — a hole that is `undefined` at\n * runtime. (Accumulating with `$items += \", entry\"` is safe by comparison, since\n * it appends within the list rather than re-emitting it; both forms appear in\n * this repo.)\n *\n * `scope` limits the match to an enclosing pattern, so same-named arrays\n * elsewhere in the file are left alone. `skipIfContains` overrides what the\n * append dedupes on, for when the rendered entry is not the identifier to match.\n *\n * The caller formats afterwards. Returns true if the entry was appended.\n */\nexport const appendToArrayViaGritQL = async (\n tree: Tree,\n filePath: string,\n arrayPrefix: string,\n entry: string,\n options: { scope?: string; skipIfContains?: string; language?: 'py' } = {},\n): Promise<boolean> => {\n const { scope, skipIfContains, language } = options;\n const within = (variable: string) =>\n scope ? `${variable} <: within \\`${scope}\\`, ` : '';\n const pattern =\n `or {` +\n // An empty array has no last element to append after.\n ` \\`${arrayPrefix}$arr\\` where { $arr <: \\`[]\\`, ${within('$arr')}` +\n ` $arr => \\`[${GRIT_INSERT_PLACEHOLDER}]\\` },` +\n // Dedupe on the list, append after its last element.\n ` \\`${arrayPrefix}[$items]\\` where {` +\n ` $items <: not contains \\`${skipIfContains ?? entry}\\`, ${within('$items')}` +\n ` $items <: [$..., $last], $last += \\`, ${GRIT_INSERT_PLACEHOLDER}\\` }` +\n ` }`;\n\n return insertViaGritQL(\n tree,\n filePath,\n language === 'py' ? `language python\\n${pattern}` : pattern,\n entry,\n );\n};\n"],"names":["QueryBuilder","path","updateGitIgnore","isEsmWorkspace","GRIT_DIR","normalizeModuleSpecifier","tree","from","isRelative","startsWith","endsWith","slice","length","ensureGritDir","process","env","GRIT_GLOBAL_DIR","join","root","patterns","assertFilePath","filePath","exists","Error","addDestructuredImport","variableNames","hasExistingImport","matchGritQL","variableName","localName","includes","split","applyGritQL","specifiers","contents","read","toString","newImport","newlineIndex","indexOf","write","substring","addPythonDestructuredImport","beforeContents","moduleAlreadyImported","appended","allAlreadyPresent","map","n","addSingleImport","alreadyImported","identifierTaken","addStarExport","trim","alreadyExported","hasExportDeclaration","source","identifierName","pattern","q","result","applyToFile","content","query","matched","filter","captureGritQL","undefined","captured","node","text","captureGritQLVariable","name","var","captureAllGritQL","push","GRIT_INSERT_PLACEHOLDER","insertViaGritQL","at","lineSoFar","lastIndexOf","replacement","replace","appendToArrayViaGritQL","arrayPrefix","entry","options","scope","skipIfContains","language","within","variable"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,QAAQ,kBAAkB;AAE/C,YAAYC,UAAU,OAAO;AAC7B,SAASC,eAAe,QAAQ,WAAW;AAC3C,SAASC,cAAc,QAAQ,qBAAqB;AAEpD,MAAMC,WAAW;AAEjB;;;;;CAKC,GACD,MAAMC,2BAA2B,CAACC,MAAYC;IAC5C,IAAIJ,eAAeG,OAAO;QACxB,OAAOC;IACT;IACA,MAAMC,aAAaD,KAAKE,UAAU,CAAC,SAASF,KAAKE,UAAU,CAAC;IAC5D,OAAOD,cAAcD,KAAKG,QAAQ,CAAC,SAC/BH,KAAKI,KAAK,CAAC,GAAG,CAAC,MAAMC,MAAM,IAC3BL;AACN;AAEA,8KAA8K;AAC9K,MAAMM,gBAAgB,CAACP;IACrBQ,QAAQC,GAAG,CAACC,eAAe,KAAKf,KAAKgB,IAAI,CAACX,KAAKY,IAAI,EAAEd;IACrDF,gBAAgBI,MAAM,KAAK,CAACa,WAAa;eAAIA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AAC,YAAY,EAAEd,wBAAwB,MAAM,CAAC,GAC9C,qDAAqD;IACrD,CAAC,GAAG,EAAEQ,YAAY,kBAAkB,CAAC,GACrC,CAAC,0BAA0B,EAAEI,kBAAkBH,MAAM,IAAI,EAAEK,OAAO,WAAW,GAC7E,CAAC,uCAAuC,EAAEd,wBAAwB,IAAI,CAAC,GACvE,CAAC,EAAE,CAAC;IAEN,OAAOC,gBACLvE,MACAe,UACAoE,aAAa,OAAO,CAAC,iBAAiB,EAAE/B,SAAS,GAAGA,SACpD2B;AAEJ,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/ast.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { QueryBuilder } from '@getgrit/gritql';\nimport type { Tree } from '@nx/devkit';\nimport * as path from 'path';\nimport { updateGitIgnore } from './git.js';\nimport { isEsmWorkspace } from './module-format.js';\n\nconst GRIT_DIR = '.grit';\n\n/**\n * Normalize a relative module specifier for the workspace's module format.\n * ESM (`nodenext`) requires an explicit `.js` extension on relative imports;\n * CommonJS (`node16`) resolves them extensionless. Callers always pass the ESM\n * form (with `.js`); this strips the extension for CommonJS workspaces.\n */\nconst normalizeModuleSpecifier = (tree: Tree, from: string): string => {\n if (isEsmWorkspace(tree)) {\n return from;\n }\n const isRelative = from.startsWith('./') || from.startsWith('../');\n return isRelative && from.endsWith('.js')\n ? from.slice(0, -'.js'.length)\n : from;\n};\n\n// Pin the gritql native library's \"global\" stdlib directory to <workspace>/.grit so it doesn't try to write to /usr/local/.grit (or wherever node's grandparent resolves to).\nconst ensureGritDir = (tree: Tree) => {\n process.env.GRIT_GLOBAL_DIR ??= path.join(tree.root, GRIT_DIR);\n updateGitIgnore(tree, '.', (patterns) => [...patterns, GRIT_DIR]);\n};\n\nconst assertFilePath = (tree: Tree, filePath: string) => {\n if (!tree.exists(filePath)) {\n throw new Error(`No file located at ${filePath}`);\n }\n};\n\nexport const addDestructuredImport = async (\n tree: Tree,\n filePath: string,\n variableNames: string[],\n from: string,\n) => {\n assertFilePath(tree, filePath);\n from = normalizeModuleSpecifier(tree, from);\n\n // Check if there's an existing import from this module\n const hasExistingImport = await matchGritQL(\n tree,\n filePath,\n `\\`import { $_ } from '${from}'\\``,\n );\n\n if (hasExistingImport) {\n // For each new variable, use GritQL rewrite to add it if not already present\n for (const variableName of variableNames) {\n const localName = variableName.includes(' as ')\n ? variableName.split(' as ')[1]\n : variableName;\n // Use rewrite (=>) which correctly handles comma-separated import specifier lists\n await applyGritQL(\n tree,\n filePath,\n `\\`import { $imports } from '${from}'\\` => \\`import { $imports, ${variableName} } from '${from}'\\` where { $imports <: not contains \\`${localName}\\` }`,\n );\n }\n } else {\n // No existing import — prepend a new one (after shebang if present)\n const specifiers = variableNames.join(', ');\n const contents = tree.read(filePath)!.toString();\n const newImport = `import { ${specifiers} } from '${from}';\\n`;\n if (contents.startsWith('#!')) {\n const newlineIndex = contents.indexOf('\\n');\n tree.write(\n filePath,\n `${contents.substring(0, newlineIndex + 1)}${newImport}${contents.substring(newlineIndex + 1)}`,\n );\n } else {\n tree.write(filePath, `${newImport}${contents}`);\n }\n }\n};\n\n/**\n * Ensure a Python `from <module> import <name1>, <name2>, ...` statement\n * exists in the given file. If the module already has a `from <module> import`\n * line, any missing names are appended; otherwise a fresh import statement is\n * prepended to the file (ruff's import sorter will reorder it into place on\n * the next format pass).\n *\n * We try to append first (which only succeeds if an import-from for the\n * module already exists AND the name isn't yet in the list). If nothing\n * was rewritten after trying every requested name, we fall back to checking\n * whether the module is imported at all; if not, we prepend a fresh\n * `from <module> import ...` line.\n */\nexport const addPythonDestructuredImport = async (\n tree: Tree,\n filePath: string,\n variableNames: string[],\n from: string,\n) => {\n assertFilePath(tree, filePath);\n\n // Determine whether there's any `from <module> import ...` line in the file.\n // We detect this by attempting a no-op transformation — the file is unchanged,\n // but a successful match tells us the line exists.\n const beforeContents = tree.read(filePath)!.toString();\n let moduleAlreadyImported = false;\n for (const variableName of variableNames) {\n // Appends the name if the import-from exists and the name isn't already there.\n const appended = await applyGritQL(\n tree,\n filePath,\n `language python\\n\\`from ${from} import $names\\` where { $names <: not contains \\`${variableName}\\`, $names += \\`, ${variableName}\\` }`,\n );\n if (appended) {\n moduleAlreadyImported = true;\n }\n }\n\n // If the append succeeded for at least one name, we know the module line\n // exists; we're done. If nothing was appended we need to distinguish\n // between \"module not imported\" (need to add a new line) and \"module\n // imported but all names already present\" (no-op).\n if (moduleAlreadyImported) {\n return;\n }\n\n const allAlreadyPresent = await matchGritQL(\n tree,\n filePath,\n `language python\\n\\`from ${from} import $names\\` where { ${variableNames\n .map((n) => `$names <: contains \\`${n}\\``)\n .join(', ')} }`,\n );\n if (allAlreadyPresent) {\n return;\n }\n\n // No existing `from <module> import` line — prepend one. Ruff's import\n // sorter will place it in the right group on the next formatter pass.\n const specifiers = variableNames.join(', ');\n tree.write(filePath, `from ${from} import ${specifiers}\\n${beforeContents}`);\n};\n\n/**\n * Adds an `import <variableName> from '<from>'; statement to the beginning of the file,\n * if it doesn't already exist\n */\nexport const addSingleImport = async (\n tree: Tree,\n filePath: string,\n variableName: string,\n from: string,\n) => {\n assertFilePath(tree, filePath);\n from = normalizeModuleSpecifier(tree, from);\n\n // Check if default import already exists using GritQL\n const alreadyImported = await matchGritQL(\n tree,\n filePath,\n `\\`import ${variableName} from '${from}'\\``,\n );\n if (alreadyImported) {\n return;\n }\n\n // The same identifier bound to a different module would be a duplicate\n // declaration, so refuse rather than emit a file that cannot compile.\n const identifierTaken = await matchGritQL(\n tree,\n filePath,\n `\\`import ${variableName} from $module\\``,\n );\n if (identifierTaken) {\n throw new Error(\n `Cannot import ${variableName} from '${from}' in ${filePath}: ${variableName} is already imported from a different module. Rename the project so its generated identifier does not collide.`,\n );\n }\n\n // Prepend new import to file\n const contents = tree.read(filePath)!.toString();\n tree.write(filePath, `import ${variableName} from '${from}';\\n${contents}`);\n};\n\n/**\n * Adds an `export * from '<from>'; statement to the given TypeScript file.\n * Note that this will create the file if it does not exist in the tree.\n */\nexport const addStarExport = async (\n tree: Tree,\n filePath: string,\n from: string,\n) => {\n from = normalizeModuleSpecifier(tree, from);\n const contents = tree.read(filePath)?.toString() ?? '';\n\n // For empty/non-existent files, just write the export\n if (!contents.trim()) {\n tree.write(filePath, `export * from '${from}';\\n`);\n return;\n }\n\n // Check if already exported using GritQL\n const alreadyExported = await matchGritQL(\n tree,\n filePath,\n `\\`export * from '${from}'\\``,\n );\n if (alreadyExported) {\n return;\n }\n\n // Prepend new export to file\n tree.write(filePath, `export * from '${from}';\\n${contents}`);\n};\n\n/**\n * Return whether or not the given identifier is exported in the source file.\n * Checks for both `export { Identifier }` and `export type Identifier = ...`.\n */\nexport const hasExportDeclaration = async (\n tree: Tree,\n source: string,\n identifierName: string,\n): Promise<boolean> => {\n ensureGritDir(tree);\n const patterns = [\n `\\`export type ${identifierName} = $_\\``,\n `\\`export { ${identifierName} }\\``,\n `\\`export type { ${identifierName} } from $_\\``,\n ];\n\n for (const pattern of patterns) {\n try {\n const q = new QueryBuilder(`$p => $p where { $p <: ${pattern} }`);\n const result = await q.applyToFile({\n path: 'check.ts',\n content: source,\n });\n if (result !== null) return true;\n } catch {\n // Pattern didn't match, try next\n }\n }\n\n return false;\n};\n\n/**\n * Apply a GritQL pattern to a file in the Nx tree.\n */\nexport const applyGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<boolean> => {\n if (!tree.exists(filePath)) throw new Error(`No file at ${filePath}`);\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n const query = new QueryBuilder(pattern);\n const result = await query.applyToFile({ path: filePath, content: source });\n if (result && result.content !== source) {\n tree.write(filePath, result.content);\n return true;\n }\n return false;\n};\n\n/**\n * Check whether a GritQL pattern matches anywhere in a file.\n * Returns true if the pattern matches at least once.\n *\n * Accepts raw GritQL, including patterns that start with a `language <name>`\n * header (e.g. `language python\\n\\`print($_)\\``) — the pattern is passed\n * straight through to QueryBuilder without any wrapping rewrite.\n */\nexport const matchGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<boolean> => {\n if (!tree.exists(filePath)) return false;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n let matched = false;\n try {\n const query = new QueryBuilder(pattern);\n query.filter(() => {\n matched = true;\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return false;\n }\n return matched;\n};\n\n/**\n * Capture the source text of the first match of a GritQL pattern.\n *\n * For example `` `dependencyCheck: $_` `` returns the whole\n * `dependencyCheck: { ... }` property text. Returns undefined if nothing\n * matches. The file is not modified.\n */\nexport const captureGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<string | undefined> => {\n if (!tree.exists(filePath)) return undefined;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n let captured: string | undefined;\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n captured ??= node.text();\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return undefined;\n }\n return captured;\n};\n\n/**\n * Like `captureGritQL`, but returns one metavariable's binding (e.g. `mod`\n * for `$mod`) instead of the whole matched node.\n */\nexport const captureGritQLVariable = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n variableName: string,\n): Promise<string | undefined> => {\n if (!tree.exists(filePath)) return undefined;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n // The underlying binding lookup requires the `$` sigil.\n const name = variableName.startsWith('$') ? variableName : `$${variableName}`;\n let captured: string | undefined;\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n captured ??= node.var(name) ?? undefined;\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return undefined;\n }\n return captured;\n};\n\n/**\n * Like {@link captureAllGritQL}, but returns one metavariable's binding for every\n * match rather than the whole matched node.\n *\n * This is what lets a caller work on the value a pattern isolated — matching\n * `` `runtime: $value` `` and reading `$value` gives `Runtime.NODEJS_24_X` alone,\n * so nothing downstream has to re-derive the assignment around it.\n *\n * A match whose metavariable is unbound contributes nothing, so the result holds\n * only real bindings. Returns undefined if the pattern could not be applied,\n * which an empty array cannot express.\n */\nexport const captureAllGritQLVariable = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n variableName: string,\n): Promise<string[] | undefined> => {\n if (!tree.exists(filePath)) return undefined;\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n // The underlying binding lookup requires the `$` sigil.\n const name = variableName.startsWith('$') ? variableName : `$${variableName}`;\n const captured: string[] = [];\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n const bound = node.var(name);\n if (bound !== null && bound !== undefined) {\n captured.push(bound);\n }\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return undefined;\n }\n return captured;\n};\n\n/**\n * Return the text of every node matching the GritQL pattern, in document order.\n */\nexport const captureAllGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n): Promise<string[]> => {\n if (!tree.exists(filePath)) return [];\n ensureGritDir(tree);\n const source = tree.read(filePath)!.toString();\n const captured: string[] = [];\n try {\n const query = new QueryBuilder(pattern);\n query.filter((node) => {\n captured.push(node.text());\n return true;\n });\n await query.applyToFile({ path: filePath, content: source });\n } catch {\n return [];\n }\n return captured;\n};\n\n/**\n * A unique token that is a valid identifier, so it can stand in for an array\n * element or object property inside a GritQL rewrite.\n */\nexport const GRIT_INSERT_PLACEHOLDER = '__GRIT_INSERT_PLACEHOLDER__';\n\n/**\n * Apply a GritQL rewrite that inserts {@link GRIT_INSERT_PLACEHOLDER}, then\n * replace the placeholder with `text`. Routing user-provided text through a\n * placeholder keeps it out of the GritQL pattern, where quotes, backticks or\n * `${...}` would otherwise break parsing.\n *\n * Any separator (e.g. a leading `, ` when appending to an array) must be part\n * of the GritQL pattern, not `text`. The one adjustment made here: if the\n * placeholder lands after a trailing line comment (`// ...`) — which would\n * comment out the text — the text is moved to its own line.\n *\n * The caller formats afterwards. Returns true if the pattern matched and the\n * file changed.\n */\nexport const insertViaGritQL = async (\n tree: Tree,\n filePath: string,\n pattern: string,\n text: string,\n): Promise<boolean> => {\n if (!(await applyGritQL(tree, filePath, pattern))) return false;\n const content = tree.read(filePath)!.toString();\n const at = content.indexOf(GRIT_INSERT_PLACEHOLDER);\n const lineSoFar = content.slice(content.lastIndexOf('\\n', at) + 1, at);\n const replacement = lineSoFar.includes('//') ? `\\n${text}` : text;\n\n // Function replacer so `$` in `text` isn't treated as a replacement pattern.\n tree.write(\n filePath,\n content.replace(GRIT_INSERT_PLACEHOLDER, () => replacement),\n );\n return true;\n};\n\n/**\n * Append `entry` to an array, skipping arrays that already contain it, e.g.\n * `` appendToArrayViaGritQL(tree, file, 'tools:', 'myTool', { scope: 'new Agent($_)' }) ``\n * turns `tools: [a, b]` into `tools: [a, b, myTool]`.\n *\n * `arrayPrefix` is whatever precedes the array literal, including its separator —\n * `'tools:'` for an object property, `'tools='` for a keyword argument or\n * assignment, `'\"tools\":'` for a quoted key. Which separator applies depends on\n * the construct rather than the language, so the caller states it.\n *\n * Appends after the last *element* rather than rewriting the element list with\n * `=>`. GritQL binds a `[$items]` list to its trailing comma too, so\n * `` `[$items]` => `[$items, entry]` `` emits the sparse array `[a, b, , entry]`\n * once the formatter has wrapped the array — a hole that is `undefined` at\n * runtime. (Accumulating with `$items += \", entry\"` is safe by comparison, since\n * it appends within the list rather than re-emitting it; both forms appear in\n * this repo.)\n *\n * `scope` limits the match to an enclosing pattern, so same-named arrays\n * elsewhere in the file are left alone. `skipIfContains` overrides what the\n * append dedupes on, for when the rendered entry is not the identifier to match.\n *\n * The caller formats afterwards. Returns true if the entry was appended.\n */\nexport const appendToArrayViaGritQL = async (\n tree: Tree,\n filePath: string,\n arrayPrefix: string,\n entry: string,\n options: { scope?: string; skipIfContains?: string; language?: 'py' } = {},\n): Promise<boolean> => {\n const { scope, skipIfContains, language } = options;\n const within = (variable: string) =>\n scope ? `${variable} <: within \\`${scope}\\`, ` : '';\n const pattern =\n `or {` +\n // An empty array has no last element to append after.\n ` \\`${arrayPrefix}$arr\\` where { $arr <: \\`[]\\`, ${within('$arr')}` +\n ` $arr => \\`[${GRIT_INSERT_PLACEHOLDER}]\\` },` +\n // Dedupe on the list, append after its last element.\n ` \\`${arrayPrefix}[$items]\\` where {` +\n ` $items <: not contains \\`${skipIfContains ?? entry}\\`, ${within('$items')}` +\n ` $items <: [$..., $last], $last += \\`, ${GRIT_INSERT_PLACEHOLDER}\\` }` +\n ` }`;\n\n return insertViaGritQL(\n tree,\n filePath,\n language === 'py' ? `language python\\n${pattern}` : pattern,\n entry,\n );\n};\n"],"names":["QueryBuilder","path","updateGitIgnore","isEsmWorkspace","GRIT_DIR","normalizeModuleSpecifier","tree","from","isRelative","startsWith","endsWith","slice","length","ensureGritDir","process","env","GRIT_GLOBAL_DIR","join","root","patterns","assertFilePath","filePath","exists","Error","addDestructuredImport","variableNames","hasExistingImport","matchGritQL","variableName","localName","includes","split","applyGritQL","specifiers","contents","read","toString","newImport","newlineIndex","indexOf","write","substring","addPythonDestructuredImport","beforeContents","moduleAlreadyImported","appended","allAlreadyPresent","map","n","addSingleImport","alreadyImported","identifierTaken","addStarExport","trim","alreadyExported","hasExportDeclaration","source","identifierName","pattern","q","result","applyToFile","content","query","matched","filter","captureGritQL","undefined","captured","node","text","captureGritQLVariable","name","var","captureAllGritQLVariable","bound","push","captureAllGritQL","GRIT_INSERT_PLACEHOLDER","insertViaGritQL","at","lineSoFar","lastIndexOf","replacement","replace","appendToArrayViaGritQL","arrayPrefix","entry","options","scope","skipIfContains","language","within","variable"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,QAAQ,kBAAkB;AAE/C,YAAYC,UAAU,OAAO;AAC7B,SAASC,eAAe,QAAQ,WAAW;AAC3C,SAASC,cAAc,QAAQ,qBAAqB;AAEpD,MAAMC,WAAW;AAEjB;;;;;CAKC,GACD,MAAMC,2BAA2B,CAACC,MAAYC;IAC5C,IAAIJ,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uC,EAAEd,wBAAwB,IAAI,CAAC,GACvE,CAAC,EAAE,CAAC;IAEN,OAAOC,gBACLzE,MACAe,UACAsE,aAAa,OAAO,CAAC,iBAAiB,EAAEjC,SAAS,GAAGA,SACpD6B;AAEJ,EAAE"}
|
|
@@ -7,7 +7,7 @@ import { forDependencies } from "../declared-dependencies.js";
|
|
|
7
7
|
import { addDependenciesToPackageJson } from "../dependencies.js";
|
|
8
8
|
import { addDependencyToTargetIfNotPresent, normalizeTargetKeyOrder } from "../nx.js";
|
|
9
9
|
import { getRelativePathToRoot } from "../paths.js";
|
|
10
|
-
import { withVersions } from "../versions.js";
|
|
10
|
+
import { LAMBDA_RUNTIME_VERSIONS, withVersions } from "../versions.js";
|
|
11
11
|
/** Dependencies a caller must declare to add a TypeScript bundle target. */ export const BUNDLE_DEPENDENCIES = [
|
|
12
12
|
{
|
|
13
13
|
name: 'rolldown'
|
|
@@ -29,7 +29,10 @@ import { withVersions } from "../versions.js";
|
|
|
29
29
|
options: {
|
|
30
30
|
commands: [
|
|
31
31
|
`uv export --frozen --no-dev --no-editable --project {projectRoot} --package ${packageName} -o dist/{projectRoot}/${bundleTargetName}/requirements.txt`,
|
|
32
|
-
|
|
32
|
+
// `--python-version` pins wheel resolution to the Lambda Python runtime,
|
|
33
|
+
// so the bundle cannot be built against whichever interpreter happens to
|
|
34
|
+
// be on the build machine.
|
|
35
|
+
`uv pip install -n --no-deps --no-installer-metadata --no-compile-bytecode --python-platform ${pythonPlatform} --python-version ${LAMBDA_RUNTIME_VERSIONS.python} --target dist/{projectRoot}/${bundleTargetName} -r dist/{projectRoot}/${bundleTargetName}/requirements.txt`
|
|
33
36
|
],
|
|
34
37
|
parallel: false
|
|
35
38
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/bundle/bundle.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type TargetConfiguration,\n type Tree,\n} from '@nx/devkit';\nimport { applyGritQL } from '../ast.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from '../declared-dependencies.js';\nimport { addDependenciesToPackageJson } from '../dependencies.js';\nimport {\n addDependencyToTargetIfNotPresent,\n normalizeTargetKeyOrder,\n} from '../nx.js';\nimport { getRelativePathToRoot } from '../paths.js';\nimport { type ITsDepVersion, withVersions } from '../versions.js';\n\n/** Dependencies a caller must declare to add a TypeScript bundle target. */\nexport const BUNDLE_DEPENDENCIES = [\n { name: 'rolldown' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\nexport interface AddPythonBundleTargetOptions {\n /**\n * Python platform\n * @default x86_64-manylinux_2_28\n */\n pythonPlatform?: 'x86_64-manylinux_2_28' | 'aarch64-manylinux_2_28';\n}\n\ninterface CreatePythonBundleTargetOptions\n extends Required<AddPythonBundleTargetOptions> {\n /**\n * Python package name\n */\n packageName: string;\n\n /**\n * Name of the bundle target, used for the outdir for the bundle\n */\n bundleTargetName: string;\n}\n\n/**\n * Create a target for bundling a python project\n */\nconst createPythonBundleTarget = ({\n packageName,\n pythonPlatform,\n bundleTargetName,\n}: CreatePythonBundleTargetOptions): TargetConfiguration => {\n return {\n cache: true,\n inputs: ['default', '^production'],\n executor: 'nx:run-commands',\n outputs: [`{workspaceRoot}/dist/{projectRoot}/${bundleTargetName}`],\n options: {\n commands: [\n `uv export --frozen --no-dev --no-editable --project {projectRoot} --package ${packageName} -o dist/{projectRoot}/${bundleTargetName}/requirements.txt`,\n `uv pip install -n --no-deps --no-installer-metadata --no-compile-bytecode --python-platform ${pythonPlatform} --target dist/{projectRoot}/${bundleTargetName} -r dist/{projectRoot}/${bundleTargetName}/requirements.txt`,\n ],\n parallel: false,\n },\n };\n};\n\n/**\n * Adds a bundle target to the given project if it does not exist, and updates the build target to depend on it\n */\nexport const addPythonBundleTarget = (\n project: ProjectConfiguration,\n opts?: AddPythonBundleTargetOptions,\n) => {\n if (!project.targets) {\n project.targets = {};\n }\n\n const pythonPlatform = opts?.pythonPlatform ?? 'x86_64-manylinux_2_28';\n const bundleTargetName =\n pythonPlatform === 'aarch64-manylinux_2_28' ? 'bundle-arm' : 'bundle-x86';\n\n if (!project.targets?.[bundleTargetName]) {\n project.targets[bundleTargetName] = normalizeTargetKeyOrder({\n ...createPythonBundleTarget({\n packageName: project.name,\n pythonPlatform,\n bundleTargetName,\n }),\n dependsOn: ['compile'],\n });\n }\n\n // Add a \"bundle\" target which depends on either bundle-arm or bundle-x86 (or both)\n addDependencyToTargetIfNotPresent(project, 'bundle', bundleTargetName);\n addDependencyToTargetIfNotPresent(project, 'build', 'bundle');\n\n return {\n bundleTargetName,\n bundleOutputDir: joinPathFragments('dist', project.root, bundleTargetName),\n };\n};\n\nexport interface AddTypeScriptBundleTargetOptions {\n /**\n * Path to the target file relative to the project dir\n */\n targetFilePath: string;\n\n /**\n * Sub directory to write bundled index.js file to (if any)\n * Outputs to dist/{projectRoot}/bundle/{bundleOutputDir}/index.js\n */\n bundleOutputDir?: string;\n\n /**\n * Modules to omit from the bundle and treat as external\n */\n external?: (string | RegExp)[];\n\n /**\n * Target platform for the bundle\n * @default 'node'\n */\n platform?: 'node' | 'browser' | 'neutral';\n}\n\n/**\n * Add a TypeScript bundle target using rolldown\n */\nexport const addTypeScriptBundleTarget = async <\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n project: ProjectConfiguration,\n opts: AddTypeScriptBundleTargetOptions,\n declaration: D & MustDeclare<typeof BUNDLE_DEPENDENCIES, D>,\n) => {\n project.targets ??= {};\n\n // Generate empty rolldown config if it doesn't exist\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'ts'),\n project.root,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add the bundle target\n if (!project.targets.bundle) {\n project.targets.bundle = normalizeTargetKeyOrder({\n cache: true,\n outputs: [`{workspaceRoot}/dist/{projectRoot}/bundle`],\n executor: 'nx:run-commands',\n options: {\n command: 'rolldown -c rolldown.config.ts',\n cwd: '{projectRoot}',\n },\n dependsOn: ['compile'],\n });\n }\n\n // Add bundle to the build target\n addDependencyToTargetIfNotPresent(project, 'build', 'bundle');\n\n const rolldownConfigPath = joinPathFragments(\n project.root,\n 'rolldown.config.ts',\n );\n\n const outputFile = joinPathFragments(\n getRelativePathToRoot(tree, project.name),\n 'dist',\n project.root,\n 'bundle',\n opts.bundleOutputDir ?? '.',\n 'index.js',\n );\n\n const external = opts.external?.length\n ? opts.external\n .map((ext) =>\n typeof ext === 'string' ? `'${ext}'` : `/${ext.source}/`,\n )\n .join(', ')\n : '';\n\n const entry = `{\n tsconfig: 'tsconfig.lib.json',\n input: '${opts.targetFilePath}',\n output: { file: '${outputFile}', format: 'cjs', codeSplitting: false },\n platform: '${opts.platform ?? 'node'}',\n ${external ? `external: [${external}],` : ''}\n }`;\n\n // Use GritQL to append the config entry to the defineConfig array.\n // First try the non-empty array case using the accumulate (+=) operator,\n // with an idempotency guard that checks the input path is not already present.\n const appended = await applyGritQL(\n tree,\n rolldownConfigPath,\n `\\`defineConfig([$items])\\` where { $items <: not contains \\`'${opts.targetFilePath}'\\`, $items += \", ${entry}\" }`,\n );\n\n if (!appended) {\n // Empty array — GritQL's += cannot accumulate into an empty list, so we\n // first insert a placeholder to make the array non-empty, then replace\n // the placeholder with the real entry via += (which handles regex\n // literals that are invalid inside GritQL backtick snippets).\n const inserted = await applyGritQL(\n tree,\n rolldownConfigPath,\n `\\`defineConfig([])\\` => \\`defineConfig([__PLACEHOLDER__])\\``,\n );\n if (inserted) {\n await applyGritQL(\n tree,\n rolldownConfigPath,\n `\\`defineConfig([$items])\\` where { $items <: \\`__PLACEHOLDER__\\` => ., $items += \"${entry}\" }`,\n );\n }\n }\n\n addDependenciesToPackageJson(\n tree,\n {},\n withVersions(forDependencies<typeof BUNDLE_DEPENDENCIES>(declaration), [\n 'rolldown',\n ]),\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","applyGritQL","forDependencies","addDependenciesToPackageJson","addDependencyToTargetIfNotPresent","normalizeTargetKeyOrder","getRelativePathToRoot","withVersions","BUNDLE_DEPENDENCIES","name","createPythonBundleTarget","packageName","pythonPlatform","bundleTargetName","cache","inputs","executor","outputs","options","commands","parallel","addPythonBundleTarget","project","opts","targets","dependsOn","bundleOutputDir","root","addTypeScriptBundleTarget","tree","declaration","dirname","overwriteStrategy","KeepExisting","bundle","command","cwd","rolldownConfigPath","outputFile","external","length","map","ext","source","join","entry","targetFilePath","platform","appended","inserted"],"mappings":"AAAA;;;CAGC,GAED,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAIZ,aAAa;AACpB,SAASC,WAAW,QAAQ,YAAY;AACxC,SAEEC,eAAe,QAEV,8BAA8B;AACrC,SAASC,4BAA4B,QAAQ,qBAAqB;AAClE,SACEC,iCAAiC,EACjCC,uBAAuB,QAClB,WAAW;AAClB,SAASC,qBAAqB,QAAQ,cAAc;AACpD,SAA6BC,YAAY,QAAQ,iBAAiB;AAElE,0EAA0E,GAC1E,OAAO,MAAMC,sBAAsB;IACjC;QAAEC,MAAM;IAAW;CACpB,CAAuD;AAuBxD;;CAEC,GACD,MAAMC,2BAA2B,CAAC,EAChCC,WAAW,EACXC,cAAc,EACdC,gBAAgB,EACgB;IAChC,OAAO;QACLC,OAAO;QACPC,QAAQ;YAAC;YAAW;SAAc;QAClCC,UAAU;QACVC,SAAS;YAAC,CAAC,mCAAmC,EAAEJ,kBAAkB;SAAC;QACnEK,SAAS;YACPC,UAAU;gBACR,CAAC,4EAA4E,EAAER,YAAY,uBAAuB,EAAEE,iBAAiB,iBAAiB,CAAC;gBACvJ,CAAC,4FAA4F,EAAED,eAAe,6BAA6B,EAAEC,iBAAiB,uBAAuB,EAAEA,iBAAiB,iBAAiB,CAAC;aAC3N;YACDO,UAAU;QACZ;IAC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;IAGF,MAAMW,aAAavC,kBACjBO,sBAAsBuB,MAAMP,QAAQb,IAAI,GACxC,QACAa,QAAQK,IAAI,EACZ,UACAJ,KAAKG,eAAe,IAAI,KACxB;IAGF,MAAMa,WAAWhB,KAAKgB,QAAQ,EAAEC,SAC5BjB,KAAKgB,QAAQ,CACVE,GAAG,CAAC,CAACC,MACJ,OAAOA,QAAQ,WAAW,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,EAAEA,IAAIC,MAAM,CAAC,CAAC,CAAC,EAEzDC,IAAI,CAAC,QACR;IAEJ,MAAMC,QAAQ,CAAC;;YAEL,EAAEtB,KAAKuB,cAAc,CAAC;qBACb,EAAER,WAAW;eACnB,EAAEf,KAAKwB,QAAQ,IAAI,OAAO;IACrC,EAAER,WAAW,CAAC,WAAW,EAAEA,SAAS,EAAE,CAAC,GAAG,GAAG;GAC9C,CAAC;IAEF,mEAAmE;IACnE,yEAAyE;IACzE,+EAA+E;IAC/E,MAAMS,WAAW,MAAM/C,YACrB4B,MACAQ,oBACA,CAAC,6DAA6D,EAAEd,KAAKuB,cAAc,CAAC,kBAAkB,EAAED,MAAM,GAAG,CAAC;IAGpH,IAAI,CAACG,UAAU;QACb,wEAAwE;QACxE,uEAAuE;QACvE,kEAAkE;QAClE,8DAA8D;QAC9D,MAAMC,WAAW,MAAMhD,YACrB4B,MACAQ,oBACA,CAAC,2DAA2D,CAAC;QAE/D,IAAIY,UAAU;YACZ,MAAMhD,YACJ4B,MACAQ,oBACA,CAAC,kFAAkF,EAAEQ,MAAM,GAAG,CAAC;QAEnG;IACF;IAEA1C,6BACE0B,MACA,CAAC,GACDtB,aAAaL,gBAA4C4B,cAAc;QACrE;KACD;AAEL,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/bundle/bundle.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type TargetConfiguration,\n type Tree,\n} from '@nx/devkit';\nimport { applyGritQL } from '../ast.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from '../declared-dependencies.js';\nimport { addDependenciesToPackageJson } from '../dependencies.js';\nimport {\n addDependencyToTargetIfNotPresent,\n normalizeTargetKeyOrder,\n} from '../nx.js';\nimport { getRelativePathToRoot } from '../paths.js';\nimport {\n type ITsDepVersion,\n LAMBDA_RUNTIME_VERSIONS,\n withVersions,\n} from '../versions.js';\n\n/** Dependencies a caller must declare to add a TypeScript bundle target. */\nexport const BUNDLE_DEPENDENCIES = [\n { name: 'rolldown' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\nexport interface AddPythonBundleTargetOptions {\n /**\n * Python platform\n * @default x86_64-manylinux_2_28\n */\n pythonPlatform?: 'x86_64-manylinux_2_28' | 'aarch64-manylinux_2_28';\n}\n\ninterface CreatePythonBundleTargetOptions\n extends Required<AddPythonBundleTargetOptions> {\n /**\n * Python package name\n */\n packageName: string;\n\n /**\n * Name of the bundle target, used for the outdir for the bundle\n */\n bundleTargetName: string;\n}\n\n/**\n * Create a target for bundling a python project\n */\nconst createPythonBundleTarget = ({\n packageName,\n pythonPlatform,\n bundleTargetName,\n}: CreatePythonBundleTargetOptions): TargetConfiguration => {\n return {\n cache: true,\n inputs: ['default', '^production'],\n executor: 'nx:run-commands',\n outputs: [`{workspaceRoot}/dist/{projectRoot}/${bundleTargetName}`],\n options: {\n commands: [\n `uv export --frozen --no-dev --no-editable --project {projectRoot} --package ${packageName} -o dist/{projectRoot}/${bundleTargetName}/requirements.txt`,\n // `--python-version` pins wheel resolution to the Lambda Python runtime,\n // so the bundle cannot be built against whichever interpreter happens to\n // be on the build machine.\n `uv pip install -n --no-deps --no-installer-metadata --no-compile-bytecode --python-platform ${pythonPlatform} --python-version ${LAMBDA_RUNTIME_VERSIONS.python} --target dist/{projectRoot}/${bundleTargetName} -r dist/{projectRoot}/${bundleTargetName}/requirements.txt`,\n ],\n parallel: false,\n },\n };\n};\n\n/**\n * Adds a bundle target to the given project if it does not exist, and updates the build target to depend on it\n */\nexport const addPythonBundleTarget = (\n project: ProjectConfiguration,\n opts?: AddPythonBundleTargetOptions,\n) => {\n if (!project.targets) {\n project.targets = {};\n }\n\n const pythonPlatform = opts?.pythonPlatform ?? 'x86_64-manylinux_2_28';\n const bundleTargetName =\n pythonPlatform === 'aarch64-manylinux_2_28' ? 'bundle-arm' : 'bundle-x86';\n\n if (!project.targets?.[bundleTargetName]) {\n project.targets[bundleTargetName] = normalizeTargetKeyOrder({\n ...createPythonBundleTarget({\n packageName: project.name,\n pythonPlatform,\n bundleTargetName,\n }),\n dependsOn: ['compile'],\n });\n }\n\n // Add a \"bundle\" target which depends on either bundle-arm or bundle-x86 (or both)\n addDependencyToTargetIfNotPresent(project, 'bundle', bundleTargetName);\n addDependencyToTargetIfNotPresent(project, 'build', 'bundle');\n\n return {\n bundleTargetName,\n bundleOutputDir: joinPathFragments('dist', project.root, bundleTargetName),\n };\n};\n\nexport interface AddTypeScriptBundleTargetOptions {\n /**\n * Path to the target file relative to the project dir\n */\n targetFilePath: string;\n\n /**\n * Sub directory to write bundled index.js file to (if any)\n * Outputs to dist/{projectRoot}/bundle/{bundleOutputDir}/index.js\n */\n bundleOutputDir?: string;\n\n /**\n * Modules to omit from the bundle and treat as external\n */\n external?: (string | RegExp)[];\n\n /**\n * Target platform for the bundle\n * @default 'node'\n */\n platform?: 'node' | 'browser' | 'neutral';\n}\n\n/**\n * Add a TypeScript bundle target using rolldown\n */\nexport const addTypeScriptBundleTarget = async <\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n project: ProjectConfiguration,\n opts: AddTypeScriptBundleTargetOptions,\n declaration: D & MustDeclare<typeof BUNDLE_DEPENDENCIES, D>,\n) => {\n project.targets ??= {};\n\n // Generate empty rolldown config if it doesn't exist\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'ts'),\n project.root,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add the bundle target\n if (!project.targets.bundle) {\n project.targets.bundle = normalizeTargetKeyOrder({\n cache: true,\n outputs: [`{workspaceRoot}/dist/{projectRoot}/bundle`],\n executor: 'nx:run-commands',\n options: {\n command: 'rolldown -c rolldown.config.ts',\n cwd: '{projectRoot}',\n },\n dependsOn: ['compile'],\n });\n }\n\n // Add bundle to the build target\n addDependencyToTargetIfNotPresent(project, 'build', 'bundle');\n\n const rolldownConfigPath = joinPathFragments(\n project.root,\n 'rolldown.config.ts',\n );\n\n const outputFile = joinPathFragments(\n getRelativePathToRoot(tree, project.name),\n 'dist',\n project.root,\n 'bundle',\n opts.bundleOutputDir ?? '.',\n 'index.js',\n );\n\n const external = opts.external?.length\n ? opts.external\n .map((ext) =>\n typeof ext === 'string' ? `'${ext}'` : `/${ext.source}/`,\n )\n .join(', ')\n : '';\n\n const entry = `{\n tsconfig: 'tsconfig.lib.json',\n input: '${opts.targetFilePath}',\n output: { file: '${outputFile}', format: 'cjs', codeSplitting: false },\n platform: '${opts.platform ?? 'node'}',\n ${external ? `external: [${external}],` : ''}\n }`;\n\n // Use GritQL to append the config entry to the defineConfig array.\n // First try the non-empty array case using the accumulate (+=) operator,\n // with an idempotency guard that checks the input path is not already present.\n const appended = await applyGritQL(\n tree,\n rolldownConfigPath,\n `\\`defineConfig([$items])\\` where { $items <: not contains \\`'${opts.targetFilePath}'\\`, $items += \", ${entry}\" }`,\n );\n\n if (!appended) {\n // Empty array — GritQL's += cannot accumulate into an empty list, so we\n // first insert a placeholder to make the array non-empty, then replace\n // the placeholder with the real entry via += (which handles regex\n // literals that are invalid inside GritQL backtick snippets).\n const inserted = await applyGritQL(\n tree,\n rolldownConfigPath,\n `\\`defineConfig([])\\` => \\`defineConfig([__PLACEHOLDER__])\\``,\n );\n if (inserted) {\n await applyGritQL(\n tree,\n rolldownConfigPath,\n `\\`defineConfig([$items])\\` where { $items <: \\`__PLACEHOLDER__\\` => ., $items += \"${entry}\" }`,\n );\n }\n }\n\n addDependenciesToPackageJson(\n tree,\n {},\n withVersions(forDependencies<typeof BUNDLE_DEPENDENCIES>(declaration), [\n 'rolldown',\n ]),\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","applyGritQL","forDependencies","addDependenciesToPackageJson","addDependencyToTargetIfNotPresent","normalizeTargetKeyOrder","getRelativePathToRoot","LAMBDA_RUNTIME_VERSIONS","withVersions","BUNDLE_DEPENDENCIES","name","createPythonBundleTarget","packageName","pythonPlatform","bundleTargetName","cache","inputs","executor","outputs","options","commands","python","parallel","addPythonBundleTarget","project","opts","targets","dependsOn","bundleOutputDir","root","addTypeScriptBundleTarget","tree","declaration","dirname","overwriteStrategy","KeepExisting","bundle","command","cwd","rolldownConfigPath","outputFile","external","length","map","ext","source","join","entry","targetFilePath","platform","appended","inserted"],"mappings":"AAAA;;;CAGC,GAED,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAIZ,aAAa;AACpB,SAASC,WAAW,QAAQ,YAAY;AACxC,SAEEC,eAAe,QAEV,8BAA8B;AACrC,SAASC,4BAA4B,QAAQ,qBAAqB;AAClE,SACEC,iCAAiC,EACjCC,uBAAuB,QAClB,WAAW;AAClB,SAASC,qBAAqB,QAAQ,cAAc;AACpD,SAEEC,uBAAuB,EACvBC,YAAY,QACP,iBAAiB;AAExB,0EAA0E,GAC1E,OAAO,MAAMC,sBAAsB;IACjC;QAAEC,MAAM;IAAW;CACpB,CAAuD;AAuBxD;;CAEC,GACD,MAAMC,2BAA2B,CAAC,EAChCC,WAAW,EACXC,cAAc,EACdC,gBAAgB,EACgB;IAChC,OAAO;QACLC,OAAO;QACPC,QAAQ;YAAC;YAAW;SAAc;QAClCC,UAAU;QACVC,SAAS;YAAC,CAAC,mCAAmC,EAAEJ,kBAAkB;SAAC;QACnEK,SAAS;YACPC,UAAU;gBACR,CAAC,4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,EAAEQ,MAAM,GAAG,CAAC;QAEnG;IACF;IAEA5C,6BACE4B,MACA,CAAC,GACDvB,aAAaN,gBAA4C8B,cAAc;QACrE;KACD;AAEL,EAAE"}
|
|
@@ -6,7 +6,7 @@ import { addStarExport } from "../ast.js";
|
|
|
6
6
|
import { esmVars } from "../module-format.js";
|
|
7
7
|
import { addDependencyToTargetIfNotPresent } from "../nx.js";
|
|
8
8
|
import { PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, SHARED_TERRAFORM_DIR } from "../shared-constructs-constants.js";
|
|
9
|
-
import { terraformProviderVersions } from "../versions.js";
|
|
9
|
+
import { cdkLambdaRuntimeVars, terraformLambdaRuntimeVars, terraformProviderVersions } from "../versions.js";
|
|
10
10
|
/**
|
|
11
11
|
* The DCR proxy Lambda handlers. Each is bundled independently and wired to a
|
|
12
12
|
* dedicated route on the HTTP API.
|
|
@@ -61,7 +61,8 @@ import { terraformProviderVersions } from "../versions.js";
|
|
|
61
61
|
nameClassName: options.dcrProxyNameClassName,
|
|
62
62
|
nameKebabCase: options.dcrProxyNameKebabCase,
|
|
63
63
|
bundlePathsFromRoot: options.bundlePathsFromRoot,
|
|
64
|
-
...esmVars(tree)
|
|
64
|
+
...esmVars(tree),
|
|
65
|
+
...cdkLambdaRuntimeVars()
|
|
65
66
|
}, {
|
|
66
67
|
overwriteStrategy: OverwriteStrategy.KeepExisting
|
|
67
68
|
});
|
|
@@ -84,7 +85,8 @@ import { terraformProviderVersions } from "../versions.js";
|
|
|
84
85
|
nameClassName: options.dcrProxyNameClassName,
|
|
85
86
|
nameKebabCase: options.dcrProxyNameKebabCase,
|
|
86
87
|
bundlePathsFromRoot: options.bundlePathsFromRoot,
|
|
87
|
-
...terraformProviderVersions()
|
|
88
|
+
...terraformProviderVersions(),
|
|
89
|
+
...terraformLambdaRuntimeVars()
|
|
88
90
|
}, {
|
|
89
91
|
overwriteStrategy: OverwriteStrategy.KeepExisting
|
|
90
92
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast.js';\nimport type { Iac } from '../iac.js';\nimport { esmVars } from '../module-format.js';\nimport { addDependencyToTargetIfNotPresent } from '../nx.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants.js';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast.js';\nimport type { Iac } from '../iac.js';\nimport { esmVars } from '../module-format.js';\nimport { addDependencyToTargetIfNotPresent } from '../nx.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants.js';\nimport {\n cdkLambdaRuntimeVars,\n terraformLambdaRuntimeVars,\n terraformProviderVersions,\n} from '../versions.js';\n\n/**\n * The DCR proxy Lambda handlers. Each is bundled independently and wired to a\n * dedicated route on the HTTP API.\n */\nexport const DCR_PROXY_HANDLERS = [\n 'authorization-server-metadata',\n 'authorize',\n 'mcp-proxy',\n 'protected-resource-metadata',\n 'register',\n 'token',\n] as const;\n\nexport type DcrProxyHandler = (typeof DCR_PROXY_HANDLERS)[number];\n\nexport interface AddDcrProxyInfraProps {\n dcrProxyNameClassName: string;\n dcrProxyNameKebabCase: string;\n\n /**\n * Fully qualified name of the TypeScript project that owns the bundled\n * handlers, used to wire the shared package build to depend on it.\n */\n proxyProjectName: string;\n\n /**\n * Map of handler name to the workspace-root-relative path of its bundle\n * output directory (e.g. `dist/packages/dcr-proxy/bundle/token`).\n */\n bundlePathsFromRoot: Record<DcrProxyHandler, string>;\n\n iac: Iac;\n}\n\n/**\n * Add a DCR proxy infrastructure (CDK construct or Terraform module) to the\n * relevant shared package.\n *\n * The infrastructure exposes props/variables for the caller to inject their\n * Cognito identifiers and the upstream MCP server URL from their own stack,\n * since these may or may not be generated by this plugin. The Lambda handlers\n * live in a standalone TypeScript project and are bundled by rolldown; both\n * IaC providers reference the same bundle output.\n */\nexport const addDcrProxyInfra = async (\n tree: Tree,\n options: AddDcrProxyInfraProps,\n) => {\n if (options.iac === 'cdk') {\n await addDcrProxyCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addDcrProxyTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n\n // Ensure the handler bundles are built before the shared package\n updateJson(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n options.iac === 'cdk' ? SHARED_CONSTRUCTS_DIR : SHARED_TERRAFORM_DIR,\n 'project.json',\n ),\n (config: ProjectConfiguration) => {\n addDependencyToTargetIfNotPresent(\n config,\n 'build',\n `${options.proxyProjectName}:build`,\n );\n return config;\n },\n );\n};\n\n/**\n * Add the DCR proxy CDK construct to the shared constructs package.\n */\nconst addDcrProxyCdkConstructs = async (\n tree: Tree,\n options: AddDcrProxyInfraProps,\n) => {\n // Ensure the core HTTP API construct + utils are available (the proxy reuses\n // them). These are shared with the api generators and safe to (re)generate\n // with KeepExisting.\n for (const coreApiFile of ['http', 'utils']) {\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n '..',\n 'api-constructs',\n 'files',\n 'cdk',\n 'core',\n 'api',\n coreApiFile,\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'core',\n 'api',\n ),\n { ...esmVars(tree) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n }\n\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'cdk',\n 'app',\n 'dcr-proxies',\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'dcr-proxies',\n ),\n {\n nameClassName: options.dcrProxyNameClassName,\n nameKebabCase: options.dcrProxyNameKebabCase,\n bundlePathsFromRoot: options.bundlePathsFromRoot,\n ...esmVars(tree),\n ...cdkLambdaRuntimeVars(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Export the construct\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'dcr-proxies',\n 'index.ts',\n ),\n `./${options.dcrProxyNameKebabCase}/${options.dcrProxyNameKebabCase}.js`,\n );\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'index.ts',\n ),\n './dcr-proxies/index.js',\n );\n};\n\n/**\n * Add the DCR proxy Terraform module to the shared terraform package.\n */\nconst addDcrProxyTerraformModules = (\n tree: Tree,\n options: AddDcrProxyInfraProps,\n) => {\n // Ensure the core HTTP API module is available (the proxy reuses it). This is\n // shared with the api generators and safe to (re)generate with KeepExisting.\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n '..',\n 'api-constructs',\n 'files',\n 'terraform',\n 'core',\n 'api',\n 'http',\n ),\n joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'core', 'api'),\n { ...terraformProviderVersions() },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Generate the app specific terraform module\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'terraform',\n 'app',\n 'dcr-proxies',\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'app',\n 'dcr-proxies',\n ),\n {\n nameClassName: options.dcrProxyNameClassName,\n nameKebabCase: options.dcrProxyNameKebabCase,\n bundlePathsFromRoot: options.bundlePathsFromRoot,\n ...terraformProviderVersions(),\n ...terraformLambdaRuntimeVars(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","updateJson","addStarExport","esmVars","addDependencyToTargetIfNotPresent","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_TERRAFORM_DIR","cdkLambdaRuntimeVars","terraformLambdaRuntimeVars","terraformProviderVersions","DCR_PROXY_HANDLERS","addDcrProxyInfra","tree","options","iac","addDcrProxyCdkConstructs","addDcrProxyTerraformModules","Error","config","proxyProjectName","coreApiFile","dirname","overwriteStrategy","KeepExisting","nameClassName","dcrProxyNameClassName","nameKebabCase","dcrProxyNameKebabCase","bundlePathsFromRoot"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAGjBC,UAAU,QACL,aAAa;AACpB,SAASC,aAAa,QAAQ,YAAY;AAE1C,SAASC,OAAO,QAAQ,sBAAsB;AAC9C,SAASC,iCAAiC,QAAQ,WAAW;AAC7D,SACEC,YAAY,EACZC,qBAAqB,EACrBC,oBAAoB,QACf,oCAAoC;AAC3C,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,yBAAyB,QACpB,iBAAiB;AAExB;;;CAGC,GACD,OAAO,MAAMC,qBAAqB;IAChC;IACA;IACA;IACA;IACA;IACA;CACD,CAAU;AAuBX;;;;;;;;;CASC,GACD,OAAO,MAAMC,mBAAmB,OAC9BC,MACAC;IAEA,IAAIA,QAAQC,GAAG,KAAK,OAAO;QACzB,MAA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,cACAC,uBACA,OACA,OACA,aAEF;AAEJ;AAEA;;CAEC,GACD,MAAMW,8BAA8B,CAClCJ,MACAC;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7EhB,cACEe,MACAd,kBACE,YAAYuB,OAAO,EACnB,MACA,kBACA,SACA,aACA,QACA,OACA,SAEFvB,kBAAkBM,cAAcE,sBAAsB,OAAO,QAAQ,QACrE;QAAE,GAAGG,2BAA2B;IAAC,GACjC;QACEa,mBAAmBvB,kBAAkBwB,YAAY;IACnD;IAGF,6CAA6C;IAC7C1B,cACEe,MACAd,kBACE,YAAYuB,OAAO,EACnB,SACA,aACA,OACA,gBAEFvB,kBACEM,cACAE,sBACA,OACA,OACA,gBAEF;QACEkB,eAAeX,QAAQY,qBAAqB;QAC5CC,eAAeb,QAAQc,qBAAqB;QAC5CC,qBAAqBf,QAAQe,mBAAmB;QAChD,GAAGnB,2BAA2B;QAC9B,GAAGD,4BAA4B;IACjC,GACA;QACEc,mBAAmBvB,kBAAkBwB,YAAY;IACnD;AAEJ"}
|
|
@@ -139,7 +139,7 @@ export class <%- nameClassName %> extends Construct {
|
|
|
139
139
|
new lambda.Function(this, id_, {
|
|
140
140
|
code: asset(bundlePathFromRoot),
|
|
141
141
|
handler: 'index.handler',
|
|
142
|
-
runtime: lambda
|
|
142
|
+
runtime: lambda.<%- nodeRuntime %>,
|
|
143
143
|
architecture: lambda.Architecture.ARM_64,
|
|
144
144
|
timeout: Duration.seconds(10),
|
|
145
145
|
memorySize: 256,
|
|
@@ -240,7 +240,7 @@ resource "aws_lambda_function" "standard" {
|
|
|
240
240
|
function_name = "<%- nameKebabCase %>-${each.key}-${random_string.suffix.result}"
|
|
241
241
|
role = each.key == "token" ? aws_iam_role.token.arn : aws_iam_role.proxy.arn
|
|
242
242
|
handler = "index.handler"
|
|
243
|
-
runtime = "
|
|
243
|
+
runtime = "<%- nodeRuntime %>"
|
|
244
244
|
architectures = ["arm64"]
|
|
245
245
|
source_code_hash = data.archive_file.handler_zip[each.key].output_base64sha256
|
|
246
246
|
timeout = 10
|
|
@@ -269,7 +269,7 @@ resource "aws_lambda_function" "mcp_proxy" {
|
|
|
269
269
|
function_name = "<%- nameKebabCase %>-mcp-proxy-${random_string.suffix.result}"
|
|
270
270
|
role = aws_iam_role.proxy.arn
|
|
271
271
|
handler = "index.handler"
|
|
272
|
-
runtime = "
|
|
272
|
+
runtime = "<%- nodeRuntime %>"
|
|
273
273
|
architectures = ["arm64"]
|
|
274
274
|
source_code_hash = data.archive_file.handler_zip["mcp-proxy"].output_base64sha256
|
|
275
275
|
timeout = var.mcp_proxy_timeout
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Builds the CDK command as an array of arguments for spawnSync.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Deploys default to --require-approval=never (standard for local dev deploys).
|
|
5
5
|
* If the user explicitly passes --require-approval with any value, we
|
|
6
|
-
* respect their choice and don't add the default.
|
|
6
|
+
* respect their choice and don't add the default. `cdk destroy` has no
|
|
7
|
+
* --require-approval option, so nothing is added for it.
|
|
7
8
|
*
|
|
8
9
|
* Pass --express to opt into CloudFormation express mode for faster
|
|
9
10
|
* iteration; it is not enabled by default so deploys wait for full
|
|
@@ -16,6 +17,9 @@ export function buildCdkCommand(
|
|
|
16
17
|
const hasRequireApproval = remainingArgs.some(
|
|
17
18
|
(a) => a === '--require-approval' || a.startsWith('--require-approval='),
|
|
18
19
|
);
|
|
19
|
-
const defaults =
|
|
20
|
+
const defaults =
|
|
21
|
+
action === 'destroy' || hasRequireApproval
|
|
22
|
+
? []
|
|
23
|
+
: ['--require-approval=never'];
|
|
20
24
|
return ['cdk', action, ...defaults, ...remainingArgs];
|
|
21
25
|
}
|
|
@@ -6,7 +6,7 @@ import { addStarExport } from "../ast.js";
|
|
|
6
6
|
import { esmVars } from "../module-format.js";
|
|
7
7
|
import { addDependencyToTargetIfNotPresent } from "../nx.js";
|
|
8
8
|
import { PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, SHARED_TERRAFORM_DIR } from "../shared-constructs-constants.js";
|
|
9
|
-
import { terraformProviderVersions } from "../versions.js";
|
|
9
|
+
import { cdkLambdaRuntime, terraformLambdaRuntime, terraformProviderVersions } from "../versions.js";
|
|
10
10
|
/**
|
|
11
11
|
* Add infrastructure for a lambda function
|
|
12
12
|
*/ export const addLambdaFunctionInfra = async (tree, options)=>{
|
|
@@ -26,7 +26,7 @@ const addLambdaFunctionCdkConstructs = async (tree, options)=>{
|
|
|
26
26
|
// Generate app specific CDK construct
|
|
27
27
|
generateFiles(tree, joinPathFragments(import.meta.dirname, 'files', 'cdk', 'app', 'lambda-functions'), joinPathFragments(PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, 'src', 'app', 'lambda-functions'), {
|
|
28
28
|
...options,
|
|
29
|
-
runtime:
|
|
29
|
+
runtime: cdkLambdaRuntime(options.runtime),
|
|
30
30
|
...esmVars(tree)
|
|
31
31
|
}, {
|
|
32
32
|
overwriteStrategy: OverwriteStrategy.KeepExisting
|
|
@@ -39,7 +39,7 @@ const addLambdaFunctionTerraformModules = (tree, options)=>{
|
|
|
39
39
|
// Generate app specific terraform module
|
|
40
40
|
generateFiles(tree, joinPathFragments(import.meta.dirname, 'files', 'terraform', 'app', 'lambda-functions'), joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'app', 'lambda-functions'), {
|
|
41
41
|
...options,
|
|
42
|
-
runtime: options.runtime
|
|
42
|
+
runtime: terraformLambdaRuntime(options.runtime),
|
|
43
43
|
...terraformProviderVersions()
|
|
44
44
|
}, {
|
|
45
45
|
overwriteStrategy: OverwriteStrategy.KeepExisting
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/function-constructs/function-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast.js';\nimport type { Iac } from '../iac.js';\nimport { esmVars } from '../module-format.js';\nimport { addDependencyToTargetIfNotPresent } from '../nx.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants.js';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/function-constructs/function-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type ProjectConfiguration,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast.js';\nimport type { Iac } from '../iac.js';\nimport { esmVars } from '../module-format.js';\nimport { addDependencyToTargetIfNotPresent } from '../nx.js';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants.js';\nimport {\n cdkLambdaRuntime,\n terraformLambdaRuntime,\n terraformProviderVersions,\n} from '../versions.js';\n\nexport interface AddLambdaFunctionConstructOptions {\n functionProjectName: string;\n nameClassName: string;\n nameKebabCase: string;\n bundlePathFromRoot: string;\n handler: string;\n runtime: 'node' | 'python';\n}\n\n/**\n * Add infrastructure for a lambda function\n */\nexport const addLambdaFunctionInfra = async (\n tree: Tree,\n options: AddLambdaFunctionConstructOptions & {\n iac: Iac;\n },\n) => {\n if (options.iac === 'cdk') {\n await addLambdaFunctionCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addLambdaFunctionTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n\n updateJson(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n options.iac === 'cdk' ? SHARED_CONSTRUCTS_DIR : SHARED_TERRAFORM_DIR,\n 'project.json',\n ),\n (config: ProjectConfiguration) => {\n addDependencyToTargetIfNotPresent(\n config,\n 'build',\n `${options.functionProjectName}:build`,\n );\n return config;\n },\n );\n};\n\nconst addLambdaFunctionCdkConstructs = async (\n tree: Tree,\n options: AddLambdaFunctionConstructOptions,\n) => {\n // Generate app specific CDK construct\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'cdk',\n 'app',\n 'lambda-functions',\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'lambda-functions',\n ),\n {\n ...options,\n runtime: cdkLambdaRuntime(options.runtime),\n ...esmVars(tree),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Export app specific CDK construct\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'lambda-functions',\n 'index.ts',\n ),\n `./${options.nameKebabCase}.js`,\n );\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'app',\n 'index.ts',\n ),\n './lambda-functions/index.js',\n );\n};\n\nconst addLambdaFunctionTerraformModules = (\n tree: Tree,\n options: AddLambdaFunctionConstructOptions,\n) => {\n // Generate app specific terraform module\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'terraform',\n 'app',\n 'lambda-functions',\n ),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'app',\n 'lambda-functions',\n ),\n {\n ...options,\n runtime: terraformLambdaRuntime(options.runtime),\n ...terraformProviderVersions(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","updateJson","addStarExport","esmVars","addDependencyToTargetIfNotPresent","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_TERRAFORM_DIR","cdkLambdaRuntime","terraformLambdaRuntime","terraformProviderVersions","addLambdaFunctionInfra","tree","options","iac","addLambdaFunctionCdkConstructs","addLambdaFunctionTerraformModules","Error","config","functionProjectName","dirname","runtime","overwriteStrategy","KeepExisting","nameKebabCase"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAGjBC,UAAU,QACL,aAAa;AACpB,SAASC,aAAa,QAAQ,YAAY;AAE1C,SAASC,OAAO,QAAQ,sBAAsB;AAC9C,SAASC,iCAAiC,QAAQ,WAAW;AAC7D,SACEC,YAAY,EACZC,qBAAqB,EACrBC,oBAAoB,QACf,oCAAoC;AAC3C,SACEC,gBAAgB,EAChBC,sBAAsB,EACtBC,yBAAyB,QACpB,iBAAiB;AAWxB;;CAEC,GACD,OAAO,MAAMC,yBAAyB,OACpCC,MACAC;IAIA,IAAIA,QAAQC,GAAG,KAAK,OAAO;QACzB,MAAMC,+BAA+BH,MAAMC;IAC7C,OAAO,IAAIA,QAAQC,GAAG,KAAK,aAAa;QACtCE,kCAAkCJ,MAAMC;IAC1C,OAAO;QACL,MAAM,IAAII,MAAM,CAAC,gBAAgB,EAAEJ,QAAQC,GAAG,EAAE;IAClD;IAEAb,WACEW,MACAb,kBACEM,cACAQ,QAAQC,GAAG,KAAK,QAAQR,wBAAwBC,sBAChD,iBAEF,CAACW;QACCd,kCACEc,QACA,SACA,GAAGL,QAAQM,mBAAmB,CAAC,MAAM,CAAC;QAExC,OAAOD;IACT;AAEJ,EAAE;AAEF,MAAMH,iCAAiC,OACrCH,MACAC;IAEA,sCAAsC;IACtCf,cACEc,MACAb,kBACE,YAAYqB,OAAO,EACnB,SACA,OACA,OACA,qBAEFrB,kBACEM,cACAC,uBACA,OACA,OACA,qBAEF;QACE,GAAGO,OAAO;QACVQ,SAASb,iBAAiBK,QAAQQ,OAAO;QACzC,GAAGlB,QAAQS,KAAK;IAClB,GACA;QACEU,mBAAmBtB,kBAAkBuB,YAAY;IACnD;IAGF,oCAAoC;IACpC,MAAMrB,cACJU,MACAb,kBACEM,cACAC,uBACA,OACA,OACA,oBACA,aAEF,CAAC,EAAE,EAAEO,QAAQW,aAAa,CAAC,GAAG,CAAC;IAEjC,MAAMtB,cACJU,MACAb,kBACEM,cACAC,uBACA,OACA,OACA,aAEF;AAEJ;AAEA,MAAMU,oCAAoC,CACxCJ,MACAC;IAEA,yCAAyC;IACzCf,cACEc,MACAb,kBACE,YAAYqB,OAAO,EACnB,SACA,aACA,OACA,qBAEFrB,kBACEM,cACAE,sBACA,OACA,OACA,qBAEF;QACE,GAAGM,OAAO;QACVQ,SAASZ,uBAAuBI,QAAQQ,OAAO;QAC/C,GAAGX,2BAA2B;IAChC,GACA;QACEY,mBAAmBtB,kBAAkBuB,YAAY;IACnD;AAEJ"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
import { type ILambdaRuntime } from './versions.js';
|
|
6
|
+
/**
|
|
7
|
+
* Resolution of the Lambda runtimes and the CPython patch the version update
|
|
8
|
+
* pins.
|
|
9
|
+
*
|
|
10
|
+
* Lives here rather than beside the script so it is covered by the plugin's test
|
|
11
|
+
* suite; the script supplies the runtime list and the uv output.
|
|
12
|
+
*/
|
|
13
|
+
/** Compare two dotted numeric versions (`24`, `3.14`) ascending. */
|
|
14
|
+
export declare const compareRuntimeVersions: (a: string, b: string) => number;
|
|
15
|
+
/**
|
|
16
|
+
* The version a managed runtime identifier names, or undefined for one that isn't
|
|
17
|
+
* a versioned `nodejs`/`python` runtime.
|
|
18
|
+
*
|
|
19
|
+
* `nodejs24.x` -> `24`, `python3.14` -> `3.14`. The bare `nodejs` and
|
|
20
|
+
* `nodejs4.3-edge` style identifiers carry no comparable version and are skipped.
|
|
21
|
+
*/
|
|
22
|
+
export declare const runtimeIdentifierVersion: (identifier: string) => {
|
|
23
|
+
language: ILambdaRuntime;
|
|
24
|
+
version: string;
|
|
25
|
+
} | undefined;
|
|
26
|
+
/** Why a language's runtime could not be resolved. */
|
|
27
|
+
export type UnresolvedReason = 'no-runtimes-listed';
|
|
28
|
+
export interface RuntimeResolution {
|
|
29
|
+
/** Runtime version per language, holding the current pin where unresolved. */
|
|
30
|
+
readonly versions: Record<string, string>;
|
|
31
|
+
/** Languages left on their current pin, and why. */
|
|
32
|
+
readonly unresolved: {
|
|
33
|
+
readonly language: string;
|
|
34
|
+
readonly kept: string;
|
|
35
|
+
readonly reason: UnresolvedReason;
|
|
36
|
+
}[];
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The latest managed runtime for each language in {@link LAMBDA_RUNTIME_VERSIONS},
|
|
40
|
+
* from the runtime identifiers `aws-cdk-lib` publishes.
|
|
41
|
+
*
|
|
42
|
+
* `Runtime.ALL` is a curated list of the runtimes CDK supports, so a runtime still
|
|
43
|
+
* in public preview does not appear — which is what makes it a usable source for a
|
|
44
|
+
* generally-available runtime. Never moves a runtime backwards: a pin ahead of
|
|
45
|
+
* what CDK offers stays.
|
|
46
|
+
*
|
|
47
|
+
* A language the list says nothing about keeps its current pin and is reported
|
|
48
|
+
* through `unresolved`, so a failure costs this bump alone rather than the whole
|
|
49
|
+
* version update.
|
|
50
|
+
*/
|
|
51
|
+
export declare const resolveLambdaRuntimes: (identifiers: readonly string[]) => RuntimeResolution;
|
|
52
|
+
/** The warning a language's unresolved runtime reports. */
|
|
53
|
+
export declare const unresolvedRuntimeWarning: (entry: RuntimeResolution["unresolved"][number]) => string;
|
|
54
|
+
/** A CPython build as `uv python list --output-format json` reports it. */
|
|
55
|
+
export interface UvPythonEntry {
|
|
56
|
+
readonly version: string;
|
|
57
|
+
readonly version_parts: {
|
|
58
|
+
readonly major: number;
|
|
59
|
+
readonly minor: number;
|
|
60
|
+
readonly patch: number;
|
|
61
|
+
};
|
|
62
|
+
readonly implementation: string;
|
|
63
|
+
readonly variant?: string;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The latest CPython patch uv can install for a `major.minor`, or undefined when
|
|
67
|
+
* it lists none.
|
|
68
|
+
*
|
|
69
|
+
* Lambda names only `major.minor` and patches the interpreter itself, but uv pins
|
|
70
|
+
* an exact `major.minor.patch`, so the patch is resolved from what uv can actually
|
|
71
|
+
* install for the runtime's minor. Pre-releases and the free-threaded variant are
|
|
72
|
+
* excluded: a generated project needs the default build of a final release.
|
|
73
|
+
*/
|
|
74
|
+
export declare const resolveLatestPythonPatch: (entries: readonly UvPythonEntry[], minor?: string) => string | undefined;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/ import { LAMBDA_RUNTIME_VERSIONS } from "./versions.js";
|
|
5
|
+
/**
|
|
6
|
+
* Resolution of the Lambda runtimes and the CPython patch the version update
|
|
7
|
+
* pins.
|
|
8
|
+
*
|
|
9
|
+
* Lives here rather than beside the script so it is covered by the plugin's test
|
|
10
|
+
* suite; the script supplies the runtime list and the uv output.
|
|
11
|
+
*/ /** Compare two dotted numeric versions (`24`, `3.14`) ascending. */ export const compareRuntimeVersions = (a, b)=>{
|
|
12
|
+
const left = a.split('.').map(Number);
|
|
13
|
+
const right = b.split('.').map(Number);
|
|
14
|
+
for(let i = 0; i < Math.max(left.length, right.length); i++){
|
|
15
|
+
const diff = (left[i] ?? 0) - (right[i] ?? 0);
|
|
16
|
+
if (diff !== 0) {
|
|
17
|
+
return diff;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return 0;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The version a managed runtime identifier names, or undefined for one that isn't
|
|
24
|
+
* a versioned `nodejs`/`python` runtime.
|
|
25
|
+
*
|
|
26
|
+
* `nodejs24.x` -> `24`, `python3.14` -> `3.14`. The bare `nodejs` and
|
|
27
|
+
* `nodejs4.3-edge` style identifiers carry no comparable version and are skipped.
|
|
28
|
+
*/ export const runtimeIdentifierVersion = (identifier)=>{
|
|
29
|
+
const node = /^nodejs(\d+)\.x$/.exec(identifier);
|
|
30
|
+
if (node) {
|
|
31
|
+
return {
|
|
32
|
+
language: 'node',
|
|
33
|
+
version: node[1]
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const python = /^python(\d+\.\d+)$/.exec(identifier);
|
|
37
|
+
return python ? {
|
|
38
|
+
language: 'python',
|
|
39
|
+
version: python[1]
|
|
40
|
+
} : undefined;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* The latest managed runtime for each language in {@link LAMBDA_RUNTIME_VERSIONS},
|
|
44
|
+
* from the runtime identifiers `aws-cdk-lib` publishes.
|
|
45
|
+
*
|
|
46
|
+
* `Runtime.ALL` is a curated list of the runtimes CDK supports, so a runtime still
|
|
47
|
+
* in public preview does not appear — which is what makes it a usable source for a
|
|
48
|
+
* generally-available runtime. Never moves a runtime backwards: a pin ahead of
|
|
49
|
+
* what CDK offers stays.
|
|
50
|
+
*
|
|
51
|
+
* A language the list says nothing about keeps its current pin and is reported
|
|
52
|
+
* through `unresolved`, so a failure costs this bump alone rather than the whole
|
|
53
|
+
* version update.
|
|
54
|
+
*/ export const resolveLambdaRuntimes = (identifiers)=>{
|
|
55
|
+
const unresolved = [];
|
|
56
|
+
const versions = Object.fromEntries(Object.keys(LAMBDA_RUNTIME_VERSIONS).map((language)=>{
|
|
57
|
+
const current = LAMBDA_RUNTIME_VERSIONS[language];
|
|
58
|
+
const available = identifiers.map(runtimeIdentifierVersion).filter((parsed)=>parsed?.language === language).map((parsed)=>parsed.version);
|
|
59
|
+
if (available.length === 0) {
|
|
60
|
+
unresolved.push({
|
|
61
|
+
language,
|
|
62
|
+
kept: current,
|
|
63
|
+
reason: 'no-runtimes-listed'
|
|
64
|
+
});
|
|
65
|
+
return [
|
|
66
|
+
language,
|
|
67
|
+
current
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
const latest = available.reduce((best, version)=>compareRuntimeVersions(version, best) > 0 ? version : best);
|
|
71
|
+
return [
|
|
72
|
+
language,
|
|
73
|
+
compareRuntimeVersions(latest, current) > 0 ? latest : current
|
|
74
|
+
];
|
|
75
|
+
}));
|
|
76
|
+
return {
|
|
77
|
+
versions,
|
|
78
|
+
unresolved
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
/** The warning a language's unresolved runtime reports. */ export const unresolvedRuntimeWarning = (entry)=>`Found no ${entry.language} runtime in the aws-cdk-lib runtime list, so it keeps its pinned runtime (${entry.kept})`;
|
|
82
|
+
/**
|
|
83
|
+
* The latest CPython patch uv can install for a `major.minor`, or undefined when
|
|
84
|
+
* it lists none.
|
|
85
|
+
*
|
|
86
|
+
* Lambda names only `major.minor` and patches the interpreter itself, but uv pins
|
|
87
|
+
* an exact `major.minor.patch`, so the patch is resolved from what uv can actually
|
|
88
|
+
* install for the runtime's minor. Pre-releases and the free-threaded variant are
|
|
89
|
+
* excluded: a generated project needs the default build of a final release.
|
|
90
|
+
*/ export const resolveLatestPythonPatch = (entries, minor = LAMBDA_RUNTIME_VERSIONS.python)=>{
|
|
91
|
+
const [major, wanted] = minor.split('.').map(Number);
|
|
92
|
+
const patches = entries.filter((entry)=>entry.implementation === 'cpython' && entry.variant !== 'freethreaded' && entry.version_parts.major === major && entry.version_parts.minor === wanted && // A final release only; `3.15.0rc1` carries a suffix.
|
|
93
|
+
/^\d+\.\d+\.\d+$/.test(entry.version)).map((entry)=>entry.version_parts.patch);
|
|
94
|
+
return patches.length > 0 ? String(Math.max(...patches)) : undefined;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=lambda-runtime-resolution.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/lambda-runtime-resolution.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { type ILambdaRuntime, LAMBDA_RUNTIME_VERSIONS } from './versions.js';\n\n/**\n * Resolution of the Lambda runtimes and the CPython patch the version update\n * pins.\n *\n * Lives here rather than beside the script so it is covered by the plugin's test\n * suite; the script supplies the runtime list and the uv output.\n */\n\n/** Compare two dotted numeric versions (`24`, `3.14`) ascending. */\nexport const compareRuntimeVersions = (a: string, b: string): number => {\n const left = a.split('.').map(Number);\n const right = b.split('.').map(Number);\n for (let i = 0; i < Math.max(left.length, right.length); i++) {\n const diff = (left[i] ?? 0) - (right[i] ?? 0);\n if (diff !== 0) {\n return diff;\n }\n }\n return 0;\n};\n\n/**\n * The version a managed runtime identifier names, or undefined for one that isn't\n * a versioned `nodejs`/`python` runtime.\n *\n * `nodejs24.x` -> `24`, `python3.14` -> `3.14`. The bare `nodejs` and\n * `nodejs4.3-edge` style identifiers carry no comparable version and are skipped.\n */\nexport const runtimeIdentifierVersion = (\n identifier: string,\n): { language: ILambdaRuntime; version: string } | undefined => {\n const node = /^nodejs(\\d+)\\.x$/.exec(identifier);\n if (node) {\n return { language: 'node', version: node[1] };\n }\n const python = /^python(\\d+\\.\\d+)$/.exec(identifier);\n return python ? { language: 'python', version: python[1] } : undefined;\n};\n\n/** Why a language's runtime could not be resolved. */\nexport type UnresolvedReason = 'no-runtimes-listed';\n\nexport interface RuntimeResolution {\n /** Runtime version per language, holding the current pin where unresolved. */\n readonly versions: Record<string, string>;\n /** Languages left on their current pin, and why. */\n readonly unresolved: {\n readonly language: string;\n readonly kept: string;\n readonly reason: UnresolvedReason;\n }[];\n}\n\n/**\n * The latest managed runtime for each language in {@link LAMBDA_RUNTIME_VERSIONS},\n * from the runtime identifiers `aws-cdk-lib` publishes.\n *\n * `Runtime.ALL` is a curated list of the runtimes CDK supports, so a runtime still\n * in public preview does not appear — which is what makes it a usable source for a\n * generally-available runtime. Never moves a runtime backwards: a pin ahead of\n * what CDK offers stays.\n *\n * A language the list says nothing about keeps its current pin and is reported\n * through `unresolved`, so a failure costs this bump alone rather than the whole\n * version update.\n */\nexport const resolveLambdaRuntimes = (\n identifiers: readonly string[],\n): RuntimeResolution => {\n const unresolved: RuntimeResolution['unresolved'][number][] = [];\n\n const versions = Object.fromEntries(\n (Object.keys(LAMBDA_RUNTIME_VERSIONS) as ILambdaRuntime[]).map(\n (language) => {\n const current = LAMBDA_RUNTIME_VERSIONS[language];\n const available = identifiers\n .map(runtimeIdentifierVersion)\n .filter((parsed) => parsed?.language === language)\n .map((parsed) => parsed!.version);\n\n if (available.length === 0) {\n unresolved.push({\n language,\n kept: current,\n reason: 'no-runtimes-listed',\n });\n return [language, current];\n }\n\n const latest = available.reduce((best, version) =>\n compareRuntimeVersions(version, best) > 0 ? version : best,\n );\n\n return [\n language,\n compareRuntimeVersions(latest, current) > 0 ? latest : current,\n ];\n },\n ),\n );\n\n return { versions, unresolved };\n};\n\n/** The warning a language's unresolved runtime reports. */\nexport const unresolvedRuntimeWarning = (\n entry: RuntimeResolution['unresolved'][number],\n): string =>\n `Found no ${entry.language} runtime in the aws-cdk-lib runtime list, so it keeps its pinned runtime (${entry.kept})`;\n\n/** A CPython build as `uv python list --output-format json` reports it. */\nexport interface UvPythonEntry {\n readonly version: string;\n readonly version_parts: {\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n };\n readonly implementation: string;\n readonly variant?: string;\n}\n\n/**\n * The latest CPython patch uv can install for a `major.minor`, or undefined when\n * it lists none.\n *\n * Lambda names only `major.minor` and patches the interpreter itself, but uv pins\n * an exact `major.minor.patch`, so the patch is resolved from what uv can actually\n * install for the runtime's minor. Pre-releases and the free-threaded variant are\n * excluded: a generated project needs the default build of a final release.\n */\nexport const resolveLatestPythonPatch = (\n entries: readonly UvPythonEntry[],\n minor: string = LAMBDA_RUNTIME_VERSIONS.python,\n): string | undefined => {\n const [major, wanted] = minor.split('.').map(Number);\n const patches = entries\n .filter(\n (entry) =>\n entry.implementation === 'cpython' &&\n entry.variant !== 'freethreaded' &&\n entry.version_parts.major === major &&\n entry.version_parts.minor === wanted &&\n // A final release only; `3.15.0rc1` carries a suffix.\n /^\\d+\\.\\d+\\.\\d+$/.test(entry.version),\n )\n .map((entry) => entry.version_parts.patch);\n\n return patches.length > 0 ? String(Math.max(...patches)) : undefined;\n};\n"],"names":["LAMBDA_RUNTIME_VERSIONS","compareRuntimeVersions","a","b","left","split","map","Number","right","i","Math","max","length","diff","runtimeIdentifierVersion","identifier","node","exec","language","version","python","undefined","resolveLambdaRuntimes","identifiers","unresolved","versions","Object","fromEntries","keys","current","available","filter","parsed","push","kept","reason","latest","reduce","best","unresolvedRuntimeWarning","entry","resolveLatestPythonPatch","entries","minor","major","wanted","patches","implementation","variant","version_parts","test","patch","String"],"mappings":"AAAA;;;CAGC,GACD,SAA8BA,uBAAuB,QAAQ,gBAAgB;AAE7E;;;;;;CAMC,GAED,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,CAACC,GAAWC;IAChD,MAAMC,OAAOF,EAAEG,KAAK,CAAC,KAAKC,GAAG,CAACC;IAC9B,MAAMC,QAAQL,EAAEE,KAAK,CAAC,KAAKC,GAAG,CAACC;IAC/B,IAAK,IAAIE,IAAI,GAAGA,IAAIC,KAAKC,GAAG,CAACP,KAAKQ,MAAM,EAAEJ,MAAMI,MAAM,GAAGH,IAAK;QAC5D,MAAMI,OAAO,AAACT,CAAAA,IAAI,CAACK,EAAE,IAAI,CAAA,IAAMD,CAAAA,KAAK,CAACC,EAAE,IAAI,CAAA;QAC3C,IAAII,SAAS,GAAG;YACd,OAAOA;QACT;IACF;IACA,OAAO;AACT,EAAE;AAEF;;;;;;CAMC,GACD,OAAO,MAAMC,2BAA2B,CACtCC;IAEA,MAAMC,OAAO,mBAAmBC,IAAI,CAACF;IACrC,IAAIC,MAAM;QACR,OAAO;YAAEE,UAAU;YAAQC,SAASH,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