[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F02Z5TP4WA2PHX5RB3Q2WH":3,"skill-same:01M7F02Z5TP4WA2PHX5RB3Q2WH":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":33,"repositoryHtmlUrl":34,"repositoryHomepageUrl":6,"ownerHtmlUrl":35,"ownerBlogUrl":6,"ownerDescription":36,"updatedAt":37,"install":38,"resources":51},"01M7F02Z5TP4WA2PHX5RB3Q2WH","frontend-data-contracts",null,"A portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F05-技能与代理开发\u002Ffrontend-data-contracts\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: frontend-data-contracts\ndescription: \"A portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app.\"\nrisk: critical\nsource: https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Ftree\u002Fmain\u002Fskills\u002Ffrontend-data-contracts\nsource_repo: stareezy-1\u002Ffrontend-architecture-skill\nsource_type: community\ndate_added: 2026-07-01\nlicense: MIT\nlicense_source: https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Fblob\u002Fmain\u002FLICENSE\n---\n\n# Frontend Data Contracts (typed network boundary)\n## When to Use\n\nUse this skill when you need a portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app. Establishes one typed API client as the single fetch boundary, a parse-don't-validate rule that turns wire JSON into trusted domain types before it enters the app, a single...\n\n\n> Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others.\n> This skill describes a **discipline at the network edge** — one client, one envelope, one error\n> type, validated types — not a state library or a styling system. It pairs with the\n> **frontend-architecture** skill (the client lives in `shared\u002Fapi-client\u002F`) and is the foundation\n> the **frontend-optimistic-mutations** skill builds on.\n\nThe goal: the moment data crosses from the network into the app, it stops being `any`-shaped wire\nJSON and becomes a **trusted, typed domain value** — or it becomes a **single, typed error**.\nThere is exactly one place this transformation happens, and nothing untyped escapes it.\n\n---\n\n## 0. The five core ideas\n\n1. **One client is the only fetch boundary.** A single typed `apiClient` wraps `fetch`. Components and hooks never call `fetch`\u002F`axios` directly — the boundary is enforceable in review and lint.\n2. **Parse, don't validate.** Wire JSON is parsed into domain types at the boundary. After the client returns, the value is trusted everywhere downstream — no defensive `?.` chains, no re-checking shapes in components.\n3. **One envelope.** Every response is `{ data }` on success or `{ error }` on failure. The client unwraps `data` and throws on `error`, so callers receive the payload directly or a typed throw.\n4. **One normalized error type.** Server error envelope, non-2xx status, malformed body, network failure, and abort all become a single `ApiError` with a machine code, status, and optional per-field errors. Callers handle one shape.\n5. **Identifiers are branded.** Domain IDs are nominal types (`InvoiceId`, `CustomerId`) so the compiler rejects passing one where another is expected — the most common silent bug in data-heavy UIs.\n\n---\n\n## 1. Directory layout\n\nThe boundary is one folder in `shared\u002F` (per the frontend-architecture skill).\n\n```\nsrc\u002Fshared\u002Fapi-client\u002F\n├── index.ts        ← barrel: apiClient, ApiError, types\n├── client.ts       ← the fetch wrapper: buildUrl, headers, parse, verbs\n├── config.ts       ← base URL resolution, default headers\n├── error.ts        ← the ApiError class + code→message-key mapping\n├── types.ts        ← envelope types, HttpMethod, RequestOptions, field errors\n└── client.test.ts  ← boundary behavior tests (envelope, errors, network)\n```\n\nDomain entity types and their **schemas** live with their feature module\n(`modules\u002F{feature}\u002Ftypes\u002F`) or a shared contract package; the client is generic over `T`.\n\n---\n\n## 2. One client, the only fetch boundary\n\nEvery verb returns the **unwrapped** `data` payload typed by the caller, and **throws** an\n`ApiError` on any failure. Components never see envelopes or raw responses.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Fclient.ts (essence)\nexport const apiClient = {\n  get\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"GET\", path, undefined, options);\n  },\n  post\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"POST\", path, body, options);\n  },\n  patch\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  put\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  delete\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n} as const;\n\nexport type ApiClient = typeof apiClient;\n```\n\n```ts\n\u002F\u002F CORRECT — a feature hook wraps the client, typed by the caller\nconst invoice = await apiClient.get\u003CInvoice>(`\u002Finvoices\u002F${id}`, { signal });\n\n\u002F\u002F WRONG — a raw fetch in a component bypasses the boundary entirely\nconst res = await fetch(`\u002Fapi\u002Finvoices\u002F${id}`); \u002F\u002F untyped, unhandled errors, no envelope\n```\n\n**Hard rules:**\n\n- No `fetch`\u002F`axios`\u002F`XMLHttpRequest` outside `shared\u002Fapi-client\u002F` — enforce with an ESLint `no-restricted-imports`\u002F`no-restricted-globals` rule.\n- The client is **framework-free**: no toasts, no router, no React. Side effects (toasts, redirects) live in the query layer's `onError` (see §6).\n- Pass `AbortSignal` through `RequestOptions` so the query layer can cancel (wired by TanStack Query).\n\n---\n\n## 3. Parse, don't validate (the boundary transform)\n\n\"Validate\" leaves you with the same untyped value and a boolean. \"Parse\" returns a **new, typed\nvalue** — so downstream code is guaranteed correct by the type system. Run a schema parse at the\nboundary; after that, the value is trusted.\n\n```ts\n\u002F\u002F modules\u002Finvoice\u002Ftypes\u002Finvoice.schema.ts\nimport { z } from \"zod\";\n\nexport const invoiceSchema = z.object({\n  id: z.string().transform(toInvoiceId), \u002F\u002F brand it (see §5)\n  number: z.string(),\n  status: z.nativeEnum(InvoiceStatus),\n  total: z.number().int(), \u002F\u002F minor units — never float money\n  issuedAt: z.string().datetime(),\n});\nexport type Invoice = z.infer\u003Ctypeof invoiceSchema>;\n```\n\n```ts\n\u002F\u002F the client (or a thin per-entity wrapper) parses at the edge\nconst raw = await apiClient.get\u003Cunknown>(`\u002Finvoices\u002F${id}`, { signal });\nreturn invoiceSchema.parse(raw); \u002F\u002F throws on contract drift → surfaces as a typed failure\n```\n\n**Why this matters:** a backend that renames a field or sends a `null` it shouldn't is caught **at\nthe boundary**, with a clear error, instead of producing `undefined` three components deep where\nthe stack trace is useless. Components downstream never write `invoice?.total ?? 0` defensively.\n\n> Validation library is your choice — **Zod**, **Valibot**, **ArkType**, **io-ts**. The rule is\n> constant: a parse step converts `unknown` wire data into a typed domain value at one boundary.\n\n---\n\n## 4. One response envelope\n\nMirror the backend's single envelope in the client and unwrap it once.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ftypes.ts\nexport interface ApiSuccessEnvelope\u003CT> {\n  data: T;\n}\nexport interface ApiErrorEnvelope {\n  error: ApiErrorBody;\n}\nexport type ApiEnvelope\u003CT> = ApiSuccessEnvelope\u003CT> | ApiErrorEnvelope;\n\nexport function isApiErrorEnvelope\u003CT>(\n  e: ApiEnvelope\u003CT>,\n): e is ApiErrorEnvelope {\n  return typeof e === \"object\" && e !== null && \"error\" in e;\n}\n\nexport interface ApiErrorBody {\n  code: ServerErrorCode; \u002F\u002F machine-readable, stable\n  message: string; \u002F\u002F server message (NOT shown to users directly)\n  fields?: Record\u003Cstring, string[]>; \u002F\u002F per-field validation errors\n}\n```\n\nThe parse step handles every shape: `204 No Content` → `undefined`; `{ error }` → throw; non-2xx\nwith no well-formed envelope → synthesize an error; `{ data }` → return `data`. The caller only\never sees a typed payload or a throw.\n\n---\n\n## 5. Branded (nominal) identifiers\n\nStrings are interchangeable; domain IDs are not. Brand them so the compiler stops you passing a\n`CustomerId` where an `InvoiceId` is required.\n\n```ts\n\u002F\u002F shared\u002Ftypes\u002Fid.ts\ndeclare const brand: unique symbol;\nexport type Brand\u003CT, B extends string> = T & { readonly [brand]: B };\n\nexport type InvoiceId = Brand\u003Cstring, \"InvoiceId\">;\nexport type CustomerId = Brand\u003Cstring, \"CustomerId\">;\n\nexport const toInvoiceId = (s: string): InvoiceId => s as InvoiceId;\nexport const toCustomerId = (s: string): CustomerId => s as CustomerId;\n```\n\n```ts\nfunction loadInvoice(id: InvoiceId) {\n  \u002F* … *\u002F\n}\nloadInvoice(customerId); \u002F\u002F ❌ compile error — exactly the bug you want caught\nloadInvoice(invoiceId); \u002F\u002F ✅\n```\n\nBrand IDs at the parse boundary (§3) so every ID in the app is already nominal. The runtime cost is\nzero — brands erase at compile time.\n\n---\n\n## 6. One normalized error type\n\nCollapse every failure mode into a single `ApiError` so callers handle one shape. It carries a\nmachine `code`, the HTTP `status`, optional per-field errors, and a stable key for localized\nmessages (it does **not** localize — that's the UI's job).\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ferror.ts (essence)\nexport class ApiError extends Error {\n  readonly code: ServerErrorCode;\n  readonly status: number; \u002F\u002F 0 when no response (network\u002Fabort)\n  readonly fields?: Record\u003Cstring, string[]>;\n\n  get isNetworkError() {\n    return this.status === 0;\n  }\n  get hasFieldErrors() {\n    return !!this.fields && Object.keys(this.fields).length > 0;\n  }\n  \u002F** Stable key under an `errors` i18n namespace — never a raw server string. *\u002F\n  get messageKey() {\n    if (this.isNetworkError) return \"network\";\n    return ERROR_CODE_MESSAGE_KEYS[this.code] ?? \"generic\";\n  }\n\n  static fromEnvelope(body: ApiErrorBody, status: number) {\n    \u002F* server { error } *\u002F\n  }\n  static fromNetwork(cause: unknown) {\n    \u002F* offline \u002F CORS \u002F abort → status 0 *\u002F\n  }\n}\n```\n\n### 6.1 Where side effects live\n\nThe client throws; the **query layer** decides what the user sees. Keep toasts\u002Fredirects out of the\nclient.\n\n```ts\n\u002F\u002F a TanStack Query mutation maps the typed error to a localized toast\nuseMutation({\n  mutationFn: (input) => apiClient.post\u003CInvoice>(\"\u002Finvoices\", input),\n  onError: (error: ApiError) => notifyError(error), \u002F\u002F looks up error.messageKey in i18n\n});\n```\n\n### 6.2 Per-field errors → form fields\n\nServer validation (`fields`) maps straight onto form-field errors — one place, typed.\n\n```ts\nif (error.hasFieldErrors) {\n  for (const [field, messages] of Object.entries(error.fields!)) {\n    form.setError(field as Path\u003CFormValues>, { message: messages[0] });\n  }\n}\n```\n\n**Hard rules:**\n\n- Never `throw new Error(string)` from the data layer — always `ApiError` with a `code`.\n- Never show `error.message` (a server\u002Fdev string) directly to users — resolve `messageKey` through i18n.\n- A 2xx with an unparseable body is a **contract violation** → throw `INVALID_RESPONSE`, don't silently return `undefined`.\n\n---\n\n## 7. Library adapters\n\nThe discipline is constant; the data-fetching library only changes where `onError`\u002Fparsing hangs.\n\n| Library                    | Where the client is called                                                | Where `ApiError` is handled                                                      |\n| -------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |\n| **TanStack Query**         | `queryFn`\u002F`mutationFn` call `apiClient.*`                                 | `onError` per query\u002Fmutation, or a global `QueryCache`\u002F`MutationCache` `onError` |\n| **RTK Query**              | `baseQuery` wraps `apiClient`, parses + returns `{ data }` or `{ error }` | `transformErrorResponse` → `ApiError`; handle in component or middleware         |\n| **SWR**                    | `fetcher = (key) => apiClient.get(key)`                                   | `onError` in `SWRConfig` or per-hook                                             |\n| **Plain fetch hooks (RN)** | a `useAsync` wrapper calls `apiClient.*`                                  | try\u002Fcatch sets a typed error state                                               |\n\nFor **React Native**, the client is unchanged — `fetch` and `AbortController` exist in RN. Only\n`credentials: \"include\"` (cookie auth) may need swapping for a token header depending on your auth.\n\n---\n\n## 8. Conventions checklist (enforce in review)\n\n- [ ] Exactly one `apiClient` in `shared\u002Fapi-client\u002F`; no `fetch`\u002F`axios` anywhere else (lint-enforced).\n- [ ] The client is framework-free — no toasts, router, or React inside it.\n- [ ] Responses are parsed into typed domain values at the boundary (parse, don't validate).\n- [ ] One `{ data } \u002F { error }` envelope, unwrapped once in the client.\n- [ ] Every failure becomes one `ApiError` (code + status + optional fields); no bare `throw new Error`.\n- [ ] Domain IDs are branded; IDs are branded at the parse boundary.\n- [ ] `error.messageKey` resolves through i18n — server `message` is never shown to users.\n- [ ] Per-field server errors map onto form fields via the typed `fields` map.\n- [ ] `AbortSignal` flows through `RequestOptions` for cancellation.\n- [ ] A 2xx with a malformed body throws a contract-violation error, not `undefined`.\n\n---\n\n## 9. How to apply this skill\n\n**Adding the boundary to a project:** create `shared\u002Fapi-client\u002F` with `client.ts`, `error.ts`,\n`types.ts`, `config.ts`. Add the lint rule banning `fetch`\u002F`axios` elsewhere. Define your envelope\nto match the backend, and your `ApiError` codes.\n\n**Adding a new entity:** define its schema (Zod\u002FValibot) and `z.infer` type in the feature module,\nbrand its ID at parse time, and wrap `apiClient` in typed query\u002Fmutation hooks — never call the\nclient from a component.\n\n**Debugging \"undefined three components deep\":** add\u002Frepair the boundary parse so contract drift\nfails loudly at the edge with a typed error, instead of leaking `undefined` downstream.\n\n**Reviewing the data layer:** run the checklist in §8. The highest-value catches are raw `fetch` in\ncomponents (boundary bypass) and `throw new Error(string)` from the data layer (untyped failures).\n\n---\n\n## Publishing \u002F installing this skill\n\nThis skill follows the Anthropic `SKILL.md` format and is portable across agents.\n\n1. Keep it under `skills\u002Ffrontend-data-contracts\u002FSKILL.md` in a public GitHub repo.\n2. Keep the frontmatter `name` and high-signal `description` — discovery indexes match against it.\n3. Install with: `npx skills add \u003Corg>\u002F\u003Crepo> --skill \"frontend-data-contracts\"`.\n4. Non-`SKILL.md` agents can be pointed here from `AGENTS.md` \u002F `CLAUDE.md`; Kiro can mirror it as a steering file.\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n","# Frontend Data Contracts (typed network boundary)\n## When to Use\n\nUse this skill when you need a portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app. Establishes one typed API client as the single fetch boundary, a parse-don't-validate rule that turns wire JSON into trusted domain types before it enters the app, a single...\n\n\n> Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others.\n> This skill describes a **discipline at the network edge** — one client, one envelope, one error\n> type, validated types — not a state library or a styling system. It pairs with the\n> **frontend-architecture** skill (the client lives in `shared\u002Fapi-client\u002F`) and is the foundation\n> the **frontend-optimistic-mutations** skill builds on.\n\nThe goal: the moment data crosses from the network into the app, it stops being `any`-shaped wire\nJSON and becomes a **trusted, typed domain value** — or it becomes a **single, typed error**.\nThere is exactly one place this transformation happens, and nothing untyped escapes it.\n\n---\n\n## 0. The five core ideas\n\n1. **One client is the only fetch boundary.** A single typed `apiClient` wraps `fetch`. Components and hooks never call `fetch`\u002F`axios` directly — the boundary is enforceable in review and lint.\n2. **Parse, don't validate.** Wire JSON is parsed into domain types at the boundary. After the client returns, the value is trusted everywhere downstream — no defensive `?.` chains, no re-checking shapes in components.\n3. **One envelope.** Every response is `{ data }` on success or `{ error }` on failure. The client unwraps `data` and throws on `error`, so callers receive the payload directly or a typed throw.\n4. **One normalized error type.** Server error envelope, non-2xx status, malformed body, network failure, and abort all become a single `ApiError` with a machine code, status, and optional per-field errors. Callers handle one shape.\n5. **Identifiers are branded.** Domain IDs are nominal types (`InvoiceId`, `CustomerId`) so the compiler rejects passing one where another is expected — the most common silent bug in data-heavy UIs.\n\n---\n\n## 1. Directory layout\n\nThe boundary is one folder in `shared\u002F` (per the frontend-architecture skill).\n\n```\nsrc\u002Fshared\u002Fapi-client\u002F\n├── index.ts        ← barrel: apiClient, ApiError, types\n├── client.ts       ← the fetch wrapper: buildUrl, headers, parse, verbs\n├── config.ts       ← base URL resolution, default headers\n├── error.ts        ← the ApiError class + code→message-key mapping\n├── types.ts        ← envelope types, HttpMethod, RequestOptions, field errors\n└── client.test.ts  ← boundary behavior tests (envelope, errors, network)\n```\n\nDomain entity types and their **schemas** live with their feature module\n(`modules\u002F{feature}\u002Ftypes\u002F`) or a shared contract package; the client is generic over `T`.\n\n---\n\n## 2. One client, the only fetch boundary\n\nEvery verb returns the **unwrapped** `data` payload typed by the caller, and **throws** an\n`ApiError` on any failure. Components never see envelopes or raw responses.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Fclient.ts (essence)\nexport const apiClient = {\n  get\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"GET\", path, undefined, options);\n  },\n  post\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"POST\", path, body, options);\n  },\n  patch\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  put\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  delete\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n} as const;\n\nexport type ApiClient = typeof apiClient;\n```\n\n```ts\n\u002F\u002F CORRECT — a feature hook wraps the client, typed by the caller\nconst invoice = await apiClient.get\u003CInvoice>(`\u002Finvoices\u002F${id}`, { signal });\n\n\u002F\u002F WRONG — a raw fetch in a component bypasses the boundary entirely\nconst res = await fetch(`\u002Fapi\u002Finvoices\u002F${id}`); \u002F\u002F untyped, unhandled errors, no envelope\n```\n\n**Hard rules:**\n\n- No `fetch`\u002F`axios`\u002F`XMLHttpRequest` outside `shared\u002Fapi-client\u002F` — enforce with an ESLint `no-restricted-imports`\u002F`no-restricted-globals` rule.\n- The client is **framework-free**: no toasts, no router, no React. Side effects (toasts, redirects) live in the query layer's `onError` (see §6).\n- Pass `AbortSignal` through `RequestOptions` so the query layer can cancel (wired by TanStack Query).\n\n---\n\n## 3. Parse, don't validate (the boundary transform)\n\n\"Validate\" leaves you with the same untyped value and a boolean. \"Parse\" returns a **new, typed\nvalue** — so downstream code is guaranteed correct by the type system. Run a schema parse at the\nboundary; after that, the value is trusted.\n\n```ts\n\u002F\u002F modules\u002Finvoice\u002Ftypes\u002Finvoice.schema.ts\nimport { z } from \"zod\";\n\nexport const invoiceSchema = z.object({\n  id: z.string().transform(toInvoiceId), \u002F\u002F brand it (see §5)\n  number: z.string(),\n  status: z.nativeEnum(InvoiceStatus),\n  total: z.number().int(), \u002F\u002F minor units — never float money\n  issuedAt: z.string().datetime(),\n});\nexport type Invoice = z.infer\u003Ctypeof invoiceSchema>;\n```\n\n```ts\n\u002F\u002F the client (or a thin per-entity wrapper) parses at the edge\nconst raw = await apiClient.get\u003Cunknown>(`\u002Finvoices\u002F${id}`, { signal });\nreturn invoiceSchema.parse(raw); \u002F\u002F throws on contract drift → surfaces as a typed failure\n```\n\n**Why this matters:** a backend that renames a field or sends a `null` it shouldn't is caught **at\nthe boundary**, with a clear error, instead of producing `undefined` three components deep where\nthe stack trace is useless. Components downstream never write `invoice?.total ?? 0` defensively.\n\n> Validation library is your choice — **Zod**, **Valibot**, **ArkType**, **io-ts**. The rule is\n> constant: a parse step converts `unknown` wire data into a typed domain value at one boundary.\n\n---\n\n## 4. One response envelope\n\nMirror the backend's single envelope in the client and unwrap it once.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ftypes.ts\nexport interface ApiSuccessEnvelope\u003CT> {\n  data: T;\n}\nexport interface ApiErrorEnvelope {\n  error: ApiErrorBody;\n}\nexport type ApiEnvelope\u003CT> = ApiSuccessEnvelope\u003CT> | ApiErrorEnvelope;\n\nexport function isApiErrorEnvelope\u003CT>(\n  e: ApiEnvelope\u003CT>,\n): e is ApiErrorEnvelope {\n  return typeof e === \"object\" && e !== null && \"error\" in e;\n}\n\nexport interface ApiErrorBody {\n  code: ServerErrorCode; \u002F\u002F machine-readable, stable\n  message: string; \u002F\u002F server message (NOT shown to users directly)\n  fields?: Record\u003Cstring, string[]>; \u002F\u002F per-field validation errors\n}\n```\n\nThe parse step handles every shape: `204 No Content` → `undefined`; `{ error }` → throw; non-2xx\nwith no well-formed envelope → synthesize an error; `{ data }` → return `data`. The caller only\never sees a typed payload or a throw.\n\n---\n\n## 5. Branded (nominal) identifiers\n\nStrings are interchangeable; domain IDs are not. Brand them so the compiler stops you passing a\n`CustomerId` where an `InvoiceId` is required.\n\n```ts\n\u002F\u002F shared\u002Ftypes\u002Fid.ts\ndeclare const brand: unique symbol;\nexport type Brand\u003CT, B extends string> = T & { readonly [brand]: B };\n\nexport type InvoiceId = Brand\u003Cstring, \"InvoiceId\">;\nexport type CustomerId = Brand\u003Cstring, \"CustomerId\">;\n\nexport const toInvoiceId = (s: string): InvoiceId => s as InvoiceId;\nexport const toCustomerId = (s: string): CustomerId => s as CustomerId;\n```\n\n```ts\nfunction loadInvoice(id: InvoiceId) {\n  \u002F* … *\u002F\n}\nloadInvoice(customerId); \u002F\u002F ❌ compile error — exactly the bug you want caught\nloadInvoice(invoiceId); \u002F\u002F ✅\n```\n\nBrand IDs at the parse boundary (§3) so every ID in the app is already nominal. The runtime cost is\nzero — brands erase at compile time.\n\n---\n\n## 6. One normalized error type\n\nCollapse every failure mode into a single `ApiError` so callers handle one shape. It carries a\nmachine `code`, the HTTP `status`, optional per-field errors, and a stable key for localized\nmessages (it does **not** localize — that's the UI's job).\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ferror.ts (essence)\nexport class ApiError extends Error {\n  readonly code: ServerErrorCode;\n  readonly status: number; \u002F\u002F 0 when no response (network\u002Fabort)\n  readonly fields?: Record\u003Cstring, string[]>;\n\n  get isNetworkError() {\n    return this.status === 0;\n  }\n  get hasFieldErrors() {\n    return !!this.fields && Object.keys(this.fields).length > 0;\n  }\n  \u002F** Stable key under an `errors` i18n namespace — never a raw server string. *\u002F\n  get messageKey() {\n    if (this.isNetworkError) return \"network\";\n    return ERROR_CODE_MESSAGE_KEYS[this.code] ?? \"generic\";\n  }\n\n  static fromEnvelope(body: ApiErrorBody, status: number) {\n    \u002F* server { error } *\u002F\n  }\n  static fromNetwork(cause: unknown) {\n    \u002F* offline \u002F CORS \u002F abort → status 0 *\u002F\n  }\n}\n```\n\n### 6.1 Where side effects live\n\nThe client throws; the **query layer** decides what the user sees. Keep toasts\u002Fredirects out of the\nclient.\n\n```ts\n\u002F\u002F a TanStack Query mutation maps the typed error to a localized toast\nuseMutation({\n  mutationFn: (input) => apiClient.post\u003CInvoice>(\"\u002Finvoices\", input),\n  onError: (error: ApiError) => notifyError(error), \u002F\u002F looks up error.messageKey in i18n\n});\n```\n\n### 6.2 Per-field errors → form fields\n\nServer validation (`fields`) maps straight onto form-field errors — one place, typed.\n\n```ts\nif (error.hasFieldErrors) {\n  for (const [field, messages] of Object.entries(error.fields!)) {\n    form.setError(field as Path\u003CFormValues>, { message: messages[0] });\n  }\n}\n```\n\n**Hard rules:**\n\n- Never `throw new Error(string)` from the data layer — always `ApiError` with a `code`.\n- Never show `error.message` (a server\u002Fdev string) directly to users — resolve `messageKey` through i18n.\n- A 2xx with an unparseable body is a **contract violation** → throw `INVALID_RESPONSE`, don't silently return `undefined`.\n\n---\n\n## 7. Library adapters\n\nThe discipline is constant; the data-fetching library only changes where `onError`\u002Fparsing hangs.\n\n| Library                    | Where the client is called                                                | Where `ApiError` is handled                                                      |\n| -------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |\n| **TanStack Query**         | `queryFn`\u002F`mutationFn` call `apiClient.*`                                 | `onError` per query\u002Fmutation, or a global `QueryCache`\u002F`MutationCache` `onError` |\n| **RTK Query**              | `baseQuery` wraps `apiClient`, parses + returns `{ data }` or `{ error }` | `transformErrorResponse` → `ApiError`; handle in component or middleware         |\n| **SWR**                    | `fetcher = (key) => apiClient.get(key)`                                   | `onError` in `SWRConfig` or per-hook                                             |\n| **Plain fetch hooks (RN)** | a `useAsync` wrapper calls `apiClient.*`                                  | try\u002Fcatch sets a typed error state                                               |\n\nFor **React Native**, the client is unchanged — `fetch` and `AbortController` exist in RN. Only\n`credentials: \"include\"` (cookie auth) may need swapping for a token header depending on your auth.\n\n---\n\n## 8. Conventions checklist (enforce in review)\n\n- [ ] Exactly one `apiClient` in `shared\u002Fapi-client\u002F`; no `fetch`\u002F`axios` anywhere else (lint-enforced).\n- [ ] The client is framework-free — no toasts, router, or React inside it.\n- [ ] Responses are parsed into typed domain values at the boundary (parse, don't validate).\n- [ ] One `{ data } \u002F { error }` envelope, unwrapped once in the client.\n- [ ] Every failure becomes one `ApiError` (code + status + optional fields); no bare `throw new Error`.\n- [ ] Domain IDs are branded; IDs are branded at the parse boundary.\n- [ ] `error.messageKey` resolves through i18n — server `message` is never shown to users.\n- [ ] Per-field server errors map onto form fields via the typed `fields` map.\n- [ ] `AbortSignal` flows through `RequestOptions` for cancellation.\n- [ ] A 2xx with a malformed body throws a contract-violation error, not `undefined`.\n\n---\n\n## 9. How to apply this skill\n\n**Adding the boundary to a project:** create `shared\u002Fapi-client\u002F` with `client.ts`, `error.ts`,\n`types.ts`, `config.ts`. Add the lint rule banning `fetch`\u002F`axios` elsewhere. Define your envelope\nto match the backend, and your `ApiError` codes.\n\n**Adding a new entity:** define its schema (Zod\u002FValibot) and `z.infer` type in the feature module,\nbrand its ID at parse time, and wrap `apiClient` in typed query\u002Fmutation hooks — never call the\nclient from a component.\n\n**Debugging \"undefined three components deep\":** add\u002Frepair the boundary parse so contract drift\nfails loudly at the edge with a typed error, instead of leaking `undefined` downstream.\n\n**Reviewing the data layer:** run the checklist in §8. The highest-value catches are raw `fetch` in\ncomponents (boundary bypass) and `throw new Error(string)` from the data layer (untyped failures).\n\n---\n\n## Publishing \u002F installing this skill\n\nThis skill follows the Anthropic `SKILL.md` format and is portable across agents.\n\n1. Keep it under `skills\u002Ffrontend-data-contracts\u002FSKILL.md` in a public GitHub repo.\n2. Keep the frontmatter `name` and high-signal `description` — discovery indexes match against it.\n3. Install with: `npx skills add \u003Corg>\u002F\u003Crepo> --skill \"frontend-data-contracts\"`.\n4. Non-`SKILL.md` agents can be pointed here from `AGENTS.md` \u002F `CLAUDE.md`; Kiro can mirror it as a steering file.\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n",{"name":5,"risk":24,"source":25,"license":15,"date_added":26,"description":7,"source_repo":27,"source_type":28,"license_source":29},"critical","https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Ftree\u002Fmain\u002Fskills\u002Ffrontend-data-contracts",1782864000000,"stareezy-1\u002Ffrontend-architecture-skill","community","https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Fblob\u002Fmain\u002FLICENSE","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","05-技能与代理开发\u002Ffrontend-data-contracts",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill frontend-data-contracts",{"tool":44,"command":45},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill frontend-data-contracts",{"tool":47,"command":48},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill frontend-data-contracts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F05-技能与代理开发\u002Ffrontend-data-contracts\u002FSKILL.md",true,[],[53,60,65,72,79,86],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":61,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]