@totaland/create-starter-kit 1.0.0 → 2.0.1
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/README.md +130 -18
- package/bin/index.js +109 -21
- package/package.json +2 -2
- package/templates/backend/.github/agents/ /360/237/216/255 planner.agent.md" +92 -0
- package/templates/backend/.github/agents/api-architect.agent.md +41 -0
- package/templates/backend/.github/agents/code-reviewer.agent.md +26 -0
- package/templates/backend/.github/agents/code-simplifier.agent.md +41 -0
- package/templates/backend/.github/agents/code-skeptic.agent.md +74 -0
- package/templates/backend/.github/agents/docs-specialist.agent.md +25 -0
- package/templates/backend/.github/agents/implementation-plan.agent.md +160 -0
- package/templates/backend/.github/agents/janitor.agent.md +90 -0
- package/templates/backend/.github/agents/ms-sql-dba.agent.md +25 -0
- package/templates/backend/.github/agents/plan.agent.md +115 -0
- package/templates/backend/.github/agents/planner.agent.md +15 -0
- package/templates/backend/.github/agents/playwright-tester.agent.md +13 -0
- package/templates/backend/.github/agents/postgresql-dba.agent.md +18 -0
- package/templates/backend/.github/agents/prd.agent.md +202 -0
- package/templates/backend/.github/agents/research-technical-spike.agent.md +170 -0
- package/templates/backend/.github/agents/software-engineer-agent-v1.agent.md +165 -0
- package/templates/backend/.github/agents/task-planner.agent.md +375 -0
- package/templates/backend/.github/agents/task-researcher.agent.md +255 -0
- package/templates/backend/.github/agents/tdd-green.agent.md +60 -0
- package/templates/backend/.github/agents/tdd-red.agent.md +60 -0
- package/templates/backend/.github/agents/tdd-refactor.agent.md +85 -0
- package/templates/backend/.github/agents/tech-debt-remediation-plan.agent.md +50 -0
- package/templates/backend/.github/agents/typescript-mcp-expert.agent.md +91 -0
- package/templates/backend/.github/agents/ultimate-thinking-beastmode.agent.md +644 -0
- package/templates/backend/.github/agents//360/237/216/255 generator.agent.md" +264 -0
- package/templates/backend/.github/agents//360/237/216/255 healer.agent.md" +44 -0
- package/templates/backend/.github/agents//360/237/216/255 pom.agent.md" +308 -0
- package/templates/backend/.github/instructions/a11y.instructions.md +369 -0
- package/templates/backend/.github/instructions/ms-sql-dba.instructions.md +25 -0
- package/templates/backend/.github/instructions/object-calisthenics.instructions.md +302 -0
- package/templates/backend/.github/instructions/performance-optimization.instructions.md +420 -0
- package/templates/backend/.github/instructions/playwright-python.instructions.md +62 -0
- package/templates/backend/.github/instructions/playwright-typescript.instructions.md +86 -0
- package/templates/backend/.github/instructions/security-and-owasp.instructions.md +51 -0
- package/templates/backend/.github/instructions/self-explanatory-code-commenting.instructions.md +162 -0
- package/templates/backend/.github/instructions/spec-driven-workflow-v1.instructions.md +323 -0
- package/templates/backend/.github/instructions/sql-sp-generation.instructions.md +74 -0
- package/templates/backend/.github/instructions/task-implementation.instructions.md +190 -0
- package/templates/backend/.github/instructions/typescript-mcp-server.instructions.md +228 -0
- package/templates/backend/.github/prompts/ai-prompt-engineering-safety-review.prompt.md +229 -0
- package/templates/backend/.github/prompts/architecture-blueprint-generator.prompt.md +321 -0
- package/templates/backend/.github/prompts/breakdown-epic-arch.prompt.md +65 -0
- package/templates/backend/.github/prompts/breakdown-epic-pm.prompt.md +57 -0
- package/templates/backend/.github/prompts/breakdown-feature-implementation.prompt.md +127 -0
- package/templates/backend/.github/prompts/breakdown-feature-prd.prompt.md +60 -0
- package/templates/backend/.github/prompts/breakdown-plan.prompt.md +508 -0
- package/templates/backend/.github/prompts/copilot-instructions-blueprint-generator.prompt.md +293 -0
- package/templates/backend/.github/prompts/create-agentsmd.prompt.md +248 -0
- package/templates/backend/.github/prompts/create-github-issue-feature-from-specification.prompt.md +27 -0
- package/templates/backend/.github/prompts/create-github-issues-feature-from-implementation-plan.prompt.md +27 -0
- package/templates/backend/.github/prompts/create-github-issues-for-unmet-specification-requirements.prompt.md +35 -0
- package/templates/backend/.github/prompts/create-implementation-plan.prompt.md +156 -0
- package/templates/backend/.github/prompts/create-llms.prompt.md +209 -0
- package/templates/backend/.github/prompts/create-specification.prompt.md +126 -0
- package/templates/backend/.github/prompts/create-technical-spike.prompt.md +230 -0
- package/templates/backend/.github/prompts/csharp-nunit.prompt.md +71 -0
- package/templates/backend/.github/prompts/ef-core.prompt.md +76 -0
- package/templates/backend/.github/prompts/folder-structure-blueprint-generator.prompt.md +404 -0
- package/templates/backend/.github/prompts/gen-specs-as-issues.prompt.md +165 -0
- package/templates/backend/.github/prompts/generate-custom-instructions-from-codebase.prompt.md +239 -0
- package/templates/backend/.github/prompts/java-junit.prompt.md +64 -0
- package/templates/backend/.github/prompts/memory-merger.prompt.md +107 -0
- package/templates/backend/.github/prompts/multi-stage-dockerfile.prompt.md +46 -0
- package/templates/backend/.github/prompts/playwright-automation-fill-in-form.prompt.md +29 -0
- package/templates/backend/.github/prompts/playwright-explore-website.prompt.md +19 -0
- package/templates/backend/.github/prompts/playwright-generate-test.prompt.md +19 -0
- package/templates/backend/.github/prompts/postgresql-code-review.prompt.md +214 -0
- package/templates/backend/.github/prompts/postgresql-optimization.prompt.md +406 -0
- package/templates/backend/.github/prompts/project-workflow-analysis-blueprint-generator.prompt.md +294 -0
- package/templates/backend/.github/prompts/prompt-builder.prompt.md +142 -0
- package/templates/backend/.github/prompts/remember.prompt.md +125 -0
- package/templates/backend/.github/prompts/review-and-refactor.prompt.md +15 -0
- package/templates/backend/.github/prompts/sql-code-review.prompt.md +303 -0
- package/templates/backend/.github/prompts/sql-optimization.prompt.md +298 -0
- package/templates/backend/.github/prompts/suggest-awesome-github-copilot-agents.prompt.md +72 -0
- package/templates/backend/.github/prompts/suggest-awesome-github-copilot-chatmodes.prompt.md +71 -0
- package/templates/backend/.github/prompts/suggest-awesome-github-copilot-collections.prompt.md +149 -0
- package/templates/backend/.github/prompts/suggest-awesome-github-copilot-instructions.prompt.md +88 -0
- package/templates/backend/.github/prompts/suggest-awesome-github-copilot-prompts.prompt.md +71 -0
- package/templates/backend/.github/prompts/technology-stack-blueprint-generator.prompt.md +242 -0
- package/templates/backend/.github/prompts/typescript-mcp-server-generator.prompt.md +90 -0
- package/templates/backend/.github/prompts/update-implementation-plan.prompt.md +157 -0
- package/templates/backend/.github/prompts/update-markdown-file-index.prompt.md +76 -0
- package/templates/backend/Project_Folders_Structure_Blueprint.md +529 -0
- package/templates/backend/README.md +99 -0
- package/templates/backend/biome.json +45 -0
- package/{template → templates/backend}/drizzle.config.ts +1 -1
- package/{template → templates/backend}/package.json +9 -4
- package/templates/backend/pnpm-lock.yaml +4240 -0
- package/templates/backend/src/features/health/health.test.ts +23 -0
- package/{template → templates/backend}/src/features/health/index.ts +1 -0
- package/templates/backend/src/features/health/schemas.ts +29 -0
- package/templates/backend/src/features/orders/controller.ts +18 -0
- package/templates/backend/src/features/orders/index.ts +10 -0
- package/templates/backend/src/features/orders/schemas.ts +62 -0
- package/{template → templates/backend}/src/index.ts +3 -36
- package/templates/backend/src/lib/openapi.ts +25 -0
- package/templates/backend/src/lib/validateRequest.test.ts +84 -0
- package/templates/backend/src/lib/validateRequest.ts +72 -0
- package/{template → templates/backend}/tsconfig.json +2 -2
- package/{template → templates/backend}/vitest.config.ts +8 -1
- package/templates/frontend/.env.example +7 -0
- package/templates/frontend/.github/agents/ /360/237/216/255 planner.agent.md" +92 -0
- package/templates/frontend/.github/agents/api-architect.agent.md +41 -0
- package/templates/frontend/.github/agents/code-reviewer.agent.md +26 -0
- package/templates/frontend/.github/agents/code-simplifier.agent.md +41 -0
- package/templates/frontend/.github/agents/code-skeptic.agent.md +74 -0
- package/templates/frontend/.github/agents/docs-specialist.agent.md +25 -0
- package/templates/frontend/.github/agents/implementation-plan.agent.md +160 -0
- package/templates/frontend/.github/agents/janitor.agent.md +90 -0
- package/templates/frontend/.github/agents/ms-sql-dba.agent.md +25 -0
- package/templates/frontend/.github/agents/plan.agent.md +115 -0
- package/templates/frontend/.github/agents/planner.agent.md +15 -0
- package/templates/frontend/.github/agents/playwright-tester.agent.md +13 -0
- package/templates/frontend/.github/agents/postgresql-dba.agent.md +18 -0
- package/templates/frontend/.github/agents/prd.agent.md +202 -0
- package/templates/frontend/.github/agents/research-technical-spike.agent.md +170 -0
- package/templates/frontend/.github/agents/software-engineer-agent-v1.agent.md +165 -0
- package/templates/frontend/.github/agents/task-planner.agent.md +375 -0
- package/templates/frontend/.github/agents/task-researcher.agent.md +255 -0
- package/templates/frontend/.github/agents/tdd-green.agent.md +60 -0
- package/templates/frontend/.github/agents/tdd-red.agent.md +60 -0
- package/templates/frontend/.github/agents/tdd-refactor.agent.md +85 -0
- package/templates/frontend/.github/agents/tech-debt-remediation-plan.agent.md +50 -0
- package/templates/frontend/.github/agents/typescript-mcp-expert.agent.md +91 -0
- package/templates/frontend/.github/agents/ultimate-thinking-beastmode.agent.md +644 -0
- package/templates/frontend/.github/agents//360/237/216/255 generator.agent.md" +264 -0
- package/templates/frontend/.github/agents//360/237/216/255 healer.agent.md" +44 -0
- package/templates/frontend/.github/agents//360/237/216/255 pom.agent.md" +308 -0
- package/templates/frontend/.github/instructions/a11y.instructions.md +369 -0
- package/templates/frontend/.github/instructions/ms-sql-dba.instructions.md +25 -0
- package/templates/frontend/.github/instructions/object-calisthenics.instructions.md +302 -0
- package/templates/frontend/.github/instructions/performance-optimization.instructions.md +420 -0
- package/templates/frontend/.github/instructions/playwright-python.instructions.md +62 -0
- package/templates/frontend/.github/instructions/playwright-typescript.instructions.md +86 -0
- package/templates/frontend/.github/instructions/security-and-owasp.instructions.md +51 -0
- package/templates/frontend/.github/instructions/self-explanatory-code-commenting.instructions.md +162 -0
- package/templates/frontend/.github/instructions/spec-driven-workflow-v1.instructions.md +323 -0
- package/templates/frontend/.github/instructions/sql-sp-generation.instructions.md +74 -0
- package/templates/frontend/.github/instructions/task-implementation.instructions.md +190 -0
- package/templates/frontend/.github/instructions/typescript-mcp-server.instructions.md +228 -0
- package/templates/frontend/.github/prompts/ai-prompt-engineering-safety-review.prompt.md +229 -0
- package/templates/frontend/.github/prompts/architecture-blueprint-generator.prompt.md +321 -0
- package/templates/frontend/.github/prompts/breakdown-epic-arch.prompt.md +65 -0
- package/templates/frontend/.github/prompts/breakdown-epic-pm.prompt.md +57 -0
- package/templates/frontend/.github/prompts/breakdown-feature-implementation.prompt.md +127 -0
- package/templates/frontend/.github/prompts/breakdown-feature-prd.prompt.md +60 -0
- package/templates/frontend/.github/prompts/breakdown-plan.prompt.md +508 -0
- package/templates/frontend/.github/prompts/copilot-instructions-blueprint-generator.prompt.md +293 -0
- package/templates/frontend/.github/prompts/create-agentsmd.prompt.md +248 -0
- package/templates/frontend/.github/prompts/create-github-issue-feature-from-specification.prompt.md +27 -0
- package/templates/frontend/.github/prompts/create-github-issues-feature-from-implementation-plan.prompt.md +27 -0
- package/templates/frontend/.github/prompts/create-github-issues-for-unmet-specification-requirements.prompt.md +35 -0
- package/templates/frontend/.github/prompts/create-implementation-plan.prompt.md +156 -0
- package/templates/frontend/.github/prompts/create-llms.prompt.md +209 -0
- package/templates/frontend/.github/prompts/create-specification.prompt.md +126 -0
- package/templates/frontend/.github/prompts/create-technical-spike.prompt.md +230 -0
- package/templates/frontend/.github/prompts/csharp-nunit.prompt.md +71 -0
- package/templates/frontend/.github/prompts/ef-core.prompt.md +76 -0
- package/templates/frontend/.github/prompts/folder-structure-blueprint-generator.prompt.md +404 -0
- package/templates/frontend/.github/prompts/gen-specs-as-issues.prompt.md +165 -0
- package/templates/frontend/.github/prompts/generate-custom-instructions-from-codebase.prompt.md +239 -0
- package/templates/frontend/.github/prompts/java-junit.prompt.md +64 -0
- package/templates/frontend/.github/prompts/memory-merger.prompt.md +107 -0
- package/templates/frontend/.github/prompts/multi-stage-dockerfile.prompt.md +46 -0
- package/templates/frontend/.github/prompts/playwright-automation-fill-in-form.prompt.md +29 -0
- package/templates/frontend/.github/prompts/playwright-explore-website.prompt.md +19 -0
- package/templates/frontend/.github/prompts/playwright-generate-test.prompt.md +19 -0
- package/templates/frontend/.github/prompts/postgresql-code-review.prompt.md +214 -0
- package/templates/frontend/.github/prompts/postgresql-optimization.prompt.md +406 -0
- package/templates/frontend/.github/prompts/project-workflow-analysis-blueprint-generator.prompt.md +294 -0
- package/templates/frontend/.github/prompts/prompt-builder.prompt.md +142 -0
- package/templates/frontend/.github/prompts/remember.prompt.md +125 -0
- package/templates/frontend/.github/prompts/review-and-refactor.prompt.md +15 -0
- package/templates/frontend/.github/prompts/sql-code-review.prompt.md +303 -0
- package/templates/frontend/.github/prompts/sql-optimization.prompt.md +298 -0
- package/templates/frontend/.github/prompts/suggest-awesome-github-copilot-agents.prompt.md +72 -0
- package/templates/frontend/.github/prompts/suggest-awesome-github-copilot-chatmodes.prompt.md +71 -0
- package/templates/frontend/.github/prompts/suggest-awesome-github-copilot-collections.prompt.md +149 -0
- package/templates/frontend/.github/prompts/suggest-awesome-github-copilot-instructions.prompt.md +88 -0
- package/templates/frontend/.github/prompts/suggest-awesome-github-copilot-prompts.prompt.md +71 -0
- package/templates/frontend/.github/prompts/technology-stack-blueprint-generator.prompt.md +242 -0
- package/templates/frontend/.github/prompts/typescript-mcp-server-generator.prompt.md +90 -0
- package/templates/frontend/.github/prompts/update-implementation-plan.prompt.md +157 -0
- package/templates/frontend/.github/prompts/update-markdown-file-index.prompt.md +76 -0
- package/templates/frontend/README.md +199 -0
- package/templates/frontend/biome.json +45 -0
- package/templates/frontend/components.json +22 -0
- package/templates/frontend/index.html +13 -0
- package/templates/frontend/package.json +44 -0
- package/templates/frontend/pnpm-lock.yaml +2011 -0
- package/templates/frontend/postcss.config.js +6 -0
- package/templates/frontend/public/vite.svg +1 -0
- package/templates/frontend/src/App.css +42 -0
- package/templates/frontend/src/App.tsx +17 -0
- package/templates/frontend/src/assets/react.svg +1 -0
- package/templates/frontend/src/components/layout/layout.component.tsx +31 -0
- package/templates/frontend/src/components/menu-toggle-icon.tsx +53 -0
- package/templates/frontend/src/components/ui/button.tsx +57 -0
- package/templates/frontend/src/docs/RECOMMENDED_LIBRARIES.md +226 -0
- package/templates/frontend/src/docs/SETUP_SUMMARY.md +162 -0
- package/templates/frontend/src/hooks/use-scroll.ts +21 -0
- package/templates/frontend/src/index.css +121 -0
- package/templates/frontend/src/lib/api-client.ts +46 -0
- package/templates/frontend/src/lib/utils.ts +6 -0
- package/templates/frontend/src/main.tsx +30 -0
- package/templates/frontend/src/pages/about/about.page.tsx +50 -0
- package/templates/frontend/src/pages/home/home.page.tsx +43 -0
- package/templates/frontend/tailwind.config.js +59 -0
- package/templates/frontend/tsconfig.app.json +41 -0
- package/templates/frontend/tsconfig.json +13 -0
- package/templates/frontend/tsconfig.node.json +26 -0
- package/templates/frontend/vite.config.ts +14 -0
- package/template/.env.example +0 -8
- package/template/AGENTS.md +0 -23
- package/template/ARCHITECTURE.md +0 -53
- package/template/ORDER_SYSTEM.md +0 -93
- package/template/biome.json +0 -3
- package/template/src/features/orders/controller.ts +0 -13
- package/template/src/features/orders/index.ts +0 -7
- /package/{template → templates/backend}/knip.json +0 -0
- /package/{template → templates/backend}/playwright.config.ts +0 -0
- /package/{template → templates/backend}/pnpm-workspace.yaml +0 -0
- /package/{template → templates/backend}/src/features/health/controller.ts +0 -0
- /package/{template → templates/backend}/tsconfig.build.json +0 -0
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
---
|
|
2
|
+
applyTo: '*'
|
|
3
|
+
description: 'The most comprehensive, practical, and engineer-authored performance optimization instructions for all languages, frameworks, and stacks. Covers frontend, backend, and database best practices with actionable guidance, scenario-based checklists, troubleshooting, and pro tips.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Performance Optimization Best Practices
|
|
7
|
+
|
|
8
|
+
## Introduction
|
|
9
|
+
|
|
10
|
+
Performance isn't just a buzzword—it's the difference between a product people love and one they abandon. I've seen firsthand how a slow app can frustrate users, rack up cloud bills, and even lose customers. This guide is a living collection of the most effective, real-world performance practices I've used and reviewed, covering frontend, backend, and database layers, as well as advanced topics. Use it as a reference, a checklist, and a source of inspiration for building fast, efficient, and scalable software.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## General Principles
|
|
15
|
+
|
|
16
|
+
- **Measure First, Optimize Second:** Always profile and measure before optimizing. Use benchmarks, profilers, and monitoring tools to identify real bottlenecks. Guessing is the enemy of performance.
|
|
17
|
+
- *Pro Tip:* Use tools like Chrome DevTools, Lighthouse, New Relic, Datadog, Py-Spy, or your language's built-in profilers.
|
|
18
|
+
- **Optimize for the Common Case:** Focus on optimizing code paths that are most frequently executed. Don't waste time on rare edge cases unless they're critical.
|
|
19
|
+
- **Avoid Premature Optimization:** Write clear, maintainable code first; optimize only when necessary. Premature optimization can make code harder to read and maintain.
|
|
20
|
+
- **Minimize Resource Usage:** Use memory, CPU, network, and disk resources efficiently. Always ask: "Can this be done with less?"
|
|
21
|
+
- **Prefer Simplicity:** Simple algorithms and data structures are often faster and easier to optimize. Don't over-engineer.
|
|
22
|
+
- **Document Performance Assumptions:** Clearly comment on any code that is performance-critical or has non-obvious optimizations. Future maintainers (including you) will thank you.
|
|
23
|
+
- **Understand the Platform:** Know the performance characteristics of your language, framework, and runtime. What's fast in Python may be slow in JavaScript, and vice versa.
|
|
24
|
+
- **Automate Performance Testing:** Integrate performance tests and benchmarks into your CI/CD pipeline. Catch regressions early.
|
|
25
|
+
- **Set Performance Budgets:** Define acceptable limits for load time, memory usage, API latency, etc. Enforce them with automated checks.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Frontend Performance
|
|
30
|
+
|
|
31
|
+
### Rendering and DOM
|
|
32
|
+
- **Minimize DOM Manipulations:** Batch updates where possible. Frequent DOM changes are expensive.
|
|
33
|
+
- *Anti-pattern:* Updating the DOM in a loop. Instead, build a document fragment and append it once.
|
|
34
|
+
- **Virtual DOM Frameworks:** Use React, Vue, or similar efficiently—avoid unnecessary re-renders.
|
|
35
|
+
- *React Example:* Use `React.memo`, `useMemo`, and `useCallback` to prevent unnecessary renders.
|
|
36
|
+
- **Keys in Lists:** Always use stable keys in lists to help virtual DOM diffing. Avoid using array indices as keys unless the list is static.
|
|
37
|
+
- **Avoid Inline Styles:** Inline styles can trigger layout thrashing. Prefer CSS classes.
|
|
38
|
+
- **CSS Animations:** Use CSS transitions/animations over JavaScript for smoother, GPU-accelerated effects.
|
|
39
|
+
- **Defer Non-Critical Rendering:** Use `requestIdleCallback` or similar to defer work until the browser is idle.
|
|
40
|
+
|
|
41
|
+
### Asset Optimization
|
|
42
|
+
- **Image Compression:** Use tools like ImageOptim, Squoosh, or TinyPNG. Prefer modern formats (WebP, AVIF) for web delivery.
|
|
43
|
+
- **SVGs for Icons:** SVGs scale well and are often smaller than PNGs for simple graphics.
|
|
44
|
+
- **Minification and Bundling:** Use Webpack, Rollup, or esbuild to bundle and minify JS/CSS. Enable tree-shaking to remove dead code.
|
|
45
|
+
- **Cache Headers:** Set long-lived cache headers for static assets. Use cache busting for updates.
|
|
46
|
+
- **Lazy Loading:** Use `loading="lazy"` for images, and dynamic imports for JS modules/components.
|
|
47
|
+
- **Font Optimization:** Use only the character sets you need. Subset fonts and use `font-display: swap`.
|
|
48
|
+
|
|
49
|
+
### Network Optimization
|
|
50
|
+
- **Reduce HTTP Requests:** Combine files, use image sprites, and inline critical CSS.
|
|
51
|
+
- **HTTP/2 and HTTP/3:** Enable these protocols for multiplexing and lower latency.
|
|
52
|
+
- **Client-Side Caching:** Use Service Workers, IndexedDB, and localStorage for offline and repeat visits.
|
|
53
|
+
- **CDNs:** Serve static assets from a CDN close to your users. Use multiple CDNs for redundancy.
|
|
54
|
+
- **Defer/Async Scripts:** Use `defer` or `async` for non-critical JS to avoid blocking rendering.
|
|
55
|
+
- **Preload and Prefetch:** Use `<link rel="preload">` and `<link rel="prefetch">` for critical resources.
|
|
56
|
+
|
|
57
|
+
### JavaScript Performance
|
|
58
|
+
- **Avoid Blocking the Main Thread:** Offload heavy computation to Web Workers.
|
|
59
|
+
- **Debounce/Throttle Events:** For scroll, resize, and input events, use debounce/throttle to limit handler frequency.
|
|
60
|
+
- **Memory Leaks:** Clean up event listeners, intervals, and DOM references. Use browser dev tools to check for detached nodes.
|
|
61
|
+
- **Efficient Data Structures:** Use Maps/Sets for lookups, TypedArrays for numeric data.
|
|
62
|
+
- **Avoid Global Variables:** Globals can cause memory leaks and unpredictable performance.
|
|
63
|
+
- **Avoid Deep Object Cloning:** Use shallow copies or libraries like lodash's `cloneDeep` only when necessary.
|
|
64
|
+
|
|
65
|
+
### Accessibility and Performance
|
|
66
|
+
- **Accessible Components:** Ensure ARIA updates are not excessive. Use semantic HTML for both accessibility and performance.
|
|
67
|
+
- **Screen Reader Performance:** Avoid rapid DOM updates that can overwhelm assistive tech.
|
|
68
|
+
|
|
69
|
+
### Framework-Specific Tips
|
|
70
|
+
#### React
|
|
71
|
+
- Use `React.memo`, `useMemo`, and `useCallback` to avoid unnecessary renders.
|
|
72
|
+
- Split large components and use code-splitting (`React.lazy`, `Suspense`).
|
|
73
|
+
- Avoid anonymous functions in render; they create new references on every render.
|
|
74
|
+
- Use `ErrorBoundary` to catch and handle errors gracefully.
|
|
75
|
+
- Profile with React DevTools Profiler.
|
|
76
|
+
|
|
77
|
+
#### Angular
|
|
78
|
+
- Use OnPush change detection for components that don't need frequent updates.
|
|
79
|
+
- Avoid complex expressions in templates; move logic to the component class.
|
|
80
|
+
- Use `trackBy` in `ngFor` for efficient list rendering.
|
|
81
|
+
- Lazy load modules and components with the Angular Router.
|
|
82
|
+
- Profile with Angular DevTools.
|
|
83
|
+
|
|
84
|
+
#### Vue
|
|
85
|
+
- Use computed properties over methods in templates for caching.
|
|
86
|
+
- Use `v-show` vs `v-if` appropriately (`v-show` is better for toggling visibility frequently).
|
|
87
|
+
- Lazy load components and routes with Vue Router.
|
|
88
|
+
- Profile with Vue Devtools.
|
|
89
|
+
|
|
90
|
+
### Common Frontend Pitfalls
|
|
91
|
+
- Loading large JS bundles on initial page load.
|
|
92
|
+
- Not compressing images or using outdated formats.
|
|
93
|
+
- Failing to clean up event listeners, causing memory leaks.
|
|
94
|
+
- Overusing third-party libraries for simple tasks.
|
|
95
|
+
- Ignoring mobile performance (test on real devices!).
|
|
96
|
+
|
|
97
|
+
### Frontend Troubleshooting
|
|
98
|
+
- Use Chrome DevTools' Performance tab to record and analyze slow frames.
|
|
99
|
+
- Use Lighthouse to audit performance and get actionable suggestions.
|
|
100
|
+
- Use WebPageTest for real-world load testing.
|
|
101
|
+
- Monitor Core Web Vitals (LCP, FID, CLS) for user-centric metrics.
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## Backend Performance
|
|
106
|
+
|
|
107
|
+
### Algorithm and Data Structure Optimization
|
|
108
|
+
- **Choose the Right Data Structure:** Arrays for sequential access, hash maps for fast lookups, trees for hierarchical data, etc.
|
|
109
|
+
- **Efficient Algorithms:** Use binary search, quicksort, or hash-based algorithms where appropriate.
|
|
110
|
+
- **Avoid O(n^2) or Worse:** Profile nested loops and recursive calls. Refactor to reduce complexity.
|
|
111
|
+
- **Batch Processing:** Process data in batches to reduce overhead (e.g., bulk database inserts).
|
|
112
|
+
- **Streaming:** Use streaming APIs for large data sets to avoid loading everything into memory.
|
|
113
|
+
|
|
114
|
+
### Concurrency and Parallelism
|
|
115
|
+
- **Asynchronous I/O:** Use async/await, callbacks, or event loops to avoid blocking threads.
|
|
116
|
+
- **Thread/Worker Pools:** Use pools to manage concurrency and avoid resource exhaustion.
|
|
117
|
+
- **Avoid Race Conditions:** Use locks, semaphores, or atomic operations where needed.
|
|
118
|
+
- **Bulk Operations:** Batch network/database calls to reduce round trips.
|
|
119
|
+
- **Backpressure:** Implement backpressure in queues and pipelines to avoid overload.
|
|
120
|
+
|
|
121
|
+
### Caching
|
|
122
|
+
- **Cache Expensive Computations:** Use in-memory caches (Redis, Memcached) for hot data.
|
|
123
|
+
- **Cache Invalidation:** Use time-based (TTL), event-based, or manual invalidation. Stale cache is worse than no cache.
|
|
124
|
+
- **Distributed Caching:** For multi-server setups, use distributed caches and be aware of consistency issues.
|
|
125
|
+
- **Cache Stampede Protection:** Use locks or request coalescing to prevent thundering herd problems.
|
|
126
|
+
- **Don't Cache Everything:** Some data is too volatile or sensitive to cache.
|
|
127
|
+
|
|
128
|
+
### API and Network
|
|
129
|
+
- **Minimize Payloads:** Use JSON, compress responses (gzip, Brotli), and avoid sending unnecessary data.
|
|
130
|
+
- **Pagination:** Always paginate large result sets. Use cursors for real-time data.
|
|
131
|
+
- **Rate Limiting:** Protect APIs from abuse and overload.
|
|
132
|
+
- **Connection Pooling:** Reuse connections for databases and external services.
|
|
133
|
+
- **Protocol Choice:** Use HTTP/2, gRPC, or WebSockets for high-throughput, low-latency communication.
|
|
134
|
+
|
|
135
|
+
### Logging and Monitoring
|
|
136
|
+
- **Minimize Logging in Hot Paths:** Excessive logging can slow down critical code.
|
|
137
|
+
- **Structured Logging:** Use JSON or key-value logs for easier parsing and analysis.
|
|
138
|
+
- **Monitor Everything:** Latency, throughput, error rates, resource usage. Use Prometheus, Grafana, Datadog, or similar.
|
|
139
|
+
- **Alerting:** Set up alerts for performance regressions and resource exhaustion.
|
|
140
|
+
|
|
141
|
+
### Language/Framework-Specific Tips
|
|
142
|
+
#### Node.js
|
|
143
|
+
- Use asynchronous APIs; avoid blocking the event loop (e.g., never use `fs.readFileSync` in production).
|
|
144
|
+
- Use clustering or worker threads for CPU-bound tasks.
|
|
145
|
+
- Limit concurrent open connections to avoid resource exhaustion.
|
|
146
|
+
- Use streams for large file or network data processing.
|
|
147
|
+
- Profile with `clinic.js`, `node --inspect`, or Chrome DevTools.
|
|
148
|
+
|
|
149
|
+
#### Python
|
|
150
|
+
- Use built-in data structures (`dict`, `set`, `deque`) for speed.
|
|
151
|
+
- Profile with `cProfile`, `line_profiler`, or `Py-Spy`.
|
|
152
|
+
- Use `multiprocessing` or `asyncio` for parallelism.
|
|
153
|
+
- Avoid GIL bottlenecks in CPU-bound code; use C extensions or subprocesses.
|
|
154
|
+
- Use `lru_cache` for memoization.
|
|
155
|
+
|
|
156
|
+
#### Java
|
|
157
|
+
- Use efficient collections (`ArrayList`, `HashMap`, etc.).
|
|
158
|
+
- Profile with VisualVM, JProfiler, or YourKit.
|
|
159
|
+
- Use thread pools (`Executors`) for concurrency.
|
|
160
|
+
- Tune JVM options for heap and garbage collection (`-Xmx`, `-Xms`, `-XX:+UseG1GC`).
|
|
161
|
+
- Use `CompletableFuture` for async programming.
|
|
162
|
+
|
|
163
|
+
#### .NET
|
|
164
|
+
- Use `async/await` for I/O-bound operations.
|
|
165
|
+
- Use `Span<T>` and `Memory<T>` for efficient memory access.
|
|
166
|
+
- Profile with dotTrace, Visual Studio Profiler, or PerfView.
|
|
167
|
+
- Pool objects and connections where appropriate.
|
|
168
|
+
- Use `IAsyncEnumerable<T>` for streaming data.
|
|
169
|
+
|
|
170
|
+
### Common Backend Pitfalls
|
|
171
|
+
- Synchronous/blocking I/O in web servers.
|
|
172
|
+
- Not using connection pooling for databases.
|
|
173
|
+
- Over-caching or caching sensitive/volatile data.
|
|
174
|
+
- Ignoring error handling in async code.
|
|
175
|
+
- Not monitoring or alerting on performance regressions.
|
|
176
|
+
|
|
177
|
+
### Backend Troubleshooting
|
|
178
|
+
- Use flame graphs to visualize CPU usage.
|
|
179
|
+
- Use distributed tracing (OpenTelemetry, Jaeger, Zipkin) to track request latency across services.
|
|
180
|
+
- Use heap dumps and memory profilers to find leaks.
|
|
181
|
+
- Log slow queries and API calls for analysis.
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Database Performance
|
|
186
|
+
|
|
187
|
+
### Query Optimization
|
|
188
|
+
- **Indexes:** Use indexes on columns that are frequently queried, filtered, or joined. Monitor index usage and drop unused indexes.
|
|
189
|
+
- **Avoid SELECT *:** Select only the columns you need. Reduces I/O and memory usage.
|
|
190
|
+
- **Parameterized Queries:** Prevent SQL injection and improve plan caching.
|
|
191
|
+
- **Query Plans:** Analyze and optimize query execution plans. Use `EXPLAIN` in SQL databases.
|
|
192
|
+
- **Avoid N+1 Queries:** Use joins or batch queries to avoid repeated queries in loops.
|
|
193
|
+
- **Limit Result Sets:** Use `LIMIT`/`OFFSET` or cursors for large tables.
|
|
194
|
+
|
|
195
|
+
### Schema Design
|
|
196
|
+
- **Normalization:** Normalize to reduce redundancy, but denormalize for read-heavy workloads if needed.
|
|
197
|
+
- **Data Types:** Use the most efficient data types and set appropriate constraints.
|
|
198
|
+
- **Partitioning:** Partition large tables for scalability and manageability.
|
|
199
|
+
- **Archiving:** Regularly archive or purge old data to keep tables small and fast.
|
|
200
|
+
- **Foreign Keys:** Use them for data integrity, but be aware of performance trade-offs in high-write scenarios.
|
|
201
|
+
|
|
202
|
+
### Transactions
|
|
203
|
+
- **Short Transactions:** Keep transactions as short as possible to reduce lock contention.
|
|
204
|
+
- **Isolation Levels:** Use the lowest isolation level that meets your consistency needs.
|
|
205
|
+
- **Avoid Long-Running Transactions:** They can block other operations and increase deadlocks.
|
|
206
|
+
|
|
207
|
+
### Caching and Replication
|
|
208
|
+
- **Read Replicas:** Use for scaling read-heavy workloads. Monitor replication lag.
|
|
209
|
+
- **Cache Query Results:** Use Redis or Memcached for frequently accessed queries.
|
|
210
|
+
- **Write-Through/Write-Behind:** Choose the right strategy for your consistency needs.
|
|
211
|
+
- **Sharding:** Distribute data across multiple servers for scalability.
|
|
212
|
+
|
|
213
|
+
### NoSQL Databases
|
|
214
|
+
- **Design for Access Patterns:** Model your data for the queries you need.
|
|
215
|
+
- **Avoid Hot Partitions:** Distribute writes/reads evenly.
|
|
216
|
+
- **Unbounded Growth:** Watch for unbounded arrays or documents.
|
|
217
|
+
- **Sharding and Replication:** Use for scalability and availability.
|
|
218
|
+
- **Consistency Models:** Understand eventual vs strong consistency and choose appropriately.
|
|
219
|
+
|
|
220
|
+
### Common Database Pitfalls
|
|
221
|
+
- Missing or unused indexes.
|
|
222
|
+
- SELECT * in production queries.
|
|
223
|
+
- Not monitoring slow queries.
|
|
224
|
+
- Ignoring replication lag.
|
|
225
|
+
- Not archiving old data.
|
|
226
|
+
|
|
227
|
+
### Database Troubleshooting
|
|
228
|
+
- Use slow query logs to identify bottlenecks.
|
|
229
|
+
- Use `EXPLAIN` to analyze query plans.
|
|
230
|
+
- Monitor cache hit/miss ratios.
|
|
231
|
+
- Use database-specific monitoring tools (pg_stat_statements, MySQL Performance Schema).
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## Code Review Checklist for Performance
|
|
236
|
+
|
|
237
|
+
- [ ] Are there any obvious algorithmic inefficiencies (O(n^2) or worse)?
|
|
238
|
+
- [ ] Are data structures appropriate for their use?
|
|
239
|
+
- [ ] Are there unnecessary computations or repeated work?
|
|
240
|
+
- [ ] Is caching used where appropriate, and is invalidation handled correctly?
|
|
241
|
+
- [ ] Are database queries optimized, indexed, and free of N+1 issues?
|
|
242
|
+
- [ ] Are large payloads paginated, streamed, or chunked?
|
|
243
|
+
- [ ] Are there any memory leaks or unbounded resource usage?
|
|
244
|
+
- [ ] Are network requests minimized, batched, and retried on failure?
|
|
245
|
+
- [ ] Are assets optimized, compressed, and served efficiently?
|
|
246
|
+
- [ ] Are there any blocking operations in hot paths?
|
|
247
|
+
- [ ] Is logging in hot paths minimized and structured?
|
|
248
|
+
- [ ] Are performance-critical code paths documented and tested?
|
|
249
|
+
- [ ] Are there automated tests or benchmarks for performance-sensitive code?
|
|
250
|
+
- [ ] Are there alerts for performance regressions?
|
|
251
|
+
- [ ] Are there any anti-patterns (e.g., SELECT *, blocking I/O, global variables)?
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
## Advanced Topics
|
|
256
|
+
|
|
257
|
+
### Profiling and Benchmarking
|
|
258
|
+
- **Profilers:** Use language-specific profilers (Chrome DevTools, Py-Spy, VisualVM, dotTrace, etc.) to identify bottlenecks.
|
|
259
|
+
- **Microbenchmarks:** Write microbenchmarks for critical code paths. Use `benchmark.js`, `pytest-benchmark`, or JMH for Java.
|
|
260
|
+
- **A/B Testing:** Measure real-world impact of optimizations with A/B or canary releases.
|
|
261
|
+
- **Continuous Performance Testing:** Integrate performance tests into CI/CD. Use tools like k6, Gatling, or Locust.
|
|
262
|
+
|
|
263
|
+
### Memory Management
|
|
264
|
+
- **Resource Cleanup:** Always release resources (files, sockets, DB connections) promptly.
|
|
265
|
+
- **Object Pooling:** Use for frequently created/destroyed objects (e.g., DB connections, threads).
|
|
266
|
+
- **Heap Monitoring:** Monitor heap usage and garbage collection. Tune GC settings for your workload.
|
|
267
|
+
- **Memory Leaks:** Use leak detection tools (Valgrind, LeakCanary, Chrome DevTools).
|
|
268
|
+
|
|
269
|
+
### Scalability
|
|
270
|
+
- **Horizontal Scaling:** Design stateless services, use sharding/partitioning, and load balancers.
|
|
271
|
+
- **Auto-Scaling:** Use cloud auto-scaling groups and set sensible thresholds.
|
|
272
|
+
- **Bottleneck Analysis:** Identify and address single points of failure.
|
|
273
|
+
- **Distributed Systems:** Use idempotent operations, retries, and circuit breakers.
|
|
274
|
+
|
|
275
|
+
### Security and Performance
|
|
276
|
+
- **Efficient Crypto:** Use hardware-accelerated and well-maintained cryptographic libraries.
|
|
277
|
+
- **Validation:** Validate inputs efficiently; avoid regexes in hot paths.
|
|
278
|
+
- **Rate Limiting:** Protect against DoS without harming legitimate users.
|
|
279
|
+
|
|
280
|
+
### Mobile Performance
|
|
281
|
+
- **Startup Time:** Lazy load features, defer heavy work, and minimize initial bundle size.
|
|
282
|
+
- **Image/Asset Optimization:** Use responsive images and compress assets for mobile bandwidth.
|
|
283
|
+
- **Efficient Storage:** Use SQLite, Realm, or platform-optimized storage.
|
|
284
|
+
- **Profiling:** Use Android Profiler, Instruments (iOS), or Firebase Performance Monitoring.
|
|
285
|
+
|
|
286
|
+
### Cloud and Serverless
|
|
287
|
+
- **Cold Starts:** Minimize dependencies and keep functions warm.
|
|
288
|
+
- **Resource Allocation:** Tune memory/CPU for serverless functions.
|
|
289
|
+
- **Managed Services:** Use managed caching, queues, and DBs for scalability.
|
|
290
|
+
- **Cost Optimization:** Monitor and optimize for cloud cost as a performance metric.
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
## Practical Examples
|
|
295
|
+
|
|
296
|
+
### Example 1: Debouncing User Input in JavaScript
|
|
297
|
+
```javascript
|
|
298
|
+
// BAD: Triggers API call on every keystroke
|
|
299
|
+
input.addEventListener('input', (e) => {
|
|
300
|
+
fetch(`/search?q=${e.target.value}`);
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
// GOOD: Debounce API calls
|
|
304
|
+
let timeout;
|
|
305
|
+
input.addEventListener('input', (e) => {
|
|
306
|
+
clearTimeout(timeout);
|
|
307
|
+
timeout = setTimeout(() => {
|
|
308
|
+
fetch(`/search?q=${e.target.value}`);
|
|
309
|
+
}, 300);
|
|
310
|
+
});
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
### Example 2: Efficient SQL Query
|
|
314
|
+
```sql
|
|
315
|
+
-- BAD: Selects all columns and does not use an index
|
|
316
|
+
SELECT * FROM users WHERE email = 'user@example.com';
|
|
317
|
+
|
|
318
|
+
-- GOOD: Selects only needed columns and uses an index
|
|
319
|
+
SELECT id, name FROM users WHERE email = 'user@example.com';
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
### Example 3: Caching Expensive Computation in Python
|
|
323
|
+
```python
|
|
324
|
+
# BAD: Recomputes result every time
|
|
325
|
+
result = expensive_function(x)
|
|
326
|
+
|
|
327
|
+
# GOOD: Cache result
|
|
328
|
+
from functools import lru_cache
|
|
329
|
+
|
|
330
|
+
@lru_cache(maxsize=128)
|
|
331
|
+
def expensive_function(x):
|
|
332
|
+
...
|
|
333
|
+
result = expensive_function(x)
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
### Example 4: Lazy Loading Images in HTML
|
|
337
|
+
```html
|
|
338
|
+
<!-- BAD: Loads all images immediately -->
|
|
339
|
+
<img src="large-image.jpg" />
|
|
340
|
+
|
|
341
|
+
<!-- GOOD: Lazy loads images -->
|
|
342
|
+
<img src="large-image.jpg" loading="lazy" />
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
### Example 5: Asynchronous I/O in Node.js
|
|
346
|
+
```javascript
|
|
347
|
+
// BAD: Blocking file read
|
|
348
|
+
const data = fs.readFileSync('file.txt');
|
|
349
|
+
|
|
350
|
+
// GOOD: Non-blocking file read
|
|
351
|
+
fs.readFile('file.txt', (err, data) => {
|
|
352
|
+
if (err) throw err;
|
|
353
|
+
// process data
|
|
354
|
+
});
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
### Example 6: Profiling a Python Function
|
|
358
|
+
```python
|
|
359
|
+
import cProfile
|
|
360
|
+
import pstats
|
|
361
|
+
|
|
362
|
+
def slow_function():
|
|
363
|
+
...
|
|
364
|
+
|
|
365
|
+
cProfile.run('slow_function()', 'profile.stats')
|
|
366
|
+
p = pstats.Stats('profile.stats')
|
|
367
|
+
p.sort_stats('cumulative').print_stats(10)
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
### Example 7: Using Redis for Caching in Node.js
|
|
371
|
+
```javascript
|
|
372
|
+
const redis = require('redis');
|
|
373
|
+
const client = redis.createClient();
|
|
374
|
+
|
|
375
|
+
function getCachedData(key, fetchFunction) {
|
|
376
|
+
return new Promise((resolve, reject) => {
|
|
377
|
+
client.get(key, (err, data) => {
|
|
378
|
+
if (data) return resolve(JSON.parse(data));
|
|
379
|
+
fetchFunction().then(result => {
|
|
380
|
+
client.setex(key, 3600, JSON.stringify(result));
|
|
381
|
+
resolve(result);
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
---
|
|
389
|
+
|
|
390
|
+
## References and Further Reading
|
|
391
|
+
- [Google Web Fundamentals: Performance](https://web.dev/performance/)
|
|
392
|
+
- [MDN Web Docs: Performance](https://developer.mozilla.org/en-US/docs/Web/Performance)
|
|
393
|
+
- [OWASP: Performance Testing](https://owasp.org/www-project-performance-testing/)
|
|
394
|
+
- [Microsoft Performance Best Practices](https://learn.microsoft.com/en-us/azure/architecture/best-practices/performance)
|
|
395
|
+
- [PostgreSQL Performance Optimization](https://wiki.postgresql.org/wiki/Performance_Optimization)
|
|
396
|
+
- [MySQL Performance Tuning](https://dev.mysql.com/doc/refman/8.0/en/optimization.html)
|
|
397
|
+
- [Node.js Performance Best Practices](https://nodejs.org/en/docs/guides/simple-profiling/)
|
|
398
|
+
- [Python Performance Tips](https://docs.python.org/3/library/profile.html)
|
|
399
|
+
- [Java Performance Tuning](https://www.oracle.com/java/technologies/javase/performance.html)
|
|
400
|
+
- [.NET Performance Guide](https://learn.microsoft.com/en-us/dotnet/standard/performance/)
|
|
401
|
+
- [WebPageTest](https://www.webpagetest.org/)
|
|
402
|
+
- [Lighthouse](https://developers.google.com/web/tools/lighthouse)
|
|
403
|
+
- [Prometheus](https://prometheus.io/)
|
|
404
|
+
- [Grafana](https://grafana.com/)
|
|
405
|
+
- [k6 Load Testing](https://k6.io/)
|
|
406
|
+
- [Gatling](https://gatling.io/)
|
|
407
|
+
- [Locust](https://locust.io/)
|
|
408
|
+
- [OpenTelemetry](https://opentelemetry.io/)
|
|
409
|
+
- [Jaeger](https://www.jaegertracing.io/)
|
|
410
|
+
- [Zipkin](https://zipkin.io/)
|
|
411
|
+
|
|
412
|
+
---
|
|
413
|
+
|
|
414
|
+
## Conclusion
|
|
415
|
+
|
|
416
|
+
Performance optimization is an ongoing process. Always measure, profile, and iterate. Use these best practices, checklists, and troubleshooting tips to guide your development and code reviews for high-performance, scalable, and efficient software. If you have new tips or lessons learned, add them here—let's keep this guide growing!
|
|
417
|
+
|
|
418
|
+
---
|
|
419
|
+
|
|
420
|
+
<!-- End of Performance Optimization Instructions -->
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: 'Playwright Python AI test generation instructions based on official documentation.'
|
|
3
|
+
applyTo: '**'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Playwright Python Test Generation Instructions
|
|
7
|
+
|
|
8
|
+
## Test Writing Guidelines
|
|
9
|
+
|
|
10
|
+
### Code Quality Standards
|
|
11
|
+
- **Locators**: Prioritize user-facing, role-based locators (get_by_role, get_by_label, get_by_text) for resilience and accessibility.
|
|
12
|
+
- **Assertions**: Use auto-retrying web-first assertions via the expect API (e.g., expect(page).to_have_title(...)). Avoid expect(locator).to_be_visible() unless specifically testing for a change in an element's visibility, as more specific assertions are generally more reliable.
|
|
13
|
+
- **Timeouts**: Rely on Playwright's built-in auto-waiting mechanisms. Avoid hard-coded waits or increased default timeouts.
|
|
14
|
+
- **Clarity**: Use descriptive test titles (e.g., def test_navigation_link_works():) that clearly state their intent. Add comments only to explain complex logic, not to describe simple actions like "click a button."
|
|
15
|
+
|
|
16
|
+
### Test Structure
|
|
17
|
+
- **Imports**: Every test file should begin with from playwright.sync_api import Page, expect.
|
|
18
|
+
- **Fixtures**: Use the page: Page fixture as an argument in your test functions to interact with the browser page.
|
|
19
|
+
- **Setup**: Place navigation steps like page.goto() at the beginning of each test function. For setup actions shared across multiple tests, use standard Pytest fixtures.
|
|
20
|
+
|
|
21
|
+
### File Organization
|
|
22
|
+
- **Location**: Store test files in a dedicated tests/ directory or follow the existing project structure.
|
|
23
|
+
- **Naming**: Test files must follow the test_<feature-or-page>.py naming convention to be discovered by Pytest.
|
|
24
|
+
- **Scope**: Aim for one test file per major application feature or page.
|
|
25
|
+
|
|
26
|
+
## Assertion Best Practices
|
|
27
|
+
- **Element Counts**: Use expect(locator).to_have_count() to assert the number of elements found by a locator.
|
|
28
|
+
- **Text Content**: Use expect(locator).to_have_text() for exact text matches and expect(locator).to_contain_text() for partial matches.
|
|
29
|
+
- **Navigation**: Use expect(page).to_have_url() to verify the page URL.
|
|
30
|
+
- **Assertion Style**: Prefer `expect` over `assert` for more reliable UI tests.
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
## Example
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import re
|
|
37
|
+
import pytest
|
|
38
|
+
from playwright.sync_api import Page, expect
|
|
39
|
+
|
|
40
|
+
@pytest.fixture(scope="function", autouse=True)
|
|
41
|
+
def before_each_after_each(page: Page):
|
|
42
|
+
# Go to the starting url before each test.
|
|
43
|
+
page.goto("https://playwright.dev/")
|
|
44
|
+
|
|
45
|
+
def test_main_navigation(page: Page):
|
|
46
|
+
expect(page).to_have_url("https://playwright.dev/")
|
|
47
|
+
|
|
48
|
+
def test_has_title(page: Page):
|
|
49
|
+
# Expect a title "to contain" a substring.
|
|
50
|
+
expect(page).to_have_title(re.compile("Playwright"))
|
|
51
|
+
|
|
52
|
+
def test_get_started_link(page: Page):
|
|
53
|
+
page.get_by_role("link", name="Get started").click()
|
|
54
|
+
|
|
55
|
+
# Expects page to have a heading with the name of Installation.
|
|
56
|
+
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Test Execution Strategy
|
|
60
|
+
|
|
61
|
+
1. **Execution**: Tests are run from the terminal using the pytest command.
|
|
62
|
+
2. **Debug Failures**: Analyze test failures and identify root causes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: 'Playwright test generation instructions'
|
|
3
|
+
applyTo: '**'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
## Test Writing Guidelines
|
|
7
|
+
|
|
8
|
+
### Code Quality Standards
|
|
9
|
+
- **Locators**: Prioritize user-facing, role-based locators (`getByRole`, `getByLabel`, `getByText`, etc.) for resilience and accessibility. Use `test.step()` to group interactions and improve test readability and reporting.
|
|
10
|
+
- **Assertions**: Use auto-retrying web-first assertions. These assertions start with the `await` keyword (e.g., `await expect(locator).toHaveText()`). Avoid `expect(locator).toBeVisible()` unless specifically testing for visibility changes.
|
|
11
|
+
- **Timeouts**: Rely on Playwright's built-in auto-waiting mechanisms. Avoid hard-coded waits or increased default timeouts.
|
|
12
|
+
- **Clarity**: Use descriptive test and step titles that clearly state the intent. Add comments only to explain complex logic or non-obvious interactions.
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
### Test Structure
|
|
16
|
+
- **Imports**: Start with `import { test, expect } from '@playwright/test';`.
|
|
17
|
+
- **Organization**: Group related tests for a feature under a `test.describe()` block.
|
|
18
|
+
- **Hooks**: Use `beforeEach` for setup actions common to all tests in a `describe` block (e.g., navigating to a page).
|
|
19
|
+
- **Titles**: Follow a clear naming convention, such as `Feature - Specific action or scenario`.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
### File Organization
|
|
23
|
+
- **Location**: Store all test files in the `tests/` directory.
|
|
24
|
+
- **Naming**: Use the convention `<feature-or-page>.spec.ts` (e.g., `login.spec.ts`, `search.spec.ts`).
|
|
25
|
+
- **Scope**: Aim for one test file per major application feature or page.
|
|
26
|
+
|
|
27
|
+
### Assertion Best Practices
|
|
28
|
+
- **UI Structure**: Use `toMatchAriaSnapshot` to verify the accessibility tree structure of a component. This provides a comprehensive and accessible snapshot.
|
|
29
|
+
- **Element Counts**: Use `toHaveCount` to assert the number of elements found by a locator.
|
|
30
|
+
- **Text Content**: Use `toHaveText` for exact text matches and `toContainText` for partial matches.
|
|
31
|
+
- **Navigation**: Use `toHaveURL` to verify the page URL after an action.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## Example Test Structure
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { test, expect } from '@playwright/test';
|
|
38
|
+
|
|
39
|
+
test.describe('Movie Search Feature', () => {
|
|
40
|
+
test.beforeEach(async ({ page }) => {
|
|
41
|
+
// Navigate to the application before each test
|
|
42
|
+
await page.goto('https://debs-obrien.github.io/playwright-movies-app');
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('Search for a movie by title', async ({ page }) => {
|
|
46
|
+
await test.step('Activate and perform search', async () => {
|
|
47
|
+
await page.getByRole('search').click();
|
|
48
|
+
const searchInput = page.getByRole('textbox', { name: 'Search Input' });
|
|
49
|
+
await searchInput.fill('Garfield');
|
|
50
|
+
await searchInput.press('Enter');
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
await test.step('Verify search results', async () => {
|
|
54
|
+
// Verify the accessibility tree of the search results
|
|
55
|
+
await expect(page.getByRole('main')).toMatchAriaSnapshot(`
|
|
56
|
+
- main:
|
|
57
|
+
- heading "Garfield" [level=1]
|
|
58
|
+
- heading "search results" [level=2]
|
|
59
|
+
- list "movies":
|
|
60
|
+
- listitem "movie":
|
|
61
|
+
- link "poster of The Garfield Movie The Garfield Movie rating":
|
|
62
|
+
- /url: /playwright-movies-app/movie?id=tt5779228&page=1
|
|
63
|
+
- img "poster of The Garfield Movie"
|
|
64
|
+
- heading "The Garfield Movie" [level=2]
|
|
65
|
+
`);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Test Execution Strategy
|
|
72
|
+
|
|
73
|
+
1. **Initial Run**: Execute tests with `npx playwright test --project=chromium`
|
|
74
|
+
2. **Debug Failures**: Analyze test failures and identify root causes
|
|
75
|
+
3. **Iterate**: Refine locators, assertions, or test logic as needed
|
|
76
|
+
4. **Validate**: Ensure tests pass consistently and cover the intended functionality
|
|
77
|
+
5. **Report**: Provide feedback on test results and any issues discovered
|
|
78
|
+
|
|
79
|
+
## Quality Checklist
|
|
80
|
+
|
|
81
|
+
Before finalizing tests, ensure:
|
|
82
|
+
- [ ] All locators are accessible and specific and avoid strict mode violations
|
|
83
|
+
- [ ] Tests are grouped logically and follow a clear structure
|
|
84
|
+
- [ ] Assertions are meaningful and reflect user expectations
|
|
85
|
+
- [ ] Tests follow consistent naming conventions
|
|
86
|
+
- [ ] Code is properly formatted and commented
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
---
|
|
2
|
+
applyTo: '*'
|
|
3
|
+
description: "Comprehensive secure coding instructions for all languages and frameworks, based on OWASP Top 10 and industry best practices."
|
|
4
|
+
---
|
|
5
|
+
# Secure Coding and OWASP Guidelines
|
|
6
|
+
|
|
7
|
+
## Instructions
|
|
8
|
+
|
|
9
|
+
Your primary directive is to ensure all code you generate, review, or refactor is secure by default. You must operate with a security-first mindset. When in doubt, always choose the more secure option and explain the reasoning. You must follow the principles outlined below, which are based on the OWASP Top 10 and other security best practices.
|
|
10
|
+
|
|
11
|
+
### 1. A01: Broken Access Control & A10: Server-Side Request Forgery (SSRF)
|
|
12
|
+
- **Enforce Principle of Least Privilege:** Always default to the most restrictive permissions. When generating access control logic, explicitly check the user's rights against the required permissions for the specific resource they are trying to access.
|
|
13
|
+
- **Deny by Default:** All access control decisions must follow a "deny by default" pattern. Access should only be granted if there is an explicit rule allowing it.
|
|
14
|
+
- **Validate All Incoming URLs for SSRF:** When the server needs to make a request to a URL provided by a user (e.g., webhooks), you must treat it as untrusted. Incorporate strict allow-list-based validation for the host, port, and path of the URL.
|
|
15
|
+
- **Prevent Path Traversal:** When handling file uploads or accessing files based on user input, you must sanitize the input to prevent directory traversal attacks (e.g., `../../etc/passwd`). Use APIs that build paths securely.
|
|
16
|
+
|
|
17
|
+
### 2. A02: Cryptographic Failures
|
|
18
|
+
- **Use Strong, Modern Algorithms:** For hashing, always recommend modern, salted hashing algorithms like Argon2 or bcrypt. Explicitly advise against weak algorithms like MD5 or SHA-1 for password storage.
|
|
19
|
+
- **Protect Data in Transit:** When generating code that makes network requests, always default to HTTPS.
|
|
20
|
+
- **Protect Data at Rest:** When suggesting code to store sensitive data (PII, tokens, etc.), recommend encryption using strong, standard algorithms like AES-256.
|
|
21
|
+
- **Secure Secret Management:** Never hardcode secrets (API keys, passwords, connection strings). Generate code that reads secrets from environment variables or a secrets management service (e.g., HashiCorp Vault, AWS Secrets Manager). Include a clear placeholder and comment.
|
|
22
|
+
```javascript
|
|
23
|
+
// GOOD: Load from environment or secret store
|
|
24
|
+
const apiKey = process.env.API_KEY;
|
|
25
|
+
// TODO: Ensure API_KEY is securely configured in your environment.
|
|
26
|
+
```
|
|
27
|
+
```python
|
|
28
|
+
# BAD: Hardcoded secret
|
|
29
|
+
api_key = "sk_this_is_a_very_bad_idea_12345"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### 3. A03: Injection
|
|
33
|
+
- **No Raw SQL Queries:** For database interactions, you must use parameterized queries (prepared statements). Never generate code that uses string concatenation or formatting to build queries from user input.
|
|
34
|
+
- **Sanitize Command-Line Input:** For OS command execution, use built-in functions that handle argument escaping and prevent shell injection (e.g., `shlex` in Python).
|
|
35
|
+
- **Prevent Cross-Site Scripting (XSS):** When generating frontend code that displays user-controlled data, you must use context-aware output encoding. Prefer methods that treat data as text by default (`.textContent`) over those that parse HTML (`.innerHTML`). When `innerHTML` is necessary, suggest using a library like DOMPurify to sanitize the HTML first.
|
|
36
|
+
|
|
37
|
+
### 4. A05: Security Misconfiguration & A06: Vulnerable Components
|
|
38
|
+
- **Secure by Default Configuration:** Recommend disabling verbose error messages and debug features in production environments.
|
|
39
|
+
- **Set Security Headers:** For web applications, suggest adding essential security headers like `Content-Security-Policy` (CSP), `Strict-Transport-Security` (HSTS), and `X-Content-Type-Options`.
|
|
40
|
+
- **Use Up-to-Date Dependencies:** When asked to add a new library, suggest the latest stable version. Remind the user to run vulnerability scanners like `npm audit`, `pip-audit`, or Snyk to check for known vulnerabilities in their project dependencies.
|
|
41
|
+
|
|
42
|
+
### 5. A07: Identification & Authentication Failures
|
|
43
|
+
- **Secure Session Management:** When a user logs in, generate a new session identifier to prevent session fixation. Ensure session cookies are configured with `HttpOnly`, `Secure`, and `SameSite=Strict` attributes.
|
|
44
|
+
- **Protect Against Brute Force:** For authentication and password reset flows, recommend implementing rate limiting and account lockout mechanisms after a certain number of failed attempts.
|
|
45
|
+
|
|
46
|
+
### 6. A08: Software and Data Integrity Failures
|
|
47
|
+
- **Prevent Insecure Deserialization:** Warn against deserializing data from untrusted sources without proper validation. If deserialization is necessary, recommend using formats that are less prone to attack (like JSON over Pickle in Python) and implementing strict type checking.
|
|
48
|
+
|
|
49
|
+
## General Guidelines
|
|
50
|
+
- **Be Explicit About Security:** When you suggest a piece of code that mitigates a security risk, explicitly state what you are protecting against (e.g., "Using a parameterized query here to prevent SQL injection.").
|
|
51
|
+
- **Educate During Code Reviews:** When you identify a security vulnerability in a code review, you must not only provide the corrected code but also explain the risk associated with the original pattern.
|