
Claude Skills by HoangNguyen0403
github.com/HoangNguyen0403For a Swift package, add the dependency in `Package.swift` and declare it on the target that imports it: ```swift let package = Package( name: "MyApp", products: [.library(name: "MyApp", targets: ["MyApp"])], dependencies: [ .package(url: "https://github.com/example/Logging.git", from: "1.2.0") ], targets: [ .target( name: "MyApp", dependencies: [.product(name: "Logging", package: "Logging")] ) ] ) ``` Use semantic version requirements, keep products and targets explicit, and run `swift packa...
Add a `.swiftlint.yml` file at the project root and configure the rules intentionally: ```yaml disabled_rules: - line_length opt_in_rules: - empty_count ``` Run SwiftLint locally and in CI, and treat compiler warnings as errors in CI. Prefer fixing the underlying violation over scattering `// swiftlint:disable` comments. Keep configuration versioned with the project so every developer and build uses the same quality rules.
Wrap development-only code in `#if DEBUG` and close it with `#endif`: ```swift let endpoint: URL guard let debugEndpoint = URL(string: "http://localhost:8080") else { fatalError("Invalid debug endpoint") } endpoint = debugEndpoint guard let productionEndpoint = URL(string: "https://api.example.com") else { fatalError("Invalid production endpoint") } endpoint = productionEndpoint ``` Use build configurations or `.xcconfig` files for environment-specific values rather than hardcoding secrets. K...
Write public API documentation with triple-slash comments so DocC can use it: ```swift /// Loads a user from the configured service. /// /// - Returns: The decoded user. /// - Throws: `NetworkError` when the request or response is invalid. public func loadUser() async throws -> User { ... } ``` Use clear summaries, parameter and return descriptions, and typed `- Throws:` documentation. DocC-compatible comments belong on public declarations, and the generated documentation should be built as p...
Use ES modules and named exports consistently. Replace each `require()` with a static import, use `import type` for type-only dependencies, and give exported functions explicit return types: ```ts // user-service.ts import type { UserRepository } from "./user-repository.js"; export interface User { readonly id: string; } export function getUser(repository: UserRepository, id: string): User { return repository.getById(id); } ``` ```ts // consumer.ts import { getUser } from "./user-service.js";...
Use a top-level async function with an explicit return type and `Promise.all()` so independent requests run concurrently. Check HTTP failures and narrow caught errors as `unknown`: ```ts interface User { readonly id: string; } interface Report { readonly total: number; } async function fetchJson<T>(url: string): Promise<T> { const response = await fetch(url); if (!response.ok) { throw new Error(`Request failed: ${response.status} ${url}`); } return (await response.json()) as T; } export async...
Prefer composition and constructor injection when the base class is becoming large. Split each capability behind a small interface and make collaborators explicit: ```ts export interface UserRepository { findById(id: string): Promise<User | null>; } export interface AuditLogger { record(event: string): Promise<void>; } export interface User { readonly id: string; } export class UserService { public constructor( private readonly repository: UserRepository, private readonly auditLogger: AuditLo...
Prefer a literal union or a const object for application roles instead of a runtime `enum`. This keeps the allowed values available to TypeScript without emitting enum JavaScript: ```ts export const USER_ROLES = ["admin", "editor", "viewer"] as const; export type UserRole = (typeof USER_ROLES)[number]; export interface User { readonly role: UserRole; } export function canManageUsers(role: UserRole): boolean { return role === "admin"; } ``` If roles arrive from a request or database, validate ...
Model the event catalog as a map from event names to payloads, then derive both the event name and payload types from that map. A discriminant or distinct key prevents mismatched payloads: ```ts type EventMap = { userCreated: { readonly userId: string }; invoicePaid: { readonly invoiceId: string; readonly amountCents: number }; }; type EventName = keyof EventMap; type Listener<K extends EventName> = (payload: EventMap[K]) => void; export class EventBus { private readonly listeners: { [K in Ev...
Use a branded type so a validated ID is not interchangeable with an arbitrary string: ```ts export type UserId = string & { readonly __brand: "UserId" }; export function parseUserId(value: string): UserId { if (!/^usr_[a-zA-Z0-9]+$/.test(value)) { throw new Error("Invalid user ID"); } return value as UserId; } export function loadUser(id: UserId): Promise<User> { return repository.findById(id); } ``` Only the parser (or a schema validator at the input boundary) should create the brand. The `l...
Validate the request at the Express boundary with a Zod schema and return structured errors before using the data: ```ts import { z } from "zod"; import type { RequestHandler } from "express"; const registrationSchema = z.object({ email: z.string().email(), password: z.string().min(12).max(128), }); type RegistrationInput = z.infer<typeof registrationSchema>; export const register: RequestHandler = async (req, res, next) => { const result = registrationSchema.safeParse(req.body); if (!result....
Store the JWT signing secret outside source control: use the deployment platform's secret manager in production, and an uncommitted `.env` file supplied through the environment for local development. Never put it in frontend code, a checked-in config file, or a JWT payload. ```ts const jwtSecret = process.env.JWT_SECRET; if (!jwtSecret) { throw new Error("JWT_SECRET is not configured"); } ``` Load it once during startup, restrict access to the service, rotate it through the secret manager, an...
String concatenation with user input is SQL injection-prone. Validate the input at the request boundary and pass values separately through a parameterized query or a type-safe ORM: ```ts const query = z.object({ email: z.string().email() }); const parsed = query.safeParse(req.query); if (!parsed.success) { res.status(400).json({ error: "invalid_request" }); return; } const result = await pool.query<UserRow>( "SELECT id, email FROM users WHERE email = $1", [parsed.data.email], ); ``` Do not in...
The original `execSync` call is vulnerable because an environment value is interpolated into a shell command. Treat the value as untrusted, validate it against the refs permitted by CI, and use `execFileSync` with an argument array and no shell: ```ts import { execFileSync } from "node:child_process"; const baseRef = process.env.GITHUB_BASE_REF; if (!baseRef || !/^[A-Za-z0-9._/-]+$/.test(baseRef) || baseRef.includes("..")) { throw new Error("Invalid GITHUB_BASE_REF"); } const output = execFil...
Do not fetch `process.env.API_URL` until it has been parsed and checked against an explicit allow-list. Environment configuration is not automatically trusted, and unrestricted URLs create an SSRF risk: ```ts const rawApiUrl = process.env.API_URL; if (!rawApiUrl) { throw new Error("API_URL is required"); } const apiUrl = new URL(rawApiUrl); const allowedOrigins = new Set(["https://api.example.com"]); if (apiUrl.protocol !== "https:" || !allowedOrigins.has(apiUrl.origin)) { throw new Error("AP...
For a new project, enable strict checking and the additional options that catch unsafe indexing, optional-property mistakes, unused code, and module inconsistencies: ```json { "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noUnusedLocals": true, "noUnusedParameters": true, "forceConsistent...
Use ESLint with the TypeScript parser and recommended type-aware rules, and keep compiler checking as a separate CI step. With flat config: ```js // eslint.config.mjs import eslint from "@eslint/js"; import tseslint from "typescript-eslint"; export default tseslint.config( eslint.configs.recommended, ...tseslint.configs.recommendedTypeChecked, { files: ["**/*.ts", "**/*.tsx"], languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname, }, }, rules: { "@type...
Do not use `@ts-ignore`: it hides an error unconditionally and does not fail when the underlying error disappears. First inspect the diagnostic and fix the type, narrowing, generic constraint, or API declaration causing it. For example: ```ts function formatId(value: string | undefined): string { if (value === undefined) { throw new Error("id is required"); } return value; } ``` If a genuine, unavoidable third-party typing defect remains, use `@ts-expect-error` on the smallest line with a com...
Apply SAP HANA database standards for SQL parameterization, in-memory engine optimization, dynamic IN query chunking, column aliasing on joins, and datatype casting. Use when writing SQL for SAP HANA, optimizing HANA queries, or diagnosing HANA driver errors.
Plan additive, zero-downtime schema migrations with rollout, backfill, and rollback awareness. Use when renaming columns, backfilling data, or shipping risky database changes.
Diagnose database latency with explain plans, index ownership, and query-shape review. Use when a query is slow, an index is missing, or scans and N+1 patterns appear.
Design relational or document schemas from access patterns, cardinality, and lifecycle. Use when modeling entities, choosing embed vs normalize, or shaping schema boundaries before implementation.
Define transaction boundaries, locking, and consistency guarantees for multi-step writes. Use when designing atomic operations, retries, idempotency, or concurrent write behavior.
Implement route configuration, go_router/deep linking, and named routes in Flutter. Use for route declarations, route guards, and URL-to-screen mapping; defer transition-only animation, state-transfer/BLoC questions, auto_route-specific setup, and generic app-bar controls.
Structure Python backends with explicit dependency direction, ports/adapters, and runtime boundaries. Use when shaping project layout, clean architecture, service boundaries, dependency injection, report rendering boundaries, or transport separation in Python.
Write correct async Python runtime code with explicit blocking-I/O boundaries, cancellation, and timeout handling. Use when editing `asyncio` workflows, background loops, async services, or mixed sync/async integrations.
Write maintainable Python with small functions, explicit boundaries, guard clauses, and readable state flow. Use when refactoring Python services, helpers, modules, or async logic for clarity—not generic test writing, tooling setup, or database transaction implementation.
Implement Python database access with parameterized SQL, transaction scope, connection helpers, and repository seams. Use when editing Postgres queries, repositories, transactions, pooling, or persistence boundaries in Python.
Design Python error paths with narrow exceptions, rollback, contextual logs, and preserved blocker truth. Use when handling retries, verifier outcomes, parser failures, or exception flow in Python services.
Core Python 3.11+ language standards for typing, dataclasses, imports, pathlib, and stdlib-first code. Use for idiomatic language constructs in Python modules or stubs; defer pytest fixtures, database/client configuration, subprocess security, and other specialized concerns.
Secure Python services against secret leakage, injection, unsafe subprocess calls, and dependency drift. Use when handling env vars, tokens, SQL, file paths, shell commands, auth flows, or Python security gates.
Test Python services with pytest, async coverage, monkeypatch, and boundary-focused fakes. Use when writing Python tests, fixtures, async tests, regression tests, or dependency-isolated verification.
Configure Python tooling, dependency surfaces, static analysis, and verification gates. Use when editing `pyproject.toml`, `requirements.txt`, `pytest.ini`, `ruff`, `pyright`, CI, or Python release checks.
Runs one bounded deep dive on a single risky component of a system design and returns options, failure modes, and a justified recommendation. Use during a design session when a component needs expert depth beyond the main thread's budget.