Skip to content

Commit 6c5b50b

Browse files
authored
fix(gen2-migration): refactor breaks for user pool groups (#14698)
* feat(cli-internal): add assess, refactor, and generate-new commands Squash of all work on the migration-plan branch since diverging from gen2-migration. Includes the assess subcommand for migration readiness, the refactor command rebuild with category-specific forward/rollback refactorers, the generate-new infrastructure with Generator+Renderer pattern, unified validation model, SpinningLogger UX, and comprehensive unit tests. --- Prompt: squash all commits after the merge base with gen2-migration into one and commit * chore: fix test * test(cli-internal): replace null-as-any logger with noOpLogger helper Add a noOpLogger() test helper that creates a real SpinningLogger in debug mode, then replace all `null as any` logger arguments across 8 refactor test files with it. This improves type safety without changing test behavior since the logger methods are never exercised in these tests. All 30 tests pass. --- Prompt: In the refactor test directory there are lot of null as any being used to pass a spinning logger instance - change it to actually create a proper logger instance. * feat(cli-internal): print validation report on failure Plan.validate() now captures the report field from ValidationResult and renders a "Failed Validations Report" section before the summary table. Each failed validation shows its description in red followed by the report text. Also trims the drift report in _validations.ts. --- Prompt: The report property in ValidationResult is currently not used at all. We should use to print the validation report in case the validation failed. * refactor(cli-internal): classify auth stacks by resource type Replace description-JSON-based auth stack classification with resource-type detection. The new approach checks for the presence of an AWS::Cognito::UserPool resource instead of parsing the stack Description field, which is more reliable. Also rename fetchStackDescription to fetchStack and descriptionCache to stackCache for accuracy since the method returns the full Stack object. --- Prompt: commit what I did * refactor(cli-internal): split auth refactorers and improve resource mapping Split monolithic auth-forward/rollback/utils into separate files for Cognito and UserPoolGroups, enabling independent forward and rollback refactoring per auth sub-resource. Replace gen1LogicalIds map with abstract targetLogicalId() method on RollbackCategoryRefactorer, giving each subclass explicit control over logical ID resolution. Extract match() hook on ForwardCategoryRefactorer for type-matching customization. Thread DiscoveredResource through CategoryRefactorer base class so refactorers can use resource metadata (e.g. resourceName) for stack discovery instead of relying on shared utility functions. Minor fixes to migration app docs and sanitize script (trailing newline normalization). --- Prompt: commit what I have * revert(cli-internal): remove trailing-newline normalization from sanitize --- Prompt: I reset the changes. just commit. * chore: remove merge markers * chore: cleanup * feat(cli-internal): group plan operations by resource Thread DiscoveredResource through all resource-backed planners so each operation carries the resource it belongs to. Plan.describe() now groups operations under resource headers using the format "<resourceName> (<category>/<service>)", matching the assessment display style. Ungrouped operations (scaffolding, validations) render as a flat list. Changes: - Add optional `resource` field to AmplifyMigrationOperation - Update Plan.describe() to group by resource label - Thread DiscoveredResource into all generate-side planners (Auth, ReferenceAuth, Data, S3, DynamoDB, RestApi, Function, AnalyticsKinesis) replacing separate resourceName params - Tag refactor-side operations via CategoryRefactorer and its forward/rollback subclasses (already had this.resource) - Update all affected test files with DiscoveredResource objects --- Prompt: in the gen2-migration, i want to make the plan describe itself by listing the description of each operation per resource. * fix(cli-internal): tweak plan resource group display Change label format to "category/resourceName (service)", add cyan color to group headers, remove indentation on grouped items, and add blank lines between groups for readability. --- Prompt: i've made changes * feat(cli-internal): refine plan display and support UserPool Groups rollback Group all operations under labeled sections — resource-backed ops use "Resource: category/name (service)", ungrouped ops fall under "Project". Descriptions rendered in gray for visual hierarchy. Add auth:Cognito-UserPool-Groups support in refactor assess and rollback using AuthUserPoolGroupsRollbackRefactorer. --- Prompt: I've made more changes. commit * docs: add commit OOM prevention and scratch file cleanup Add NODE_OPTIONS="--max-old-space-size=8192" to the commit command example and instructions to delete the scratch commit message file after a successful commit. --- Prompt: add an instruction in AGENTS.md to delete the commit file after committing and always increase memory size to prevent lint failures * feat(cli-internal): add changeset preview and move table to refactor plan Enrich the refactor plan output with changeset reports and formatted move tables so operators can review exactly what each operation will change before executing. Key changes: - Auth cognito: explicit client matching (GEN1_WEB_CLIENT ↔ GEN2_WEB_CLIENT, GEN1_NATIVE_APP_CLIENT ↔ GEN2_NATIVE_APP_CLIENT) replacing negation-based logic. Exported shared constants. - Auth user pool groups: extracted RESOURCE_TYPES constant, use USER_POOL_GROUP_TYPE consistently. - category-refactorer: added changeset preview via CreateChangeSetCommand/DescribeChangeSetCommand, made updateSource/updateTarget/buildMoveOperations/beforeMovePlan async, enriched plan descriptions with changeset reports and move tables. - forward/rollback-category-refactorer: updated to async signatures, added move table formatting to descriptions. - Removed validateSingleResourcePerCategory from refactor.ts. - Plan output now uses numbered steps and bold labels. - New files: changeset-report.ts, template-diff.ts, move-table.ts (formatting utilities). - Test stubs updated for new CFN commands. --- Prompt: I've made changes - commit what i've done. dont run tests or anything, just commit. * fix(cli-internal): improve changeset report formatting Use full JSON path (Target.Path) instead of just the top-level property name so duplicate property names like RoleMappings are distinguishable. Show before/after values on separate lines for readability. Use bgGray chalk headers for operation descriptions. Minor spacing tweaks in plan output and move table. --- Prompt: I've made more changes. Commit them. not tests. * refactor(cli-internal): use cli-table3 for move table and fix changeset no-changes detection Replace hand-rolled box-drawing move table with cli-table3 (CLITable) to match existing patterns. Fix changeset no-changes detection: a CREATE_COMPLETE changeset with an empty Changes list is the actual no-changes case, not a waiter failure. formatChangeSetReport now returns undefined when there are no changes. Remove debug 'bubu' suffix from cfn-output-resolver. --- Prompt: commit * feat(cli-internal): validate stack updates via changeset during refactor plan Move changeset creation into the validation lifecycle of updateSource/updateTarget operations. formatChangeSetReport returns undefined when no changes are detected. The validation checks report === undefined (valid) and surfaces the changeset report on failure. The describe output shows the report regardless. Removed unused chalk and formatTemplateDiff imports. --- Prompt: Commit. Don't run tests yet. * test(cli-internal): fix gen2-migration refactor tests Add CreateChangeSetCommand/DescribeChangeSetCommand mocks to the CloudFormationMock framework and individual test files that call plan(). Update tests for API changes: renamed module paths (auth-forward → auth-cognito-forward), new abstract targetLogicalId method on RollbackCategoryRefactorer, async beforeMovePlan, updated error message format, and Cognito-UserPool-Groups now being supported. Remove dead auth-utils.test.ts for deleted module. All 376 gen2-migr * refactor(cli-internal): improve refactor workflow resilience Improve category refactorer resilience for partial failure recovery and multi-stack auth scenarios: - Handle empty change-sets gracefully when source/target templates match deployed state (partial failure recovery) - Support reusing existing holding stacks in forward path for auth's two-gen1-stack-to-one-gen2-stack mapping - Consolidate rollback restore-from-holding into a single operation instead of three separate ops - Add logging before stack update/move/refactor operations - Improve plan step formatting (remove extra blank lines, add trailing newline to move table) - Use clearer descriptions for empty change-set validation --- Prompt: commit my changes * refactor(cli-internal): add physicalResourceId to MoveMapping Move physicalResourceId onto MoveMapping so it is populated once during buildResourceMappings and carried through the entire refactor pipeline. This eliminates redundant fetchStackResources calls in buildMoveOperations and the separate physicalIds/types maps that were threaded to formatMoveTable. - buildResourceMappings is now async; forward fetches from gen1Env, rollback from gen2Branch. - buildBlueprint is now async to await buildResourceMappings. - Deleted move-table.ts; renderMappingTable is now a protected method on CategoryRefactorer accepting MoveMapping[]. --- Prompt: in category-refactorer - I want to add the physical resource id to MoveMapping. Also make formatMoveTable accept MoveMapping[] and remove the unnecessary maps being passed to it. Remove move-table.ts and put formatMoveTable into a protected method inside CategoryRefactorer. Rename formatMoveTable to renderMappingTable. * refactor(cli-internal): hoist computation out of callbacks and simplify error handling Move all non-mutating work out of execute/describe/validate callbacks so errors surface during planning before any mutations run. tryRefactorStack and tryUpdateStack now throw on failure instead of returning result objects, eliminating boilerplate checks at every call site. createChangeSetReport now cleans up its changeset via try/finally. Deleted unused legacy-custom-resource.ts and template-diff.ts. --- Prompt: hoist computation out of execute callbacks, make tryRefactorStack and tryUpdateStack throw on failure, createChangeSetReport should delete its changeset, remove legacy-custom-resource.ts and template-diff.ts. * refactor(cli-internal): consolidate CFN operations into Cfn class Introduce a Cfn class that centralizes all CloudFormation operations (update, refactor, createChangeSet, findStack, deleteStack, renderChangeSet) behind a single client instance. Replace custom polling with SDK waiters (waitUntilStackUpdateComplete, waitUntilStackRefactorCreate/ ExecuteComplete, waitUntilStackDeleteComplete). Delete refactorer.ts (re-export of Planner), holding-stack.ts, cfn-stack-updater.ts, cfn-stack-refactor-updater.ts, changeset-report.ts, and snap.ts. Move getHoldingStackName and HOLDING_STACK_SUFFIX into CategoryRefactorer. Inline snapshot writing into cfn.ts. --- Prompt: consolidate 3 CFN operations into a Cfn class, replace custom polling with SDK waiters, remove refactorer.ts, holding-stack.ts, snap.ts, changeset-report.ts, inline snap into cfn.ts, remove resolveStackName, move ensureOutputDirectory to constructor. * refactor(cli-internal): add SpinningLogger to Cfn class Cfn now accepts a SpinningLogger and logs info messages before every wait operation (stack update, refactor create/execute, source/destination verification, stack deletion). --- Prompt: the cfn class should accept the spinning logger and log info whenever it is waiting on something. * refactor(cli-internal): clean up refactorer operations Split rollback holding stack update into its own operation with a validation that the changeset only adds the placeholder. Split forward holding stack deletion into a separate operation. Remove redundant fetchStackResources calls by deriving physical IDs from blueprint mappings. Move description/header construction into describe callbacks and ResourceMapping construction into execute callbacks. Add Cfn.fetchTemplate method. Remove unused imports. --- Prompt: split holding stack operations, add validation, remove redundant fetches, move descriptions into describe callbacks, add Cfn.fetchTemplate. * refactor(cli-internal): harden refactor workflow for multi-stack moves Add stack-level deduplication to prevent duplicate updates when multiple refactorers target the same stack. Thread targetStackId through buildResourceMappings for better error messages. Rework forward beforeMove to incrementally build holding stack templates by fetching existing state. In rollback, defer template computation into the execute closure and add duplicate-resource detection. Remove non-null assertions on StackResource fields. --- Prompt: commit everything I did. don't run tests. * refactor(cli-internal): improve refactor logging, remove caching, add noop handling Add resource-scoped log prefixes to Cfn operations so each category/resource pair is identifiable in output. Remove StackFacade caching layer so every call fetches fresh state from CloudFormation. Introduce buildNoopOperation and suppress the Implications section when all operations are no-ops. In rollback, skip resources that already exist in the target stack instead of throwing. Reduce max wait time from 3600s to 900s and pre-check destination stack existence to select the correct waiter. --- Prompt: commit everything I did. Don't run tests. just commit. * fix(cli-internal): defer template resolution to execution time in refactor workflow RefactorBlueprint now carries only mappings and stack IDs. Templates are fetched and resolved fresh inside each operation's execute() closure, so sequential refactorers targeting the same stack always see current state. This fixes the stale template bug where the second auth refactorer (user-pool-groups) would operate on a Gen2 template that the first refactorer (cognito) had already mutated. updateSource/updateTarget use plan-time resolved stacks directly (still fresh since they run before any moves). updateSource now accepts mappings to determine if a placeholder is needed. move(), beforeMove() (forward), and afterMove() (rollback) all re-fetch and re-resolve templates at execution time. --- Prompt: defer template resolution to execution time in refactor workflow to fix stale template bug when two Gen1 stacks map to the same Gen2 stack. * refactor(cli-internal): move template manipulation into Cfn.refactor and use SDK ResourceMapping Cfn.refactor() now accepts ResourceMapping[] directly, fetches both stack templates, moves resources between them, and handles the full refactor lifecycle internally. This eliminates template manipulation from callers entirely. Replace custom MoveMapping with the SDK's ResourceMapping type throughout the workflow. Simplify move(), beforeMove() (forward), and afterMove() (rollback) to just pass resource mappings. Remove fetchHoldingStackTemplate, isPlaceholderOnlyChangeSet, and the holding stack changeset validation. Move placeholder logic into addPlaceHolderIfNeeded() at the top of plan(). Fix symmetricDifference check to compare .size === 0. --- Prompt: Read what i've done and commit it. * refactor(cli-internal): use SDK ResourceMapping and strip all DependsOn Replace custom MoveMapping with the SDK ResourceMapping type. Cfn.refactor() now accepts ResourceMapping[] directly, fetches both stack templates internally, and moves resources between them before calling the refactor API. Simplify resolveDependencies to unconditionally strip all DependsOn from templates. DependsOn only controls deployment ordering which is irrelevant during refactor since all resources already exist. This also eliminates the partial-view problem where each refactorer only resolved dependencies for its own resource types. Remove resourceIds computation from resolveSource/resolveTarget since resolveDependencies no longer needs it. --- Prompt: use SDK ResourceMapping, move template manipulation into Cfn.refactor, strip all DependsOn unconditionally. * fix(cli-internal): handle absent holding stacks and defer template fetch in rollback Check target stack existence before fetching its template in Cfn.refactor(). Use an empty holding template when the target stack doesn't exist yet (only holding stacks may be absent). Defer holdingTemplate fetch into the execute closure in rollback afterMove so it reads fresh state. Improve error messages to show resource spec instead of class name. --- Prompt: I've made changes. Commit. * refactor(cli-internal): share Cfn instance, enable rollback resolution, add resource logging Share a single Cfn instance across all refactorers. Move update dedup from StackFacade into the workflow: updateSource/updateTarget check cfn.isUpdateClaimed() and call cfn.claimUpdate() at plan time to prevent duplicate operations in the plan. Enable resolveSource/resolveTarget and updateSource/updateTarget in rollback (previously skipped). This fixes the Fn::GetAtt dangling reference error when rolling back after a Gen2 redeploy. Thread DiscoveredResource into Cfn.update(), refactor(), and deleteStack() for resource-scoped log prefixes. --- Prompt: share Cfn instance, enable rollback resolution, add resource logging, plan-time update dedup. * test(cli-internal): update refactor tests for new interfaces Update all refactor test files to match the new API: SDK ResourceMapping instead of MoveMapping, slim RefactorBlueprint with only mappings + stack IDs, shared Cfn instance passed to constructors, and resolveDependencies taking no resource IDs. Update rollback plan test to expect updateSource/updateTarget operations (rollback now resolves and updates both stacks). Remove holding-stack.test.ts (module no longer exists). Rewrite build-refactor-templates.test.ts as minimal constant tests since buildBlueprint was removed. Update refactor.md docs to reflect current architecture. --- Prompt: make all the tests compile, update docs. * fix(cli-internal): prevent test hangs with missing mocks and async fixes Add DeleteChangeSetCommand mock to OAuth test. Make testBuildResourceMappings async and await all callers since buildResourceMappings is async. Convert sync throw assertions to async rejects.toThrow. --- Prompt: make sure the test won't hang by configuring all necessary mocks. * test(cli-internal): fix all refactor tests — 17 suites, 92 tests pass Delete tests for removed modules (cfn-stack-updater, cfn-stack-refactor-updater, legacy-custom-resource). Fix category-plan-orchestration constructor calls with shared Cfn. Update rollback assertions to expect no-op when resources already exist in target. Add default DescribeStacksCommand mocks for holding stack lookups. Mock SDK waiters in snapshot tests to avoid 30s polling delays. Handle missing template files in test framework GetTemplateCommand mock. Update snapshot files for DependsOn stripping. Add early return in beforeMove for empty mappings. Replace symmetricDifference with simple every() check in addPlaceHolderIfNeeded. --- Prompt: start running tests and fix what's needed. * docs(cli-internal): update JSDoc for refactor workflow changes Remove stale "Cached" references from StackFacade. Fix class-level JSDoc in CategoryRefactorer and RollbackCategoryRefactorer to match current method names. Add JSDoc to buildNoopOperation, buildResourceMappings, match, targetLogicalId, updateStackClaims, and createInfrastructure. --- Prompt: compare our code against the gen2-migration branch and make all necessary JSDoc changes. * docs(cli-internal): fix remaining JSDoc inaccuracies Fix afterMove JSDoc to not mention holding stack deletion. Fix "resources resources" typo in UserPoolGroups rollback. --- Prompt: do another pass. * test(cli-internal): make CloudFormation mock stateful with template map Replace invocation counter with a _templateForStack map pre-populated from snapshot files. DescribeStacks and GetTemplate now read from the map. CreateStackRefactor writes both stack templates to the map on create. UpdateStack writes the new template body to the map. DescribeStacks throws ValidationError for stacks not in the map, and returns minimal metadata for dynamically created stacks that lack snapshot files. --- Prompt: commit my changes. * test(cli-internal): reorganize refactor tests to mirror source structure Move test files into subdirectories matching the source layout: resolvers/, auth/, workflow/. Merge auth-forward-mapping tests into auth/auth-cognito-forward.test.ts. Merge build-refactor-templates tests into workflow/category-refactorer.test.ts. Split default-resource-mappings tests into the forward and rollback workflow test files. Delete flat test files that were replaced. Update all import paths for the new directory depth. --- Prompt: reorganize refactor tests to mirror source structure. * chore: revert snapshots * fix(cli-internal): clone empty holding template to prevent cross-refactorer leak EMPTY_HOLDING_TEMPLATE was a shared mutable object. When Cfn.refactor() used it as the target template for a new holding stack, it mutated the shared object by adding resources. Subsequent refactorers that also needed a new holding stack would get the already-mutated object, causing auth resources to leak into the storage holding stack. Fix by cloning the constant before use. --- Prompt: inspect snapshot changes and explain auth resources in storage holding stack. * docs: add coding guideline for module-level mutable constants Add "Don't mutate module-level constant objects" to the Mutability section of CODING_GUIDELINES.md. This pattern caused a real bug where EMPTY_HOLDING_TEMPLATE was shared across refactorers and accumulated resources from previous calls. --- Prompt: review session and add needed guidelines. * chore(cli-internal): remove duplicate ResourceMapping, add dictionary words Remove local ResourceMapping interface from category-refactorer and use the SDK type directly. Add refactorer, refactorers, and changeset to the eslint spellcheck dictionary. --- Prompt: remove ResourceMapping interface, add dictionary words. * style(cli-internal): consistent property order in ResourceMapping objects Reorder ResourceMapping properties to StackName before LogicalResourceId for consistency across forward and rollback refactorers. Update snapshot mapping files accordingly. --- Prompt: I've made some more changes - commit. * chore: regen fitness tracker snapshots * chore: update snapshots * refactor(cli-internal): simplify beforeMove/afterMove to take stack ID Replace RefactorBlueprint parameter with gen2StackId string in beforeMove and afterMove. Both methods now fetch templates and build resource mappings independently from the blueprint, reading the actual stack state at plan time. This decouples holding stack operations from the main move mappings. Add info/debug helpers to CategoryRefactorer base class. Move empty-mappings guard from plan() into move(). Add debug logging to beforeMove and afterMove for traceability. Update fitness-tracker generate snapshots for resource naming. --- Prompt: commit my changes. * test(cli-internal): fix tests for beforeMove/afterMove signature change Update beforeMove tests to pass gen2StackId string and mock GetTemplateCommand for Gen2 template fetch. Update afterMove tests to pass gen2StackId string. Update plan orchestration tests for new operation counts (no early no-op return). --- Prompt: run all cli package tests and fix what's needed. * chore: recapture snapshot * chore: update snapshots * docs(cli-internal): update refactor.md for beforeMove/afterMove changes Update flowcharts and plan() lifecycle to reflect that beforeMove and afterMove now independently discover resources from stack templates rather than using blueprint mappings. --- Prompt: run the PR stage from AGENTS.md. * test(cli-internal): add buildResourceMappings edge case tests Add tests for multiple matching targets, empty source, resource already in target (rollback skip), and empty rollback source. Remove unused CFNResource import from category-refactorer test. --- Prompt: add missing buildResourceMappings tests. * test(cli-internal): add targetLogicalId and match tests for all refactorers Add targetLogicalId tests for auth-cognito-rollback, auth-user-pool-groups-rollback, storage-rollback, storage-dynamo-rollback, and analytics-rollback. Add GroupName-based match tests for auth-user-pool-groups-forward. Add forward edge case tests for duplicate targets and ambiguous same-type matching. Fix bare throw in auth-cognito-rollback to use AmplifyError. Remove unused AmplifyError import from storage-dynamo-rollback. --- Prompt: add targetLogicalId and match tests for all refactorers, fix bare throw. * docs(cli-internal): document resource mapping happy and unhappy paths Add Resource Mapping section to refactor.md explaining forward type-based matching with usedTargetIds dedup, rollback targetLogicalId-based mapping, and all error conditions. --- Prompt: explain happy and unhappy paths of building resource mappings in refactor.md. * fix(cli-internal): skip holding stack resources already present in beforeMove beforeMove now checks the holding stack template before building resource mappings. Resources that already exist in the holding stack are skipped to handle re-execution of forward after a partial failure. Fix test mock to return empty template for REVIEW_IN_PROGRESS holding stacks. --- Prompt: fix REVIEW_IN_PROGRESS holding stack test failure. * feat(cli-internal): delete holding stack after rollback if only placeholder remains After moving resources out of the holding stack during rollback, check if only the migration placeholder resource remains. If so, delete the holding stack. This cleanup happens at execution time since each refactorer moves its own resources independently. --- Prompt: commit what I did. * chore: bring back discussions from gen2-migration * chore: update snapshots * fix(cli-internal): align tests with gen2-migration merge changes Three test files were broken after merging the gen2-migration branch: - category-refactorer.test.ts: fetchSourceStackId now uses 'storage' + resourceName as the prefix. Changed resourceName from 'test' to 'avatars' to match the mock's 'storageavatars' logical ID. - backend.generator.test.ts: Removed ensureStorageStack tests since that method was replaced by createDynamoDBStack (which already has its own tests). - dynamodb.generator.test.ts: Constructor now takes a DiscoveredResource instead of a string. Updated two call sites to pass full DiscoveredResource objects. All 125 test suites (716 tests) pass. --- Prompt: I merged code from the gen2-migration branch and now some cli package tests are failing. run and fix. * fix(cli-internal): drop removed hasS3Bucket param from DynamoDB tests The DynamoDBGenerator constructor dropped the hasS3Bucket parameter but the test file still passed it as a 4th argument. Removed the extra argument from all constructor calls and deleted the now-irrelevant "creates per-table stack regardless of hasS3Bucket flag" test. All 125 test suites (715 tests) pass. --- Prompt: run tests and fix * refactor(cli-internal): remove hasS3Bucket param from DynamoDBGenerator The DynamoDBGenerator now creates per-table stacks via createDynamoDBStack, making the hasS3Bucket flag unnecessary. Removed the parameter from the constructor and updated the call site in generate.ts. --- Prompt: there are still uncomitted changes * fix(cli-internal): address PR #14698 review comments Remove unused buildNoopOperation/NO_OP_MESSAGE from _operation.ts and _plan.ts. Restore deleted comment in _validations.ts. Rename description to stack in forward resolveTarget. Extract resource type constants in auth, analytics, and storage forward files and reuse them in rollback files. Add REVIEW_IN_PROGRESS holding stack check and duplicate logical ID error in rollback afterMove. Update rollback test mock to differentiate Gen2 vs holding stack templates. All 19 refactor test suites pass (118 tests). --- Prompt: Address the comments in this PR: 14698
1 parent 04199d7 commit 6c5b50b

356 files changed

Lines changed: 13825 additions & 6560 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.eslint-dictionary.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
"captcha",
6868
"cfn",
6969
"cfnlambda",
70+
"changeset",
7071
"chatbot",
7172
"chatbots",
7273
"chdir",
@@ -330,9 +331,12 @@
330331
"regenerator",
331332
"regexes",
332333
"rekognition",
334+
"renderer",
333335
"repo",
334336
"reqheaders",
335337
"resolvers",
338+
"refactorer",
339+
"refactorers",
336340
"rethrow",
337341
"retrier",
338342
"rimraf",

AGENTS.md

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,18 +39,24 @@ Verify your changes by following these guidelines:
3939
- **Always** update the appropriate JSDoc strings in the code you change. Be concise.
4040
- Do not create additional markdown files in the repository unless you are instructed explicitly to.
4141
- Never commit `.ai-generated` files (`.commit-message.ai-generated.txt`, `.pr-body.ai-generated.md`, etc.) — they are gitignored and are only used as local scratch files.
42-
- Commit your changes in git using a well-formed commit message following the Conventional Commits format. The message must start
43-
with a type prefix (e.g., `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`) followed by a single sentence summary and no more
42+
- Commit your changes in git using a well-formed commit message following the Conventional Commits format. The message must include
43+
a scope when the change is scoped to a specific package: `type(scope): subject`. The scope is derived from the package's `name`
44+
field in `package.json` with the `@aws-amplify/` prefix stripped. For example, `@aws-amplify/cli-internal``cli-internal`,
45+
`@aws-amplify/amplify-prompts``amplify-prompts`. Valid scopes are enforced by commitlint via `commitlint.config.js`. The
46+
message must start with a type prefix (e.g., `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`) followed by a single sentence summary and no more
4447
than a few paragraphs explaining the change and your testing. After this explanation, place the prompt the user used to trigger this
4548
work prefixed with a "Prompt: " after a single line consisting of '---'. Make sure there are no empty lines before or after this line.
4649
Word wrap all paragraphs at 72 columns including the prompt. For the author of the commit, use the configured username in git with
4750
' (AI)' appended and the user email. For example, `git commit --author="John Doe (AI) <john@bigco.com>" -m "docs: update configuration guide"`.
4851
To avoid issues with multi-line commit messages, write the message to `.commit-message.ai-generated.txt` and use `-F`:
4952

5053
```bash
51-
git commit --author="John Doe (AI) <john@bigco.com>" -F .commit-message.ai-generated.txt
54+
NODE_OPTIONS="--max-old-space-size=8192" git commit --author="John Doe (AI) <john@bigco.com>" -F .commit-message.ai-generated.txt
5255
```
5356

57+
Always set `NODE_OPTIONS="--max-old-space-size=8192"` when committing to prevent OOM failures in the lint-staged hook.
58+
After a successful commit, delete the scratch file: `rm -f .commit-message.ai-generated.txt`.
59+
5460
- Since this repo has a commit hook that takes quite a long time to run, don't immediately commit every
5561
change you were asked to do. Apply your judgment, if the diff is still fairly small just keep going.
5662
Otherwise, ask the user if they want to commit or keep going.

CODING_GUIDELINES.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,43 @@ funcGenerator.setAuthGenerator(authGenerator);
129129

130130
---
131131

132+
### Don't mutate module-level constant objects
133+
134+
`const` prevents reassignment but does not prevent mutation of the object's properties. A module-level `const` object that gets passed to a function and mutated there silently becomes shared mutable state — every subsequent caller sees the mutations from previous calls.
135+
136+
This is especially dangerous when the constant looks like a template or default value that multiple callers use as a starting point. The first caller mutates it, and the second caller unknowingly starts with the first caller's leftovers.
137+
138+
```typescript
139+
// Bad — shared object mutated by callers
140+
const EMPTY_TEMPLATE = { Resources: {} };
141+
142+
function createStack(resources: Record<string, Resource>) {
143+
const template = EMPTY_TEMPLATE; // not a copy!
144+
for (const [id, r] of Object.entries(resources)) {
145+
template.Resources[id] = r; // mutates the shared constant
146+
}
147+
return template;
148+
}
149+
150+
// Second call sees resources from the first call
151+
createStack({ BucketA: bucket });
152+
createStack({ BucketB: bucket }); // template now has both BucketA and BucketB
153+
```
154+
155+
**Instead:** Clone the object before mutating it, or use a factory function that returns a fresh object each time.
156+
157+
```typescript
158+
// Good — clone before use
159+
const template = JSON.parse(JSON.stringify(EMPTY_TEMPLATE));
160+
161+
// Good — factory function
162+
function emptyTemplate() {
163+
return { Resources: {} };
164+
}
165+
```
166+
167+
---
168+
132169
### Prefer `const` over `let`
133170

134171
Avoid `let` when the code can be restructured to use `const` instead. Even when `let` is technically correct (the variable is reassigned), the reassignment pattern itself is often the problem — it usually means branching logic is being used to populate variables that are consumed later, making it hard to reason about what values they hold at any given point.

amplify-migration-apps/backend-only/_snapshot.post.refactor/refactor.__from__.amplify-backendonly-gen2main-branch-8e0f260810-auth179371D7-SEM95NL3BKFT.__to__.amplify-backendonly-gen2main-branch-8e0f260810-auth179371D7-SEM95NL3BKFT-holding.target.template.json

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -204,10 +204,6 @@
204204
"authenticated": "arn:aws:iam::123456789012:role/amplify-backendonly-ge-amplifyAuthauthenticatedU-NrnOsacJVeCr"
205205
}
206206
},
207-
"DependsOn": [
208-
"amplifyAuthIdentityPool3FDE84CC",
209-
"amplifyAuthUserPoolAppClient2626C6F8"
210-
],
211207
"Metadata": {
212208
"aws:cdk:path": "amplify-backendonly-gen2main-branch-8e0f260810/auth/amplifyAuth/IdentityPoolRoleAttachment"
213209
}

amplify-migration-apps/backend-only/_snapshot.post.refactor/refactor.__from__.amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I.__to__.amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I-holding.source.template.json

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,6 @@
6969
"ServiceToken": "arn:aws:lambda:us-east-1:123456789012:function:amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I/CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F",
7070
"BucketName": "amplify-backendonly-ge-backendonlycb1a13ab81664-hysxrjfwrstc"
7171
},
72-
"DependsOn": [
73-
"backendonlycb1a13ab81664ecaa7d015068ab2d0165e0fagen2mainBucketPolicy14D90AB6"
74-
],
7572
"UpdateReplacePolicy": "Delete",
7673
"DeletionPolicy": "Delete",
7774
"Metadata": {
@@ -128,9 +125,6 @@
128125
]
129126
}
130127
},
131-
"DependsOn": [
132-
"CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092"
133-
],
134128
"Metadata": {
135129
"aws:cdk:path": "amplify-backendonly-gen2main-branch-8e0f260810/storage/Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler",
136130
"aws:asset:path": "asset.faa95a81ae7d7373f3e1f242268f904eb748d8d0fdd306e8a6fe515a1905a7d6",

amplify-migration-apps/backend-only/_snapshot.post.refactor/refactor.__from__.amplify-backendonly-main-5e0fa-authbackendonlyf8c4c57b-SC9H4E2DZU7A.__to__.amplify-backendonly-gen2main-branch-8e0f260810-auth179371D7-SEM95NL3BKFT.target.template.json

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -168,10 +168,7 @@
168168
"RefreshToken": "days"
169169
},
170170
"UserPoolId": "us-east-1_1rvCNKN5B"
171-
},
172-
"DependsOn": [
173-
"amplifyAuthUserPool4BA7F805"
174-
]
171+
}
175172
},
176173
"amplifyAuthUserPoolNativeAppClient79534448": {
177174
"Type": "AWS::Cognito::UserPoolClient",
@@ -183,10 +180,7 @@
183180
"RefreshToken": "days"
184181
},
185182
"UserPoolId": "us-east-1_1rvCNKN5B"
186-
},
187-
"DependsOn": [
188-
"amplifyAuthUserPool4BA7F805"
189-
]
183+
}
190184
},
191185
"amplifyAuthIdentityPool3FDE84CC": {
192186
"Type": "AWS::Cognito::IdentityPool",
@@ -241,10 +235,7 @@
241235
"unauthenticated": "arn:aws:iam::123456789012:role/amplify-backendonly-main-5e0fa-unauthRole",
242236
"authenticated": "arn:aws:iam::123456789012:role/amplify-backendonly-main-5e0fa-authRole"
243237
}
244-
},
245-
"DependsOn": [
246-
"amplifyAuthIdentityPool3FDE84CC"
247-
]
238+
}
248239
}
249240
},
250241
"Conditions": {

amplify-migration-apps/backend-only/_snapshot.post.refactor/refactor.__from__.amplify-backendonly-main-5e0fa-storages3c31471c3-MQFWTKK6ETYR.__to__.amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I.source.template.json

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,6 @@
213213
"amplify-backendonly-main-5e0fa-authRole"
214214
]
215215
},
216-
"DependsOn": [],
217216
"Condition": "CreateAuthPublic"
218217
},
219218
"S3AuthProtectedPolicy": {
@@ -250,7 +249,6 @@
250249
"amplify-backendonly-main-5e0fa-authRole"
251250
]
252251
},
253-
"DependsOn": [],
254252
"Condition": "CreateAuthProtected"
255253
},
256254
"S3AuthPrivatePolicy": {
@@ -287,7 +285,6 @@
287285
"amplify-backendonly-main-5e0fa-authRole"
288286
]
289287
},
290-
"DependsOn": [],
291288
"Condition": "CreateAuthPrivate"
292289
},
293290
"S3AuthUploadPolicy": {
@@ -324,7 +321,6 @@
324321
"amplify-backendonly-main-5e0fa-authRole"
325322
]
326323
},
327-
"DependsOn": [],
328324
"Condition": "CreateAuthUploads"
329325
},
330326
"S3GuestPublicPolicy": {
@@ -361,7 +357,6 @@
361357
"amplify-backendonly-main-5e0fa-unauthRole"
362358
]
363359
},
364-
"DependsOn": [],
365360
"Condition": "CreateGuestPublic"
366361
},
367362
"S3AuthReadPolicy": {
@@ -416,7 +411,6 @@
416411
"amplify-backendonly-main-5e0fa-authRole"
417412
]
418413
},
419-
"DependsOn": [],
420414
"Condition": "AuthReadAndList"
421415
},
422416
"S3GuestReadPolicy": {
@@ -469,7 +463,6 @@
469463
"amplify-backendonly-main-5e0fa-unauthRole"
470464
]
471465
},
472-
"DependsOn": [],
473466
"Condition": "GuestReadAndList"
474467
}
475468
}

amplify-migration-apps/backend-only/_snapshot.post.refactor/refactor.__from__.amplify-backendonly-main-5e0fa-storages3c31471c3-MQFWTKK6ETYR.__to__.amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I.target.template.json

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,6 @@
6969
"ServiceToken": "arn:aws:lambda:us-east-1:123456789012:function:amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I/CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F",
7070
"BucketName": "amplify-backendonly-ge-backendonlycb1a13ab81664-hysxrjfwrstc"
7171
},
72-
"DependsOn": [
73-
"backendonlycb1a13ab81664ecaa7d015068ab2d0165e0fagen2mainBucketPolicy14D90AB6"
74-
],
7572
"UpdateReplacePolicy": "Delete",
7673
"DeletionPolicy": "Delete",
7774
"Metadata": {
@@ -128,9 +125,6 @@
128125
]
129126
}
130127
},
131-
"DependsOn": [
132-
"CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092"
133-
],
134128
"Metadata": {
135129
"aws:cdk:path": "amplify-backendonly-gen2main-branch-8e0f260810/storage/Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler",
136130
"aws:asset:path": "asset.faa95a81ae7d7373f3e1f242268f904eb748d8d0fdd306e8a6fe515a1905a7d6",

amplify-migration-apps/backend-only/_snapshot.post.refactor/update.amplify-backendonly-gen2main-branch-8e0f260810-auth179371D7-SEM95NL3BKFT.template.json

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -303,10 +303,6 @@
303303
"authenticated": "arn:aws:iam::123456789012:role/amplify-backendonly-ge-amplifyAuthauthenticatedU-NrnOsacJVeCr"
304304
}
305305
},
306-
"DependsOn": [
307-
"amplifyAuthIdentityPool3FDE84CC",
308-
"amplifyAuthUserPoolAppClient2626C6F8"
309-
],
310306
"Metadata": {
311307
"aws:cdk:path": "amplify-backendonly-gen2main-branch-8e0f260810/auth/amplifyAuth/IdentityPoolRoleAttachment"
312308
}

amplify-migration-apps/backend-only/_snapshot.post.refactor/update.amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I.template.json

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,6 @@
141141
"ServiceToken": "arn:aws:lambda:us-east-1:123456789012:function:amplify-backendonly-gen2main-branch-8e0f260810-storage0EC3F24A-1BTE7UH0TFE2I/CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F",
142142
"BucketName": "amplify-backendonly-ge-backendonlycb1a13ab81664-hysxrjfwrstc"
143143
},
144-
"DependsOn": [
145-
"backendonlycb1a13ab81664ecaa7d015068ab2d0165e0fagen2mainBucketPolicy14D90AB6"
146-
],
147144
"UpdateReplacePolicy": "Delete",
148145
"DeletionPolicy": "Delete",
149146
"Metadata": {
@@ -200,9 +197,6 @@
200197
]
201198
}
202199
},
203-
"DependsOn": [
204-
"CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092"
205-
],
206200
"Metadata": {
207201
"aws:cdk:path": "amplify-backendonly-gen2main-branch-8e0f260810/storage/Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler",
208202
"aws:asset:path": "asset.faa95a81ae7d7373f3e1f242268f904eb748d8d0fdd306e8a6fe515a1905a7d6",

0 commit comments

Comments
 (0)