@fitzzero/quickdraw-core 5.1.2 → 5.1.3

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.
Files changed (124) hide show
  1. package/README.md +793 -57
  2. package/dist/{admin-DWWrT1h6.d.ts → admin-CS7JB_UH.d.ts} +2 -2
  3. package/dist/{adminSchemas-D4bFKsrb.d.ts → adminSchemas-29cGgrg5.d.ts} +1 -1
  4. package/dist/{auth-DXiSJZaf.d.ts → auth-DtdYjrZ9.d.ts} +11 -7
  5. package/dist/{caller-BT-Mv4bD.d.ts → caller-BTwGl7vm.d.ts} +183 -15
  6. package/dist/chunk-2FDSKLBO.js +82 -0
  7. package/dist/chunk-2FDSKLBO.js.map +1 -0
  8. package/dist/{chunk-GSIPUNJL.js → chunk-64I6MYBC.js} +139 -792
  9. package/dist/chunk-64I6MYBC.js.map +1 -0
  10. package/dist/chunk-7473HK24.js +17 -0
  11. package/dist/chunk-7473HK24.js.map +1 -0
  12. package/dist/chunk-7Y5ROPXL.js +33 -0
  13. package/dist/chunk-7Y5ROPXL.js.map +1 -0
  14. package/dist/chunk-A2RBQD66.js +7 -0
  15. package/dist/chunk-A2RBQD66.js.map +1 -0
  16. package/dist/chunk-ASAMUGHG.js +651 -0
  17. package/dist/chunk-ASAMUGHG.js.map +1 -0
  18. package/dist/{chunk-B2P7AZ25.js → chunk-CYE4UBOB.js} +6 -4
  19. package/dist/chunk-CYE4UBOB.js.map +1 -0
  20. package/dist/chunk-DNP65TD5.js +832 -0
  21. package/dist/chunk-DNP65TD5.js.map +1 -0
  22. package/dist/{chunk-5CGO426C.js → chunk-GYLWEJHW.js} +5 -1
  23. package/dist/chunk-GYLWEJHW.js.map +1 -0
  24. package/dist/{chunk-AONAFOYU.js → chunk-I3JCFS7H.js} +25 -13
  25. package/dist/chunk-I3JCFS7H.js.map +1 -0
  26. package/dist/{chunk-X5CWPX7H.js → chunk-IIQ3WMJK.js} +13 -2
  27. package/dist/chunk-IIQ3WMJK.js.map +1 -0
  28. package/dist/{chunk-6K5BY47X.js → chunk-JVTONQFI.js} +1277 -277
  29. package/dist/chunk-JVTONQFI.js.map +1 -0
  30. package/dist/{chunk-RL4VKLBX.js → chunk-KKQANRLG.js} +2 -2
  31. package/dist/{chunk-RL4VKLBX.js.map → chunk-KKQANRLG.js.map} +1 -1
  32. package/dist/{chunk-GKH3LJ7N.js → chunk-MPQAT55F.js} +38 -205
  33. package/dist/chunk-MPQAT55F.js.map +1 -0
  34. package/dist/chunk-NX2V6SIL.js +202 -0
  35. package/dist/chunk-NX2V6SIL.js.map +1 -0
  36. package/dist/{chunk-7QCUX4TK.js → chunk-NZHA4TZD.js} +72 -175
  37. package/dist/chunk-NZHA4TZD.js.map +1 -0
  38. package/dist/{chunk-MBH6IDSM.js → chunk-OCZJ4EYV.js} +40 -17
  39. package/dist/chunk-OCZJ4EYV.js.map +1 -0
  40. package/dist/{chunk-RJ5I2VO3.js → chunk-PHCURHC7.js} +6 -6
  41. package/dist/chunk-PHCURHC7.js.map +1 -0
  42. package/dist/{chunk-4YO5H5ON.js → chunk-Q4OGQM5I.js} +4 -10
  43. package/dist/chunk-Q4OGQM5I.js.map +1 -0
  44. package/dist/chunk-QSU47XEX.js +13 -0
  45. package/dist/chunk-QSU47XEX.js.map +1 -0
  46. package/dist/{chunk-LCC7HNFP.js → chunk-RZXJTDH5.js} +2 -2
  47. package/dist/{chunk-Z2LZ7IZ7.js → chunk-SN3OZVEQ.js} +5 -31
  48. package/dist/chunk-SN3OZVEQ.js.map +1 -0
  49. package/dist/{chunk-Z5ILULF2.js → chunk-SQ5VUG77.js} +4 -3
  50. package/dist/{chunk-Z5ILULF2.js.map → chunk-SQ5VUG77.js.map} +1 -1
  51. package/dist/chunk-STH5DLQP.js +1192 -0
  52. package/dist/chunk-STH5DLQP.js.map +1 -0
  53. package/dist/{chunk-NMXYENH4.js → chunk-VZFJTKIW.js} +6 -6
  54. package/dist/{chunk-753VJIUP.js → chunk-X4ZU4QH5.js} +43 -9
  55. package/dist/chunk-X4ZU4QH5.js.map +1 -0
  56. package/dist/chunk-XD7SRDUY.js +188 -0
  57. package/dist/chunk-XD7SRDUY.js.map +1 -0
  58. package/dist/chunk-Z7I6SONO.js +825 -0
  59. package/dist/chunk-Z7I6SONO.js.map +1 -0
  60. package/dist/cli/quickdraw-docs.js +131 -113
  61. package/dist/cli/quickdraw-docs.js.map +1 -1
  62. package/dist/client/core.d.ts +387 -0
  63. package/dist/client/core.js +109 -0
  64. package/dist/client/core.js.map +1 -0
  65. package/dist/client/index.d.ts +30 -193
  66. package/dist/client/index.js +56 -217
  67. package/dist/client/index.js.map +1 -1
  68. package/dist/{clientTypes-hWcPUVS9.d.ts → clientTypes-CUUNJwWs.d.ts} +3 -3
  69. package/dist/{connection-CgijdGpT.d.ts → connection-2EeQ_Et0.d.ts} +16 -9
  70. package/dist/{createServer-Cp-Wk500.d.ts → createServer-Bx5HOcYK.d.ts} +37 -9
  71. package/dist/{createTestApp-BB_PkqQ7.d.ts → createTestApp-DAMANT79.d.ts} +36 -9
  72. package/dist/{envelope-DzWyIXjj.d.ts → envelope-BMBaxppV.d.ts} +200 -8
  73. package/dist/{http-DotQ5bj8.d.ts → http-YzLAar3w.d.ts} +15 -50
  74. package/dist/index.d.ts +7 -6
  75. package/dist/index.js +61 -28
  76. package/dist/index.js.map +1 -1
  77. package/dist/{infer-BmoZsL9a.d.ts → infer-Br62cnyW.d.ts} +39 -1
  78. package/dist/{metrics-DW80Exve.d.ts → metrics-CTVpw0gu.d.ts} +2 -2
  79. package/dist/parser.js +2 -1
  80. package/dist/prisma/index.d.ts +13 -6
  81. package/dist/prisma/index.js +155 -9
  82. package/dist/prisma/index.js.map +1 -1
  83. package/dist/remote-N7OUAGOW.js +15 -0
  84. package/dist/remote-N7OUAGOW.js.map +1 -0
  85. package/dist/server/auth/index.d.ts +3 -3
  86. package/dist/server/auth/index.js +5 -3
  87. package/dist/server/auth/index.js.map +1 -1
  88. package/dist/server/index.d.ts +140 -36
  89. package/dist/server/index.js +162 -55
  90. package/dist/server/index.js.map +1 -1
  91. package/dist/server/mcp/index.d.ts +34 -18
  92. package/dist/server/mcp/index.js +29 -12
  93. package/dist/server/mcp/index.js.map +1 -1
  94. package/dist/server/otel.d.ts +3 -3
  95. package/dist/{sharing-UDLn1049.d.ts → sharing-BrsmlDv_.d.ts} +3 -3
  96. package/dist/testing/client.d.ts +13 -13
  97. package/dist/testing/client.js +17 -10
  98. package/dist/testing/client.js.map +1 -1
  99. package/dist/testing/index.d.ts +49 -12
  100. package/dist/testing/index.js +102 -19
  101. package/dist/testing/index.js.map +1 -1
  102. package/dist/testing/mock.d.ts +5 -5
  103. package/dist/testing/mock.js +15 -9
  104. package/dist/tracked-BR5b2O-U.d.ts +43 -0
  105. package/dist/{types-CYliTP65.d.ts → types-CLRCQGnO.d.ts} +4 -3
  106. package/dist/types-tMagHbjy.d.ts +151 -0
  107. package/dist/utils/index.d.ts +16 -4
  108. package/dist/utils/index.js +6 -3
  109. package/package.json +5 -1
  110. package/dist/chunk-4YO5H5ON.js.map +0 -1
  111. package/dist/chunk-5CGO426C.js.map +0 -1
  112. package/dist/chunk-6K5BY47X.js.map +0 -1
  113. package/dist/chunk-753VJIUP.js.map +0 -1
  114. package/dist/chunk-7QCUX4TK.js.map +0 -1
  115. package/dist/chunk-AONAFOYU.js.map +0 -1
  116. package/dist/chunk-B2P7AZ25.js.map +0 -1
  117. package/dist/chunk-GKH3LJ7N.js.map +0 -1
  118. package/dist/chunk-GSIPUNJL.js.map +0 -1
  119. package/dist/chunk-MBH6IDSM.js.map +0 -1
  120. package/dist/chunk-RJ5I2VO3.js.map +0 -1
  121. package/dist/chunk-X5CWPX7H.js.map +0 -1
  122. package/dist/chunk-Z2LZ7IZ7.js.map +0 -1
  123. /package/dist/{chunk-LCC7HNFP.js.map → chunk-RZXJTDH5.js.map} +0 -0
  124. /package/dist/{chunk-NMXYENH4.js.map → chunk-VZFJTKIW.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/contract/methods.ts","../src/contract/kits/schemas.ts","../src/contract/kits/crudList.ts","../src/contract/kits/crudSchemas.ts","../src/contract/kits/searchSchemas.ts","../src/contract/kits/search.ts","../src/contract/kits/adminFields.ts","../src/contract/kits/adminSchemas.ts","../src/contract/kits/admin.ts"],"sourcesContent":["// Method declarations for a contract (RFC 0003 section 2). Every method is a\n// `query` or a `mutation`, and both `input` and `output` are required. This\n// replaces the 4.1 hand-written `ServiceMethodsMap` plus the optional Zod\n// schema passed to `defineMethod` (4.1 `src/server/BaseService.ts:848-851`).\n\nimport type { InferInput, StandardSchemaV1 } from \"./standardSchema\";\n\n/**\n * A query reads; a mutation writes. The kind decides request sharing,\n * cancellation, the per-socket concurrency cap, the HTTP verb, the MCP\n * read-only hint and which client hook exists.\n */\nexport type MethodKind = \"query\" | \"mutation\";\n\n/** The name of the implicit projection: the full entity. */\nexport type EntityProjection = \"entity\";\n\n/** `nullable(\"entity\")`: one row of a projection, or `null`. */\nexport interface NullableProjection<Projection extends string = string> {\n readonly kind: \"nullable\";\n readonly projection: Projection;\n}\n\n/** `listOf(\"card\")`: an array of rows of a projection. */\nexport interface ProjectionList<Projection extends string = string> {\n readonly kind: \"list\";\n readonly projection: Projection;\n}\n\n/** A method output given as a projection: its name, optionally wrapped. */\nexport type ProjectionRef<Projection extends string = string> =\n | Projection\n | NullableProjection<Projection>\n | ProjectionList<Projection>;\n\n/** What a method returns: any Standard Schema, or a projection of the entity. */\nexport type MethodOutput = StandardSchemaV1 | ProjectionRef;\n\n/**\n * Declares that a query reads one scope of one of the contract's collections.\n * The client joins that topic and invalidates the query when the scope changes\n * (RFC 0003 section 11.3). `scope` receives the input exactly as the caller\n * passed it.\n */\nexport interface Watch<Collection extends string = string, Input = never> {\n readonly collection: Collection;\n readonly scope: (input: Input) => string;\n}\n\n/**\n * `watch: { service: [\"gameScore\"] }`: the service's change topic, narrowed\n * to the models named (finding F7.3 of the quickdraw-chat review): the\n * query is invalidated only after a flush that changed one of them. The\n * names are models of the service, by the client's model name: its `model`\n * and those it lists in `writes`; `defineService` refuses any other.\n */\nexport interface ServiceModelsWatch {\n readonly service: readonly string[];\n}\n\n/**\n * `watch: \"service\"`: the query reads what the service's change topic covers\n * (its rows, its collections, and the models it lists in `writes`, such as\n * a game's high scores), so it is invalidated after every flush that\n * changes any of them. `watch: { service: [models] }` is invalidated only\n * when one of the models named changed. The service must open its topic\n * with `watchAccess`.\n */\nexport type ServiceWatch = \"service\" | ServiceModelsWatch;\n\n/** A `query` as `defineContract` stores it. */\nexport interface QueryDef<\n Input extends StandardSchemaV1 = StandardSchemaV1,\n Output extends MethodOutput = MethodOutput,\n Watched extends string = never,\n> {\n readonly kind: \"query\";\n readonly input: Input;\n readonly output: Output;\n /**\n * The topic the query watches: a collection scope (`Watched` is then the\n * collection's name), or `\"service\"`, its service's own topic, or\n * `{ service: [models] }`, that topic narrowed to the models named.\n */\n readonly watch?:\n | ([Watched] extends [never] ? ServiceWatch : Watch<Watched, InferInput<Input>>)\n | undefined;\n /** What the method does, in a sentence or two. The MCP bridge uses it as the tool's description. */\n readonly describe?: string | undefined;\n}\n\n/** A `mutation` as `defineContract` stores it. Mutations never watch. */\nexport interface MutationDef<\n Input extends StandardSchemaV1 = StandardSchemaV1,\n Output extends MethodOutput = MethodOutput,\n> {\n readonly kind: \"mutation\";\n readonly input: Input;\n readonly output: Output;\n readonly watch?: undefined;\n /** What the method does, in a sentence or two. The MCP bridge uses it as the tool's description. */\n readonly describe?: string | undefined;\n}\n\n/** Any method of any contract. */\nexport interface MethodDef {\n readonly kind: MethodKind;\n readonly input: StandardSchemaV1;\n readonly output: MethodOutput;\n readonly watch?: Watch<string> | ServiceWatch | undefined;\n readonly describe?: string | undefined;\n}\n\n/**\n * A read. `output` is a schema or a projection name (`\"entity\"` or a key of\n * the contract's `projections`), optionally wrapped in `nullable` or `listOf`.\n * `describe` says what the method does, for people and agents: the MCP\n * bridge uses it as the tool's description.\n *\n * @example\n * get: query({ input: z.object({ id: z.string() }), output: \"entity\", describe: \"Reads one task\" })\n */\nexport function query<\n const Input extends StandardSchemaV1,\n const Output extends MethodOutput,\n const Watched extends string = never,\n>(def: {\n readonly input: Input;\n readonly output: Output;\n readonly watch?: Watch<Watched, InferInput<Input>> | ServiceWatch;\n readonly describe?: string;\n}): QueryDef<Input, Output, NoInfer<Watched>> {\n // `NoInfer` in the return type: inside `defineContract`, TypeScript would\n // otherwise infer `Watched` from the surrounding contract as `string` for a\n // query that does not watch, and the watch check would then reject it.\n // Absent options stay absent rather than becoming `undefined` members.\n // A collection watch names `Watched`; `\"service\"` leaves it `never`, as the type says.\n const method = {\n kind: \"query\",\n input: def.input,\n output: def.output,\n ...(def.watch === undefined ? {} : { watch: def.watch }),\n ...(def.describe === undefined ? {} : { describe: def.describe }),\n } as QueryDef<Input, Output, Watched>;\n return Object.freeze(method);\n}\n\n/**\n * A write. `output` and `describe` follow the same rules as `query`; a\n * mutation cannot `watch`.\n *\n * @example\n * rename: mutation({ input: renameSchema, output: \"entity\" })\n */\nexport function mutation<\n const Input extends StandardSchemaV1,\n const Output extends MethodOutput,\n>(def: {\n readonly input: Input;\n readonly output: Output;\n readonly describe?: string;\n}): MutationDef<Input, Output> {\n const method: MutationDef<Input, Output> = {\n kind: \"mutation\",\n input: def.input,\n output: def.output,\n ...(def.describe === undefined ? {} : { describe: def.describe }),\n };\n return Object.freeze(method);\n}\n\n/** A method output of one projection row, or `null` when there is none. */\nexport function nullable<const Projection extends string>(\n projection: Projection,\n): NullableProjection<Projection> {\n return Object.freeze({ kind: \"nullable\", projection });\n}\n\n/** A method output of an array of projection rows. */\nexport function listOf<const Projection extends string>(\n projection: Projection,\n): ProjectionList<Projection> {\n return Object.freeze({ kind: \"list\", projection });\n}\n","// The schemas kits generate (RFC 0003 section 12): plain Standard Schemas that\n// also describe themselves as JSON Schema (Standard JSON Schema v1), so a\n// kit's methods become MCP tools like any method whose schemas come from\n// Zod 4.2 or later. Dependency-free and browser-safe, like the rest of the\n// contract layer: a kit takes the app's own schemas (any Standard Schema\n// library) and wraps them, and builds the parts it adds (ids, cursors,\n// limits) itself.\n\nimport type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n StandardSchemaWithJSON,\n} from \"../standardSchema\";\n\n/** A JSON Schema document, as a kit schema writes it. */\nexport type JsonSchema = Record<string, unknown>;\n\n/** A schema a kit generates: validation, and its JSON Schema. */\nexport type KitSchema<Input, Output = Input> = StandardSchemaWithJSON<Input, Output>;\n\n/** A schema's validation result: `{ value }` or `{ issues }`. */\nexport type Validated<Output> = StandardSchemaV1.Result<Output>;\n\ntype Validator<Output> = (value: unknown) => Validated<Output> | Promise<Validated<Output>>;\n\n/** Writes the JSON Schema of a kit schema's input and output for one target. */\nexport interface JsonWriter {\n readonly input: (target: string) => JsonSchema;\n readonly output?: (target: string) => JsonSchema;\n}\n\nconst DIALECTS: Readonly<Record<string, string>> = Object.freeze({\n \"draft-07\": \"http://json-schema.org/draft-07/schema#\",\n \"draft-2020-12\": \"https://json-schema.org/draft/2020-12/schema\",\n});\n\n/** The `$schema` of a JSON Schema target a kit schema writes, or an error for one it does not. */\nfunction dialectOf(options: StandardJSONSchemaV1.Options): string {\n const dialect = DIALECTS[options.target];\n if (dialect === undefined) {\n throw new Error(\n `quickdraw's kit schemas write JSON Schema draft-07 and draft-2020-12, not ${options.target}`,\n );\n }\n return dialect;\n}\n\n/** A Standard Schema with Standard JSON Schema, from a validator and a JSON Schema writer. */\nexport function kitSchema<Input, Output = Input>(\n validate: Validator<Output>,\n json: JsonWriter,\n): KitSchema<Input, Output> {\n const write =\n (side: (target: string) => JsonSchema) =>\n (options: StandardJSONSchemaV1.Options): Record<string, unknown> => ({\n $schema: dialectOf(options),\n ...side(options.target),\n });\n const jsonSchema = Object.freeze({\n input: write(json.input),\n output: write(json.output ?? json.input),\n });\n return Object.freeze({\n \"~standard\": Object.freeze({ version: 1, vendor: \"quickdraw\", validate, jsonSchema }),\n }) as KitSchema<Input, Output>;\n}\n\n/** A failed validation with one issue. */\nexport function invalid(message: string, path: readonly PropertyKey[] = []): Validated<never> {\n return { issues: [{ message, path: [...path] }] };\n}\n\n/** A plain object: what kit inputs are made of. */\nexport function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A row id: a non-empty string. */\nexport function isId(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/** The keys of `value` that are not in `allowed`, as issues at `path`. */\nexport function unknownKeys(\n value: Readonly<Record<string, unknown>>,\n allowed: readonly string[],\n path: readonly PropertyKey[] = [],\n): StandardSchemaV1.Issue[] {\n const known = allowed.length === 0 ? \"none\" : allowed.map((key) => `\"${key}\"`).join(\", \");\n return Object.keys(value)\n .filter((key) => !allowed.includes(key))\n .map((key) => ({\n message: `Unknown key \"${key}\"; the keys are ${known}`,\n path: [...path, key],\n }));\n}\n\n/** Issues from another schema, moved under `path`. */\nexport function nested(\n issues: readonly StandardSchemaV1.Issue[],\n path: readonly PropertyKey[],\n): StandardSchemaV1.Issue[] {\n return issues.map((issue) => ({\n message: issue.message,\n path: [...path, ...(issue.path ?? [])],\n }));\n}\n\n/** The JSON Schema of a row id. */\nexport function idJson(): JsonSchema {\n return { type: \"string\", minLength: 1 };\n}\n\n/** The JSON Schema of an object with `properties`, all of `required` present and nothing else. */\nexport function objectJson(\n properties: Readonly<Record<string, JsonSchema>>,\n required: readonly string[] = [],\n): JsonSchema {\n return {\n type: \"object\",\n properties: { ...properties },\n ...(required.length === 0 ? {} : { required: [...required] }),\n additionalProperties: false,\n };\n}\n\n/** True when `schema` can describe itself as JSON Schema. */\nfunction describes(schema: StandardSchemaV1): schema is StandardSchemaWithJSON {\n const props: object = schema[\"~standard\"];\n return \"jsonSchema\" in props && isRecord(props.jsonSchema);\n}\n\n/**\n * The JSON Schema a Standard Schema writes for `target`, without its\n * `$schema` (the kit schema around it writes its own), or `undefined` when\n * the schema cannot describe itself.\n */\nexport function jsonOf(\n schema: StandardSchemaV1,\n side: \"input\" | \"output\",\n target: string,\n): JsonSchema | undefined {\n if (!describes(schema)) {\n return undefined;\n }\n const { $schema: _dialect, ...json } = schema[\"~standard\"].jsonSchema[side]({ target });\n return json;\n}\n\n/** True when `schema` can describe itself as JSON Schema: a kit schema wrapping it can too. */\nexport function hasJson(schema: StandardSchemaV1): boolean {\n return describes(schema);\n}\n","// The input and output of the read/write kit's `list` (RFC 0003 section\n// 12.1). A caller may filter and sort only on the fields the contract\n// declares, and a filter value is a plain value (equality), never an object:\n// nothing the caller sends reaches the database as an operator. The page\n// size defaults to 50 and is clamped to 200; the cursor is opaque here and\n// decoded by the server.\n\nimport type { SortDirection } from \"../collections\";\nimport type { StandardSchemaV1 } from \"../standardSchema\";\nimport {\n isRecord,\n jsonOf,\n kitSchema,\n objectJson,\n unknownKeys,\n type JsonSchema,\n type KitSchema,\n} from \"./schemas\";\n\n/** `list`'s page size when the caller gives none. */\nexport const LIST_DEFAULT_LIMIT = 50;\n\n/** The largest page `list` returns: a larger `limit` is clamped to it. */\nexport const LIST_MAX_LIMIT = 200;\n\n/** The longest cursor `list` (and `search`) accepts. */\nexport const MAX_CURSOR_LENGTH = 4096;\n\n/** A value a `list` filter compares a field with. */\nexport type FilterValue = string | number | boolean | null;\n\n/** A `list` call's sort: one declared field, ascending unless said otherwise. */\nexport interface ListSort<Field extends string = string> {\n readonly field: Field;\n readonly direction?: SortDirection;\n}\n\n/** `list`'s input as its handler receives it: defaults applied, the limit clamped. */\nexport interface ListQuery<Filter extends string = string, Sort extends string = string> {\n /** Equality per declared field; `{}` for none. */\n readonly filter: { readonly [Field in Filter]?: FilterValue };\n /** The caller's sort, or `undefined` for the default order. */\n readonly sort: { readonly field: Sort; readonly direction: SortDirection } | undefined;\n readonly cursor: string | undefined;\n /** At least 1 and at most {@link LIST_MAX_LIMIT}. */\n readonly limit: number;\n /** Whether to count every matching row, which costs a second statement. */\n readonly totalCount: boolean;\n}\n\n/** One page of `list`. */\nexport interface ListPage<Item> {\n readonly items: Item[];\n /** Passed back as `cursor` for the next page; `null` on the last page. */\n readonly nextCursor: string | null;\n /** Every row the call's filter and access match, when it asked with `totalCount: true`. */\n readonly totalCount?: number;\n}\n\n/** What `list` declares: the fields a caller may filter and sort on. */\nexport interface ListFields {\n readonly filter: readonly string[];\n readonly sort: readonly string[];\n}\n\ntype Issues = StandardSchemaV1.Issue[];\n\nfunction isFilterValue(value: unknown): value is FilterValue {\n return value === null || [\"string\", \"number\", \"boolean\"].includes(typeof value);\n}\n\nfunction quoted(names: readonly string[]): string {\n return names.length === 0 ? \"none\" : names.map((name) => `\"${name}\"`).join(\", \");\n}\n\n/** The issues of a `filter`: equality on declared fields only. The admin kit's `adminList` too. */\nexport function filterIssues(filter: unknown, fields: readonly string[]): Issues {\n if (filter === undefined) {\n return [];\n }\n if (!isRecord(filter)) {\n return [{ message: \"Expected an object of field values\", path: [\"filter\"] }];\n }\n return Object.entries(filter).flatMap(([field, value]): Issues => {\n if (!fields.includes(field)) {\n const message = `\"${field}\" is not a filter field; the filter fields are ${quoted(fields)}`;\n return [{ message, path: [\"filter\", field] }];\n }\n return isFilterValue(value)\n ? []\n : [{ message: \"Expected a string, number, boolean or null\", path: [\"filter\", field] }];\n });\n}\n\n/** The issues of a `sort`: one declared field, and a direction. The admin kit's `adminList` too. */\nexport function sortIssues(sort: unknown, fields: readonly string[]): Issues {\n if (sort === undefined) {\n return [];\n }\n if (!isRecord(sort)) {\n return [{ message: \"Expected { field, direction? }\", path: [\"sort\"] }];\n }\n const issues = unknownKeys(sort, [\"field\", \"direction\"], [\"sort\"]);\n if (typeof sort.field !== \"string\" || !fields.includes(sort.field)) {\n const message = `\"${String(sort.field)}\" is not a sort field; the sort fields are ${quoted(fields)}`;\n issues.push({ message, path: [\"sort\", \"field\"] });\n }\n if (sort.direction !== undefined && sort.direction !== \"asc\" && sort.direction !== \"desc\") {\n issues.push({ message: 'Expected \"asc\" or \"desc\"', path: [\"sort\", \"direction\"] });\n }\n return issues;\n}\n\n/** The issues of a page request's `cursor`, `limit` and `totalCount`, those it has. */\nexport function pagingIssues(value: Readonly<Record<string, unknown>>): Issues {\n const { cursor, limit, totalCount } = value;\n const issues: Issues = [];\n const isCursor =\n typeof cursor === \"string\" && cursor.length > 0 && cursor.length <= MAX_CURSOR_LENGTH;\n if (cursor !== undefined && !isCursor) {\n issues.push({ message: \"Expected a cursor from an earlier page\", path: [\"cursor\"] });\n }\n if (limit !== undefined && !(Number.isInteger(limit) && (limit as number) >= 1)) {\n issues.push({ message: \"Expected a whole number of at least 1\", path: [\"limit\"] });\n }\n if (totalCount !== undefined && typeof totalCount !== \"boolean\") {\n issues.push({ message: \"Expected a boolean\", path: [\"totalCount\"] });\n }\n return issues;\n}\n\n/** The parsed input of a valid `list` call. */\nfunction queryOf(value: Readonly<Record<string, unknown>>): ListQuery {\n const sort = value.sort as ListSort | undefined;\n const limit = (value.limit as number | undefined) ?? LIST_DEFAULT_LIMIT;\n return {\n filter: { ...(value.filter as Readonly<Record<string, FilterValue>> | undefined) },\n sort:\n sort === undefined ? undefined : { field: sort.field, direction: sort.direction ?? \"asc\" },\n cursor: value.cursor as string | undefined,\n limit: Math.min(limit, LIST_MAX_LIMIT),\n totalCount: value.totalCount === true,\n };\n}\n\n/** The entity's JSON Schema properties, which describe its filter fields; none when it cannot write them. */\nfunction entityProperties(\n entity: StandardSchemaV1 | undefined,\n target: string,\n): Readonly<Record<string, unknown>> {\n let properties: unknown;\n try {\n properties = entity === undefined ? undefined : jsonOf(entity, \"input\", target)?.properties;\n } catch {\n properties = undefined;\n }\n return isRecord(properties) ? properties : {};\n}\n\n/** The JSON Schema of one filter field: the entity's own for that field, or any plain value. */\nfunction fieldJson(properties: Readonly<Record<string, unknown>>, field: string): JsonSchema {\n const own = properties[field];\n return isRecord(own) ? { ...own } : { type: [\"string\", \"number\", \"boolean\", \"null\"] };\n}\n\n/**\n * The JSON Schema properties `filter` and `sort` of a list's input, those it\n * declares fields for. The admin kit's `adminList` too.\n */\nexport function filterSortJson(\n fields: ListFields,\n entity: StandardSchemaV1 | undefined,\n target: string,\n): Record<string, JsonSchema> {\n const properties = entityProperties(entity, target);\n const filter = Object.fromEntries(\n fields.filter.map((field) => [field, fieldJson(properties, field)]),\n );\n const sort = objectJson(\n {\n field: { type: \"string\", enum: [...fields.sort] },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n [\"field\"],\n );\n return {\n ...(fields.filter.length === 0 ? {} : { filter: objectJson(filter) }),\n ...(fields.sort.length === 0 ? {} : { sort }),\n };\n}\n\nfunction listJson(fields: ListFields, entity: StandardSchemaV1 | undefined, target: string) {\n return objectJson({\n ...filterSortJson(fields, entity, target),\n cursor: { type: \"string\", minLength: 1, maxLength: MAX_CURSOR_LENGTH },\n limit: { type: \"integer\", minimum: 1, maximum: LIST_MAX_LIMIT, default: LIST_DEFAULT_LIMIT },\n totalCount: { type: \"boolean\" },\n });\n}\n\n/**\n * `list`'s input: `{ filter?, sort?, cursor?, limit?, totalCount? }`, or\n * nothing. `entity` gives the filter fields' JSON Schema when it can write one.\n */\nexport function listInput<Input, Query extends ListQuery>(\n fields: ListFields,\n entity: StandardSchemaV1 | undefined,\n): KitSchema<Input, Query> {\n return kitSchema<Input, Query>(\n (input) => {\n const value = input ?? {};\n if (!isRecord(value)) {\n return { issues: [{ message: \"Expected an object\", path: [] }] };\n }\n const issues = [\n ...unknownKeys(value, [\"filter\", \"sort\", \"cursor\", \"limit\", \"totalCount\"]),\n ...filterIssues(value.filter, fields.filter),\n ...sortIssues(value.sort, fields.sort),\n ...pagingIssues(value),\n ];\n return issues.length > 0 ? { issues } : { value: queryOf(value) as Query };\n },\n { input: (target) => listJson(fields, entity, target) },\n );\n}\n\n/** The issues of a page's `items`: each must be a row with an id. */\nexport function itemsIssues(items: unknown): Issues {\n if (!Array.isArray(items)) {\n return [{ message: \"Expected an array of rows\", path: [\"items\"] }];\n }\n return items.flatMap((item: unknown, index): Issues => {\n const id = isRecord(item) ? item.id : undefined;\n return typeof id === \"string\" && id.length > 0\n ? []\n : [{ message: \"Expected a row with an id\", path: [\"items\", index] }];\n });\n}\n\n/** The JSON Schema of a page's `items`: an array of `item`'s rows, as far as `item` can describe them. */\nexport function itemsJson(item: StandardSchemaV1, target: string): JsonSchema {\n let items: JsonSchema;\n try {\n items = jsonOf(item, \"output\", target) ?? {};\n } catch {\n items = {};\n }\n return { type: \"array\", items };\n}\n\nfunction pageJson(item: StandardSchemaV1, target: string): JsonSchema {\n return objectJson(\n {\n items: itemsJson(item, target),\n nextCursor: { type: [\"string\", \"null\"] },\n totalCount: { type: \"integer\", minimum: 0 },\n },\n [\"items\", \"nextCursor\"],\n );\n}\n\n/**\n * One page of `list`: `{ items, nextCursor, totalCount? }`. Items are checked\n * to be rows with an id, not against `item`: the server strips the fields a\n * reader's level does not reach from them, which the item's own schema may\n * require.\n */\nexport function pageOutput<Item>(item: StandardSchemaV1): KitSchema<ListPage<Item>> {\n return kitSchema<ListPage<Item>>(\n (value) => {\n if (!isRecord(value)) {\n return { issues: [{ message: \"Expected a page\", path: [] }] };\n }\n const { nextCursor, totalCount } = value;\n const issues = [...unknownKeys(value, [\"items\", \"nextCursor\", \"totalCount\"])];\n issues.push(...itemsIssues(value.items));\n if (nextCursor !== null && typeof nextCursor !== \"string\") {\n issues.push({ message: \"Expected a cursor or null\", path: [\"nextCursor\"] });\n }\n if (\n totalCount !== undefined &&\n !(Number.isInteger(totalCount) && (totalCount as number) >= 0)\n ) {\n issues.push({ message: \"Expected a count of rows\", path: [\"totalCount\"] });\n }\n return issues.length > 0 ? { issues } : { value: value as unknown as ListPage<Item> };\n },\n { input: (target) => pageJson(item, target) },\n );\n}\n","// The inputs and outputs the read/write kit generates (RFC 0003 section\n// 12.1), except `list`'s (`crudList.ts`): `{ id }`, `{ ids }` (at most 200),\n// a patch with `id` added, `{ ids, data }`, a reorder's neighbors, `null`\n// and `{ count }`. A part the app's own schema provides (a create input, an\n// update patch) is validated by that schema, and its JSON Schema is the\n// app's own when its library can write one.\n\nimport type { InferInput, InferOutput, StandardSchemaV1 } from \"../standardSchema\";\nimport {\n hasJson,\n idJson,\n invalid,\n isId,\n isRecord,\n jsonOf,\n kitSchema,\n nested,\n objectJson,\n unknownKeys,\n type JsonSchema,\n type KitSchema,\n type Validated,\n} from \"./schemas\";\n\n/** The most ids one `getMany`, `bulkUpdate` or `bulkDelete` call may name. */\nexport const CRUD_MAX_IDS = 200;\n\n/** `{ id }`: one row. */\nexport interface IdInput {\n readonly id: string;\n}\n\n/** `{ ids }`: up to {@link CRUD_MAX_IDS} rows. */\nexport interface IdsInput {\n readonly ids: readonly string[];\n}\n\n/** What `bulkUpdate` and `bulkDelete` return: how many rows they changed. */\nexport interface BulkResult {\n readonly count: number;\n}\n\n/**\n * `reorder`'s input: the row to move, and the rows it lands between. `beforeId`\n * is the row that will come right before it, `afterId` the one right after;\n * one of them is enough.\n */\nexport interface ReorderInput {\n readonly id: string;\n readonly beforeId?: string;\n readonly afterId?: string;\n}\n\nfunction idsIssues(ids: unknown, path: readonly PropertyKey[]): StandardSchemaV1.Issue[] {\n if (!Array.isArray(ids)) {\n return [{ message: \"Expected an array of row ids\", path: [...path] }];\n }\n if (ids.length > CRUD_MAX_IDS) {\n return [{ message: `At most ${CRUD_MAX_IDS} ids`, path: [...path] }];\n }\n return ids.flatMap((id: unknown, index) =>\n isId(id) ? [] : [{ message: \"Expected a non-empty string\", path: [...path, index] }],\n );\n}\n\nfunction idsJson(): JsonSchema {\n return { type: \"array\", items: idJson(), maxItems: CRUD_MAX_IDS };\n}\n\n/** `{ id }`. */\nexport function idInput(): KitSchema<IdInput> {\n return kitSchema<IdInput>(\n (value) => {\n if (!isRecord(value)) {\n return invalid(\"Expected an object\");\n }\n const issues = unknownKeys(value, [\"id\"]);\n if (!isId(value.id)) {\n issues.push({ message: \"Expected a non-empty string\", path: [\"id\"] });\n }\n return issues.length > 0 ? { issues } : { value: { id: value.id as string } };\n },\n { input: () => objectJson({ id: idJson() }, [\"id\"]) },\n );\n}\n\n/** `{ ids }`, at most {@link CRUD_MAX_IDS} of them. */\nexport function idsInput(): KitSchema<IdsInput, { readonly ids: string[] }> {\n return kitSchema<IdsInput, { readonly ids: string[] }>(\n (value) => {\n if (!isRecord(value)) {\n return invalid(\"Expected an object\");\n }\n const issues = [...unknownKeys(value, [\"ids\"]), ...idsIssues(value.ids, [\"ids\"])];\n return issues.length > 0 ? { issues } : { value: { ids: [...(value.ids as string[])] } };\n },\n { input: () => objectJson({ ids: idsJson() }, [\"ids\"]) },\n );\n}\n\n/** The JSON Schema of `{ id, ...patch }`, from the patch's own object schema. */\nfunction withIdJson(patch: StandardSchemaV1, side: \"input\" | \"output\", target: string): JsonSchema {\n const json = jsonOf(patch, side, target) ?? {};\n if (json.type !== \"object\") {\n throw new Error(\"the patch schema does not describe an object\");\n }\n const properties = isRecord(json.properties) ? json.properties : {};\n const required = Array.isArray(json.required) ? (json.required as unknown[]) : [];\n return {\n ...json,\n properties: { id: idJson(), ...properties },\n required: [\"id\", ...required.filter((key) => key !== \"id\")],\n };\n}\n\n/** Validates `value` with the app's patch schema; its result must be an object. */\nasync function patchOf(\n patch: StandardSchemaV1,\n value: unknown,\n path: readonly PropertyKey[],\n): Promise<Validated<Readonly<Record<string, unknown>>>> {\n const result = await patch[\"~standard\"].validate(value);\n if (result.issues !== undefined) {\n return { issues: nested(result.issues, path) };\n }\n return isRecord(result.value)\n ? { value: result.value }\n : invalid(\"The patch schema must produce an object\", path);\n}\n\n/** The schema of `{ id } & patch`: what `update` takes. */\nexport type WithId<Patch extends StandardSchemaV1> = StandardSchemaV1<\n { readonly id: string } & InferInput<Patch>,\n { readonly id: string } & InferOutput<Patch>\n>;\n\n/**\n * `{ id, ...patch }`: `id` is checked here and the other keys by the app's\n * patch schema. With JSON Schema when the patch schema can write it.\n */\nexport function withId<Patch extends StandardSchemaV1>(patch: Patch): WithId<Patch> {\n const validate = async (\n value: unknown,\n ): Promise<Validated<Readonly<Record<string, unknown>>>> => {\n if (!isRecord(value)) {\n return invalid(\"Expected an object\");\n }\n const { id, ...rest } = value;\n const result = await patchOf(patch, rest, []);\n const issues = [\n ...(isId(id) ? [] : [{ message: \"Expected a non-empty string\", path: [\"id\"] }]),\n ...(result.issues ?? []),\n ];\n if (issues.length > 0 || result.issues !== undefined) {\n return { issues };\n }\n return { value: { ...result.value, id: id as string } };\n };\n if (!hasJson(patch)) {\n const props = { version: 1 as const, vendor: \"quickdraw\", validate };\n return Object.freeze({ \"~standard\": Object.freeze(props) }) as unknown as WithId<Patch>;\n }\n return kitSchema(validate, {\n input: (target) => withIdJson(patch, \"input\", target),\n output: (target) => withIdJson(patch, \"output\", target),\n }) as unknown as WithId<Patch>;\n}\n\n/** The schema of `{ ids, data }`: what `bulkUpdate` takes. */\nexport type BulkPatch<Patch extends StandardSchemaV1> = StandardSchemaV1<\n { readonly ids: readonly string[]; readonly data: InferInput<Patch> },\n { readonly ids: string[]; readonly data: InferOutput<Patch> }\n>;\n\nfunction bulkJson(patch: StandardSchemaV1, side: \"input\" | \"output\", target: string): JsonSchema {\n return objectJson({ ids: idsJson(), data: jsonOf(patch, side, target) ?? {} }, [\"ids\", \"data\"]);\n}\n\n/** `{ ids, data }`: up to {@link CRUD_MAX_IDS} ids, and one patch for all of them. */\nexport function bulkPatch<Patch extends StandardSchemaV1>(patch: Patch): BulkPatch<Patch> {\n const validate = async (\n value: unknown,\n ): Promise<Validated<Readonly<Record<string, unknown>>>> => {\n if (!isRecord(value)) {\n return invalid(\"Expected an object\");\n }\n const data = await patchOf(patch, value.data, [\"data\"]);\n const issues = [\n ...unknownKeys(value, [\"ids\", \"data\"]),\n ...idsIssues(value.ids, [\"ids\"]),\n ...(data.issues ?? []),\n ];\n if (issues.length > 0 || data.issues !== undefined) {\n return { issues };\n }\n return { value: { ids: [...(value.ids as string[])], data: data.value } };\n };\n if (!hasJson(patch)) {\n const props = { version: 1 as const, vendor: \"quickdraw\", validate };\n return Object.freeze({ \"~standard\": Object.freeze(props) }) as unknown as BulkPatch<Patch>;\n }\n return kitSchema(validate, {\n input: (target) => bulkJson(patch, \"input\", target),\n output: (target) => bulkJson(patch, \"output\", target),\n }) as unknown as BulkPatch<Patch>;\n}\n\nfunction neighborIssues(value: Readonly<Record<string, unknown>>): StandardSchemaV1.Issue[] {\n const { id, beforeId, afterId } = value;\n const issues: StandardSchemaV1.Issue[] = [];\n for (const key of [\"beforeId\", \"afterId\"] as const) {\n const neighbor = value[key];\n if (neighbor !== undefined && !isId(neighbor)) {\n issues.push({ message: \"Expected a non-empty string\", path: [key] });\n } else if (neighbor !== undefined && neighbor === id) {\n issues.push({ message: \"A row cannot move next to itself\", path: [key] });\n }\n }\n if (beforeId === undefined && afterId === undefined) {\n issues.push({ message: \"Give beforeId, afterId or both\", path: [] });\n } else if (beforeId !== undefined && beforeId === afterId) {\n issues.push({ message: \"beforeId and afterId must be different rows\", path: [\"afterId\"] });\n }\n return issues;\n}\n\n/** `{ id, beforeId?, afterId? }`. */\nexport function reorderInput(): KitSchema<ReorderInput> {\n return kitSchema<ReorderInput>(\n (value) => {\n if (!isRecord(value)) {\n return invalid(\"Expected an object\");\n }\n const issues = [...unknownKeys(value, [\"id\", \"beforeId\", \"afterId\"])];\n if (!isId(value.id)) {\n issues.push({ message: \"Expected a non-empty string\", path: [\"id\"] });\n }\n issues.push(...neighborIssues(value));\n if (issues.length > 0) {\n return { issues };\n }\n const { id, beforeId, afterId } = value as unknown as ReorderInput;\n return {\n value: {\n id,\n ...(beforeId === undefined ? {} : { beforeId }),\n ...(afterId === undefined ? {} : { afterId }),\n },\n };\n },\n {\n input: () => objectJson({ id: idJson(), beforeId: idJson(), afterId: idJson() }, [\"id\"]),\n },\n );\n}\n\n/** `null`: what `delete` returns. */\nexport function nullOutput(): KitSchema<null> {\n return kitSchema<null>((value) => (value === null ? { value } : invalid(\"Expected null\")), {\n input: () => ({ type: \"null\" }),\n });\n}\n\n/** `{ count }`: what `bulkUpdate` and `bulkDelete` return. */\nexport function countOutput(): KitSchema<BulkResult> {\n return kitSchema<BulkResult>(\n (value) => {\n const count = isRecord(value) ? value.count : undefined;\n return Number.isInteger(count) && (count as number) >= 0\n ? { value: { count: count as number } }\n : invalid(\"Expected { count } with a count of rows\");\n },\n { input: () => objectJson({ count: { type: \"integer\", minimum: 0 } }, [\"count\"]) },\n );\n}\n","// The input and output of the search kit's `search` (RFC 0003 section 12.2).\n// A call passes the text to look for, `q`, trimmed here; `scope`, one scope\n// of the collection the contract's search names (only when it names one);\n// and the cursor and page size of `list` (`crudList.ts`): 20 items by\n// default, at most 100 (a larger `limit` is clamped). The cursor is opaque\n// here and decoded by the server.\n//\n// A page is `{ items, nextCursor, rev? }`. Its items are checked to be rows\n// with an id, not against the item schema: the server strips the fields the\n// reader's level does not reach, which the item's own schema may require.\n\nimport type { StandardSchemaV1 } from \"../standardSchema\";\nimport { itemsIssues, itemsJson, MAX_CURSOR_LENGTH, pagingIssues } from \"./crudList\";\nimport {\n isRecord,\n kitSchema,\n objectJson,\n unknownKeys,\n type JsonSchema,\n type KitSchema,\n} from \"./schemas\";\n\n/** `search`'s page size when the caller gives none. */\nexport const SEARCH_DEFAULT_LIMIT = 20;\n\n/** The largest page `search` returns: a larger `limit` is clamped to it. */\nexport const SEARCH_MAX_LIMIT = 100;\n\n/** How long a query must be, once trimmed, unless the contract says otherwise. */\nexport const SEARCH_DEFAULT_MIN_LENGTH = 2;\n\n/** The longest query `search` accepts, in characters. */\nexport const SEARCH_MAX_QUERY_LENGTH = 256;\n\n/** The longest scope value `search` accepts, as for subscriptions (RFC 0003 section 8.2). */\nconst MAX_SCOPE_LENGTH = 256;\n\n/** What a `search` call passes; `Scoped` when the contract's search names a collection. */\nexport type SearchInput<Scoped extends boolean = false> = {\n /** The text to look for. Trimmed; one shorter than the method's `minLength` finds nothing. */\n readonly q: string;\n /** The `nextCursor` of the page before; the first page when absent. */\n readonly cursor?: string;\n /** The page size: default 20, at most 100 (a larger one is clamped). */\n readonly limit?: number;\n} & (Scoped extends true\n ? {\n /** One scope of the search's collection (a project id): only its members are searched. */\n readonly scope?: string;\n }\n : unknown);\n\n/** `search`'s input as its handler receives it: `q` trimmed, defaults applied, the limit clamped. */\nexport interface SearchQuery {\n readonly q: string;\n readonly scope: string | undefined;\n readonly cursor: string | undefined;\n /** At least 1 and at most {@link SEARCH_MAX_LIMIT}. */\n readonly limit: number;\n}\n\n/** One page of `search`. */\nexport interface SearchPage<Item> {\n readonly items: Item[];\n /** Passed back as `cursor` for the next page; `null` on the last page. */\n readonly nextCursor: string | null;\n /**\n * Set when the search ran in a scope and its items are that scope's\n * collection items exactly as the collection's subscribers receive them:\n * the revision they were read at, so a client can keep them in the\n * collection's cache, where the scope's deltas keep them current.\n */\n readonly rev?: number;\n}\n\ntype Issues = StandardSchemaV1.Issue[];\n\nfunction queryIssues(q: unknown): Issues {\n if (typeof q !== \"string\") {\n return [{ message: \"Expected the text to search for\", path: [\"q\"] }];\n }\n return q.length > SEARCH_MAX_QUERY_LENGTH\n ? [{ message: `At most ${SEARCH_MAX_QUERY_LENGTH} characters`, path: [\"q\"] }]\n : [];\n}\n\nfunction scopeIssues(scope: unknown): Issues {\n const valid =\n scope === undefined ||\n (typeof scope === \"string\" && scope.length > 0 && scope.length <= MAX_SCOPE_LENGTH);\n return valid ? [] : [{ message: \"Expected a scope value\", path: [\"scope\"] }];\n}\n\n/** The parsed input of a valid `search` call. */\nfunction queryOf(value: Readonly<Record<string, unknown>>): SearchQuery {\n const limit = (value.limit as number | undefined) ?? SEARCH_DEFAULT_LIMIT;\n return {\n q: (value.q as string).trim(),\n scope: value.scope as string | undefined,\n cursor: value.cursor as string | undefined,\n limit: Math.min(limit, SEARCH_MAX_LIMIT),\n };\n}\n\nfunction searchJson(scoped: boolean): JsonSchema {\n return objectJson(\n {\n q: { type: \"string\", maxLength: SEARCH_MAX_QUERY_LENGTH },\n ...(scoped ? { scope: { type: \"string\", minLength: 1, maxLength: MAX_SCOPE_LENGTH } } : {}),\n cursor: { type: \"string\", minLength: 1, maxLength: MAX_CURSOR_LENGTH },\n limit: {\n type: \"integer\",\n minimum: 1,\n maximum: SEARCH_MAX_LIMIT,\n default: SEARCH_DEFAULT_LIMIT,\n },\n },\n [\"q\"],\n );\n}\n\n/**\n * `search`'s input: `{ q, scope?, cursor?, limit? }`, with `scope` only when\n * the contract's search names a collection (`scoped`).\n */\nexport function searchInput<Scoped extends boolean>(\n scoped: Scoped,\n): KitSchema<SearchInput<Scoped>, SearchQuery> {\n const keys = scoped ? [\"q\", \"scope\", \"cursor\", \"limit\"] : [\"q\", \"cursor\", \"limit\"];\n return kitSchema<SearchInput<Scoped>, SearchQuery>(\n (input) => {\n if (!isRecord(input)) {\n return { issues: [{ message: \"Expected { q, ... }\", path: [] }] };\n }\n const issues = [\n ...unknownKeys(input, keys),\n ...queryIssues(input.q),\n ...(scoped ? scopeIssues(input.scope) : []),\n ...pagingIssues({ cursor: input.cursor, limit: input.limit }),\n ];\n return issues.length > 0 ? { issues } : { value: queryOf(input) };\n },\n { input: () => searchJson(scoped) },\n );\n}\n\n/** One page of `search`: `{ items, nextCursor, rev? }`. */\nexport function searchPageOutput<Item>(item: StandardSchemaV1): KitSchema<SearchPage<Item>> {\n return kitSchema<SearchPage<Item>>(\n (value) => {\n if (!isRecord(value)) {\n return { issues: [{ message: \"Expected a page\", path: [] }] };\n }\n const { nextCursor, rev } = value;\n const issues = [...unknownKeys(value, [\"items\", \"nextCursor\", \"rev\"])];\n issues.push(...itemsIssues(value.items));\n if (nextCursor !== null && typeof nextCursor !== \"string\") {\n issues.push({ message: \"Expected a cursor or null\", path: [\"nextCursor\"] });\n }\n if (rev !== undefined && !(typeof rev === \"number\" && Number.isFinite(rev))) {\n issues.push({ message: \"Expected a revision\", path: [\"rev\"] });\n }\n return issues.length > 0 ? { issues } : { value: value as unknown as SearchPage<Item> };\n },\n {\n input: (target) =>\n objectJson(\n {\n items: itemsJson(item, target),\n nextCursor: { type: [\"string\", \"null\"] },\n rev: { type: \"number\" },\n },\n [\"items\", \"nextCursor\"],\n ),\n },\n );\n}\n","// The search kit's contract half (RFC 0003 section 12.2). `search.contract`\n// returns one ordinary `query` entry, `search`, to spread into a contract's\n// `methods`:\n//\n// export const task = defineContract(\"taskService\", {\n// entity: taskSchema,\n// projections: { card: cardSchema },\n// methods: {\n// ...search.contract({ entity: taskSchema, item: cardSchema, fields: [\"title\"], scope: \"byProject\" }),\n// },\n// collections: { byProject: { scope: \"projectId\", item: \"card\", order: [...] } },\n// });\n//\n// `fields` are the entity's text fields a search looks in: an explicit list,\n// because an unbounded \"contains\" over every column is slow. `scope` names a\n// collection of the contract: a call may then pass one of its scopes, and\n// the search keeps to that scope's members, in the collection's order, its\n// results the collection's items (so a client keeps them live through the\n// collection's cache). The server half (`search.handlers` on `./server`)\n// finds the entry in the contract by what it was made for (`searchSpecOf`);\n// its type carries that too (`SearchTag`), and the client adds `useSearch`\n// to its member.\n\nimport type { RowSchema } from \"../defineContract\";\nimport { query, type QueryDef } from \"../methods\";\nimport { isStandardSchema, type InferOutput, type StandardSchemaV1 } from \"../standardSchema\";\nimport type { KitSchema } from \"./schemas\";\nimport {\n SEARCH_DEFAULT_MIN_LENGTH,\n SEARCH_MAX_QUERY_LENGTH,\n searchInput,\n searchPageOutput,\n type SearchInput,\n type SearchPage,\n type SearchQuery,\n} from \"./searchSchemas\";\n\n/** Type-only: marks a method the search kit made. Never set. */\nexport interface SearchTag {\n readonly \"~search\"?: true;\n}\n\ntype RowOf<Entity> = Entity extends StandardSchemaV1 ? InferOutput<Entity> : never;\n\n/** The entity's fields holding strings: what a search may look in. */\nexport type TextFieldOf<Row> = {\n [Field in keyof Row]-?: NonNullable<Row[Field]> extends string ? Field : never;\n}[keyof Row] &\n string;\n\n/** `search.contract`'s options. */\nexport interface SearchContractOptions {\n /** The contract's entity schema: `fields` are its fields. */\n readonly entity: RowSchema;\n /** The text fields a search looks in (at least one). */\n readonly fields: readonly string[];\n /**\n * The schema of each result: the contract's entity schema (the default) or\n * one of its projections' schemas, the same object. With `scope`, the\n * scope collection's item.\n */\n readonly item?: RowSchema;\n /** A collection of the contract: a call may pass one of its scopes, and the search keeps to it. */\n readonly scope?: string;\n /** How long a query must be once trimmed; a shorter one finds nothing. Default 2. */\n readonly minLength?: number;\n /** The method's description, for people and agents; the kit's own when absent. */\n readonly describe?: string;\n}\n\ntype Quoted<Names> = `\"${Names & string}\"`;\n\ntype FieldsIn<O> = O extends { readonly fields: readonly (infer Field extends string)[] }\n ? Field\n : never;\n\n/** The check of `fields` against the entity that the option types alone cannot state. */\ntype SearchChecks<O> = O extends { readonly entity: infer Entity }\n ? [Exclude<FieldsIn<O>, TextFieldOf<RowOf<Entity>>>] extends [never]\n ? unknown\n : {\n readonly fields: `search.contract: fields: ${Quoted<\n Exclude<FieldsIn<O>, TextFieldOf<RowOf<Entity>>>\n >} is not a field of the entity holding strings`;\n }\n : unknown;\n\n/** The entry `search.contract` makes: a query of a page of `Item`s. */\nexport type SearchDef<Item, Scoped extends boolean = false> = QueryDef<\n KitSchema<SearchInput<Scoped>, SearchQuery>,\n KitSchema<SearchPage<Item>>\n> &\n SearchTag;\n\ntype ItemIn<O> = O extends { readonly item: infer Item }\n ? RowOf<Item>\n : O extends { readonly entity: infer Entity }\n ? RowOf<Entity>\n : never;\n\ntype ScopedIn<O> = O extends { readonly scope: string } ? true : false;\n\n/** What `search.contract(options)` returns: one entry, `search`. */\nexport interface SearchMethods<O> {\n readonly search: SearchDef<ItemIn<O>, ScopedIn<O>>;\n}\n\n/** What the server half and the client need to know about a method the search kit made. */\nexport interface SearchSpec {\n readonly fields: readonly string[];\n /** The item's schema; `undefined` for the entity. */\n readonly item: RowSchema | undefined;\n /** The collection whose scopes a call may keep to. */\n readonly scope: string | undefined;\n readonly minLength: number;\n}\n\nconst SPECS = new WeakMap<object, SearchSpec>();\n\n/** What the search kit made `method` for, or `undefined` for any other method. */\nexport function searchSpecOf(method: unknown): SearchSpec | undefined {\n return typeof method === \"object\" && method !== null ? SPECS.get(method) : undefined;\n}\n\ntype UnknownRecord = Readonly<Record<string, unknown>>;\n\nconst OPTIONS = [\"entity\", \"fields\", \"item\", \"scope\", \"minLength\", \"describe\"];\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction fail(message: string): never {\n throw new TypeError(`search.contract: ${message}`);\n}\n\nfunction checkFields(fields: unknown): readonly string[] {\n const valid =\n Array.isArray(fields) &&\n fields.length > 0 &&\n fields.every((field) => typeof field === \"string\" && field.length > 0) &&\n new Set(fields).size === fields.length;\n if (!valid) {\n fail(\"fields must be a list of the distinct text fields to search, at least one\");\n }\n return Object.freeze([...(fields as string[])]);\n}\n\nfunction checkMinLength(minLength: unknown): number {\n if (minLength === undefined) {\n return SEARCH_DEFAULT_MIN_LENGTH;\n }\n const valid =\n typeof minLength === \"number\" &&\n Number.isInteger(minLength) &&\n minLength >= 1 &&\n minLength <= SEARCH_MAX_QUERY_LENGTH;\n if (!valid) {\n fail(`minLength must be a whole number from 1 to ${SEARCH_MAX_QUERY_LENGTH}`);\n }\n return minLength;\n}\n\n/** The options, checked: what the server half and the client read. */\nfunction specOf(options: unknown): SearchSpec {\n if (!isRecord(options)) {\n fail(\"options must be { entity, fields, item?, scope?, minLength?, describe? }\");\n }\n const unknownKey = Object.keys(options).find((key) => !OPTIONS.includes(key));\n if (unknownKey !== undefined) {\n fail(`unknown option \"${unknownKey}\"; the options are ${OPTIONS.join(\", \")}`);\n }\n if (!isStandardSchema(options.entity)) {\n fail(\"entity must be the contract's entity schema\");\n }\n if (options.item !== undefined && !isStandardSchema(options.item)) {\n fail(\"item must be the entity schema or one of the contract's projection schemas\");\n }\n const { scope } = options;\n if (scope !== undefined && (typeof scope !== \"string\" || scope.length === 0)) {\n fail(\"scope must name a collection of the contract\");\n }\n return {\n fields: checkFields(options.fields),\n item: options.item as RowSchema | undefined,\n scope: scope as string | undefined,\n minLength: checkMinLength(options.minLength),\n };\n}\n\n/** The method's description: its own `describe`, or the kit's. */\nfunction describeOf(options: UnknownRecord, spec: SearchSpec): string {\n const own = options.describe;\n if (own !== undefined && (typeof own !== \"string\" || own.length === 0)) {\n fail(\"describe must be a non-empty string\");\n }\n const scoped =\n spec.scope === undefined\n ? \"\"\n : ` Pass scope (one scope of ${spec.scope}) to search only its members.`;\n return (\n own ??\n `Searches the rows the caller can read for the text q (at least ${spec.minLength} characters), a page at a time.${scoped} Pass a page's nextCursor back as cursor for the next page.`\n );\n}\n\nfunction contract<const O extends SearchContractOptions>(\n options: O & NoInfer<SearchChecks<O>>,\n): SearchMethods<O> {\n const spec = specOf(options);\n const entity = options.entity as StandardSchemaV1;\n const def = query({\n input: searchInput(spec.scope !== undefined),\n output: searchPageOutput(spec.item ?? entity),\n describe: describeOf(options as unknown as UnknownRecord, spec),\n });\n SPECS.set(def, Object.freeze(spec));\n return Object.freeze({ search: def }) as unknown as SearchMethods<O>;\n}\n\n/**\n * The search kit's contract half: `search.contract({ entity, fields, item?,\n * scope?, minLength? })` makes the `search` query, which the server half\n * (`search.handlers` on `./server`) implements.\n */\nexport const search = Object.freeze({ contract });\n","// The admin kit's view of an entity (RFC 0003 sections 2 and 12.4): its\n// fields, read from the entity schema's Standard JSON Schema (Zod 4.2 or\n// later), since Standard Schema exposes validation only, and how a write of\n// them is checked. 4.1 read Zod's type names instead\n// (4.1 `src/server/utils/zodToAdminFields.ts:33-103`); the same field\n// types come from each property's JSON Schema here:\n//\n// | JSON Schema of the property | Admin field type |\n// |-------------------------------------------------|-----------------------|\n// | `type: \"string\"`, `format: \"date-time\"`/`\"date\"`| `date` |\n// | `enum` of strings, a string `const`, or a union | `enum` (`enumValues`) |\n// | of those | |\n// | `type: \"string\"` | `string` |\n// | `type: \"number\"` or `\"integer\"` | `number` |\n// | `type: \"boolean\"` | `boolean` |\n// | `type: \"object\"` or `\"array\"`, a union holding | `json` |\n// | one, or no type at all (`z.json()`, `{}`) | |\n// | a union of other types | `string`, as in 4.1 |\n//\n// `null` in a union or a type list makes the field nullable. A field is\n// required when the schema requires it, it is not nullable and it has no\n// default, as 4.1 counted optional, nullable and defaulted fields as not\n// required. `relation` is never derived; `fieldOverrides` sets it.\n//\n// The types here are 4.1's (4.1 `src/shared/types.ts:283-338`).\n\nimport { hasJsonSchema, type StandardSchemaV1 } from \"../standardSchema\";\nimport { isRecord, nested } from \"./schemas\";\n\n/** Supported field types for admin UI generation. */\nexport type AdminFieldType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"enum\"\n | \"json\"\n | \"relation\";\n\n/** Every admin field type. */\nexport const ADMIN_FIELD_TYPES: readonly AdminFieldType[] = Object.freeze([\n \"string\",\n \"number\",\n \"boolean\",\n \"date\",\n \"enum\",\n \"json\",\n \"relation\",\n]);\n\n/** Configuration for a single field in the admin UI: derived from the entity schema, with overrides. */\nexport interface AdminFieldConfig {\n /** Field name (property key on the entity). */\n readonly name: string;\n /** Field type for rendering the right input. */\n readonly type: AdminFieldType;\n /** Human-readable label. */\n readonly label: string;\n /** Whether the field is required for creation. */\n readonly required: boolean;\n /** Whether `adminCreate` and `adminUpdate` may write it (never `id` or the timestamps). */\n readonly editable: boolean;\n /** Whether to show the field as a table column. */\n readonly showInTable: boolean;\n /** Whether `adminList` may sort by it: the contract declares it in `sort`. */\n readonly sortable: boolean;\n /**\n * Whether `adminList` may filter on it: the contract declares it in\n * `filter`. `adminMeta` always says; optional (default `false`) so field\n * configurations written for 4.x, which had no `filterable`, still type.\n */\n readonly filterable?: boolean;\n /** For enum fields, the allowed values. */\n readonly enumValues?: readonly string[];\n /** For relation fields, the related service's name. */\n readonly relationService?: string;\n /**\n * What the field holds, when the kit knows it: `\"grants\"` for a user's\n * service-wide grants (`serviceAccess`, or the column the server's\n * `auth.serviceAccessSource` names, whatever its name), which\n * `admin.handlers(contract, { grants: true })` shows. An admin screen with\n * a grants editor of its own finds that field by it, never by its name.\n * Absent for any other field.\n */\n readonly kind?: \"grants\";\n /**\n * Whether a generic create or edit form shows the field. `false` from a\n * `fieldOverrides` entry (`{ serviceAccess: { showInForm: false } }`) keeps\n * it for an editor of the app's own; the kit still reads and writes it.\n * Absent unless overridden: shown.\n */\n readonly showInForm?: boolean;\n}\n\n/** Service metadata for admin UI generation: what `adminMeta` returns. */\nexport interface AdminServiceMeta {\n /** The service's name on the wire (`\"taskService\"`). */\n readonly serviceName: string;\n /** Human-readable display name (`\"Tasks\"`). */\n readonly displayName: string;\n /** The entity's fields, but those the service hides, as configured for an admin screen. */\n readonly fields: readonly AdminFieldConfig[];\n}\n\n/** An admin field type the entity schema can give: every type but `relation`. */\nexport type EntityFieldType = Exclude<AdminFieldType, \"relation\">;\n\n/** One field of the entity, as its JSON Schema describes it. */\nexport interface AdminEntityField {\n readonly name: string;\n readonly type: EntityFieldType;\n /** Required, not nullable and without a default. */\n readonly required: boolean;\n /** Whether the field accepts `null`. */\n readonly nullable: boolean;\n /** The values of an `enum` field. */\n readonly enumValues: readonly string[] | undefined;\n}\n\n/**\n * Fields no admin call writes, whatever the service configures: the row's key\n * and its timestamps, which the database sets (4.1's non-editable fields,\n * 4.1 `src/server/utils/zodToAdminFields.ts:7`).\n */\nexport const ADMIN_NEVER_WRITABLE: readonly string[] = Object.freeze([\n \"id\",\n \"createdAt\",\n \"updatedAt\",\n \"created_at\",\n \"updated_at\",\n]);\n\n/** The JSON Schema target fields are read from: the MCP bridge's. */\nconst TARGET = \"draft-07\";\n\n/** How deep `$ref`s are followed before a property counts as JSON. */\nconst MAX_REFS = 8;\n\ntype Node = Readonly<Record<string, unknown>>;\n\n/** The `definitions` and `$defs` of the entity's JSON Schema, which `$ref`s point into. */\ntype Defs = Readonly<Record<string, unknown>>;\n\n/** What one property's JSON Schema says: its type, whether it takes `null`, and its enum values. */\ninterface Shape {\n readonly type: EntityFieldType;\n readonly nullable: boolean;\n readonly enumValues?: readonly string[];\n}\n\nconst JSON_SHAPE: Shape = Object.freeze({ type: \"json\", nullable: true });\n\n/** `node` with its `$ref` followed, or `undefined` for a node that says nothing (`true`, a dangling ref). */\nfunction resolve(node: unknown, defs: Defs, depth = 0): Node | undefined {\n if (!isRecord(node)) {\n return undefined;\n }\n const ref = node.$ref;\n if (typeof ref !== \"string\") {\n return node;\n }\n const match = /^#\\/(definitions|\\$defs)\\/(.+)$/.exec(ref);\n const group = match === null ? undefined : defs[match[1] ?? \"\"];\n const target = isRecord(group) ? group[match?.[2] ?? \"\"] : undefined;\n return depth < MAX_REFS ? resolve(target, defs, depth + 1) : undefined;\n}\n\nfunction isNullNode(node: Node | undefined): boolean {\n if (node === undefined) {\n return false;\n }\n const values = node.enum;\n return (\n node.type === \"null\" ||\n (Object.hasOwn(node, \"const\") && node.const === null) ||\n (Array.isArray(values) && values.length > 0 && values.every((value) => value === null))\n );\n}\n\n/** A string `type` alone: `format` makes a string a date. */\nfunction typeShape(type: unknown, format: unknown): EntityFieldType {\n switch (type) {\n case \"string\":\n return format === \"date-time\" || format === \"date\" ? \"date\" : \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n default:\n return \"json\";\n }\n}\n\n/** The shape of a `const`. */\nfunction constShape(value: unknown): Shape {\n if (typeof value === \"string\") {\n return { type: \"enum\", nullable: false, enumValues: [value] };\n }\n return { type: typeShape(typeof value, undefined), nullable: value === null };\n}\n\n/** The shape of an `enum`: of strings an `enum` field, otherwise its type. */\nfunction enumShape(values: readonly unknown[], node: Node): Shape {\n const present = values.filter((value) => value !== null);\n const nullable = present.length < values.length;\n if (present.length > 0 && present.every((value) => typeof value === \"string\")) {\n return { type: \"enum\", nullable, enumValues: present as string[] };\n }\n const type = typeof node.type === \"string\" ? node.type : typeof present[0];\n return { type: typeShape(type, undefined), nullable };\n}\n\n/** The shape of several types at once: JSON when one is a structure, else a string (4.1's default). */\nfunction mixedShape(shapes: readonly Shape[], nullable: boolean): Shape {\n if (shapes.some((shape) => shape.type === \"json\")) {\n return { type: \"json\", nullable };\n }\n if (shapes.every((shape) => shape.type === \"enum\")) {\n const values = shapes.flatMap((shape) => shape.enumValues ?? []);\n return { type: \"enum\", nullable, enumValues: [...new Set(values)] };\n }\n return { type: \"string\", nullable };\n}\n\n/** The shape of a `type` list, `[\"string\", \"null\"]`. */\nfunction typesShape(types: readonly unknown[], node: Node): Shape {\n const present = types.filter((type) => type !== \"null\");\n const nullable = present.length < types.length;\n if (present.length === 1) {\n return { type: typeShape(present[0], node.format), nullable };\n }\n return mixedShape(\n present.map((type) => ({ type: typeShape(type, undefined), nullable: false })),\n nullable,\n );\n}\n\nfunction shapeOf(node: unknown, defs: Defs, depth = 0): Shape {\n const resolved = resolve(node, defs);\n if (resolved === undefined || depth > MAX_REFS) {\n return JSON_SHAPE;\n }\n const union = resolved.anyOf ?? resolved.oneOf;\n if (Array.isArray(union)) {\n return unionShape(union, defs, depth);\n }\n if (Object.hasOwn(resolved, \"const\")) {\n return constShape(resolved.const);\n }\n if (Array.isArray(resolved.enum)) {\n return enumShape(resolved.enum, resolved);\n }\n if (Array.isArray(resolved.type)) {\n return typesShape(resolved.type, resolved);\n }\n if (resolved.type === undefined) {\n // No type at all (`z.unknown()`, `z.any()`): any JSON value, null among them.\n return JSON_SHAPE;\n }\n return {\n type: typeShape(resolved.type, resolved.format),\n nullable: resolved.type === \"null\",\n };\n}\n\n/** The shape of `anyOf` or `oneOf`: `null` makes it nullable, one other member is the field. */\nfunction unionShape(members: readonly unknown[], defs: Defs, depth: number): Shape {\n const present = members.filter((member) => !isNullNode(resolve(member, defs)));\n const nullable = present.length < members.length;\n const shapes = present.map((member) => shapeOf(member, defs, depth + 1));\n if (shapes.length === 1 && shapes[0] !== undefined) {\n return { ...shapes[0], nullable: nullable || shapes[0].nullable };\n }\n return mixedShape(shapes, nullable || shapes.some((shape) => shape.nullable));\n}\n\n/** The object schema a JSON Schema document describes, following one top-level `$ref`. */\nfunction rootObject(json: Node): Node | undefined {\n const root = resolve(json, { definitions: json.definitions, $defs: json.$defs });\n return isRecord(root?.properties) ? root : undefined;\n}\n\n/** Fails with why the entity schema cannot list the admin kit's fields, as a sentence. */\nexport type FieldsFailure = (message: string) => never;\n\n/** The entity's input JSON Schema (draft-07, as the MCP bridge reads it), or a failure naming why it has none. */\nfunction entityJson(entity: StandardSchemaV1, fail: FieldsFailure): Node {\n if (!hasJsonSchema(entity)) {\n fail(\n \"the entity schema cannot describe itself as JSON Schema, which the admin kit's field metadata needs: use Zod 4.2 or later for that schema\",\n );\n }\n try {\n const json: unknown = entity[\"~standard\"].jsonSchema.input({ target: TARGET });\n if (isRecord(json)) {\n return json;\n }\n return fail(\"the entity schema's JSON Schema is not an object\");\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n return fail(\n `the entity schema cannot be written as JSON Schema (${reason}), which the admin kit's field metadata needs: change that schema`,\n );\n }\n}\n\n/**\n * The entity's fields, in its schema's order, from its Standard JSON Schema.\n * Fails through `fail` for a schema that cannot describe itself, or that does\n * not describe an object with an `id`.\n */\nexport function entityFieldsOf(\n entity: StandardSchemaV1,\n fail: FieldsFailure,\n): readonly AdminEntityField[] {\n const json = entityJson(entity, fail);\n const root = rootObject(json);\n const properties = root?.properties;\n if (root === undefined || !isRecord(properties) || !Object.hasOwn(properties, \"id\")) {\n fail(\"the entity schema must describe an object with an id\");\n }\n const required = new Set(Array.isArray(root.required) ? root.required : []);\n const defs: Defs = { definitions: json.definitions, $defs: json.$defs };\n return Object.freeze(\n Object.entries(properties).map(([name, node]) => {\n const shape = shapeOf(node, defs);\n const defaulted = isRecord(node) && Object.hasOwn(node, \"default\");\n return Object.freeze({\n name,\n type: shape.type,\n required: required.has(name) && !shape.nullable && !defaulted,\n nullable: shape.nullable,\n enumValues:\n shape.enumValues === undefined ? undefined : Object.freeze([...shape.enumValues]),\n });\n }),\n );\n}\n\ntype Issues = StandardSchemaV1.Issue[];\n\n/** The first key of an issue's path. */\nfunction headOf(issue: StandardSchemaV1.Issue): PropertyKey | undefined {\n const [head] = issue.path ?? [];\n return typeof head === \"object\" ? head.key : head;\n}\n\nfunction quoted(names: readonly string[]): string {\n return names.length === 0 ? \"none\" : names.map((name) => `\"${name}\"`).join(\", \");\n}\n\n/**\n * The issues of a write's `data` at `path`: a key that is not one of\n * `writable` (the entity's fields but `id` and the timestamps), and a value\n * the entity schema refuses for its field. The entity schema checks the given\n * fields only: a field the write leaves out is the database's to fill.\n */\nexport async function dataIssues(\n entity: StandardSchemaV1,\n writable: readonly string[],\n data: unknown,\n path: readonly PropertyKey[],\n): Promise<Issues> {\n if (!isRecord(data)) {\n return [{ message: \"Expected an object of field values\", path: [...path] }];\n }\n const given = Object.keys(data).filter((key) => data[key] !== undefined);\n const refused = given.filter((key) => !writable.includes(key));\n if (refused.length > 0) {\n return refused.map((key) => ({\n message: ADMIN_NEVER_WRITABLE.includes(key)\n ? `\"${key}\" is not writable`\n : `\"${key}\" is not a writable field; the writable fields are ${quoted(writable)}`,\n path: [...path, key],\n }));\n }\n if (given.length === 0) {\n return [];\n }\n const result = await entity[\"~standard\"].validate(writtenData(data));\n const issues = (result.issues ?? []).filter((issue) => {\n const head = headOf(issue);\n return typeof head === \"string\" && given.includes(head);\n });\n return nested(issues, path);\n}\n\n/** The fields a write sets: `data` without its `undefined` values. */\nexport function writtenData(data: Readonly<Record<string, unknown>>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(data).filter(([, value]) => value !== undefined));\n}\n","// The inputs and outputs the admin kit generates (RFC 0003 section 12.4).\n//\n// `adminList` pages by number, as 4.1's did\n// (4.1 `src/server/BaseService.ts:1367-1388`): `page` from 1, `pageSize`\n// 20 by default and at most 100 (a larger one is clamped). Its filter and\n// sort are restricted to the fields the contract declares and checked as\n// the read/write kit's `list` checks them (`crudList.ts`): a filter is\n// equality on plain values, so nothing the caller sends reaches the database\n// as an operator. 4.1 handed the caller's `where` and `orderBy` to the\n// database as they came.\n//\n// A write's `data` holds field values of the entity: a key that is not one of\n// its fields, `id` and the timestamps are refused, and each value is checked\n// by the entity schema itself (`adminFields.ts`). A row out is the entity's\n// row, checked to have an id: the server leaves out the fields the caller's\n// level does not reach and those the service hides.\n\nimport type { AccessLevel } from \"../access\";\nimport type { SortDirection } from \"../collections\";\nimport type { StandardSchemaV1 } from \"../standardSchema\";\nimport { ADMIN_FIELD_TYPES, dataIssues, writtenData, type AdminServiceMeta } from \"./adminFields\";\nimport {\n filterIssues,\n filterSortJson,\n itemsIssues,\n sortIssues,\n type FilterValue,\n type ListFields,\n type ListSort,\n} from \"./crudList\";\nimport {\n idJson,\n invalid,\n isId,\n isRecord,\n jsonOf,\n kitSchema,\n objectJson,\n unknownKeys,\n type JsonSchema,\n type KitSchema,\n} from \"./schemas\";\n\n/** `adminList`'s page size when the caller gives none: 4.1's. */\nexport const ADMIN_DEFAULT_PAGE_SIZE = 20;\n\n/** The largest page `adminList` returns: a larger `pageSize` is clamped to it. */\nexport const ADMIN_MAX_PAGE_SIZE = 100;\n\n/** The highest page number `adminList` takes: past it the offset alone is a slow scan. */\nexport const ADMIN_MAX_PAGE = 1_000_000;\n\n/** What an `adminList` call passes: a page, and a filter and a sort over the declared fields. */\nexport type AdminListInput<Row, Filter extends string, Sort extends string> = {\n /** The page, from 1. Default 1. */\n readonly page?: number;\n /** The rows per page: default 20, at most 100 (a larger one is clamped). */\n readonly pageSize?: number;\n readonly filter?: [Filter] extends [never]\n ? undefined\n : { readonly [Field in Filter]?: Field extends keyof Row ? Row[Field] : never };\n readonly sort?: [Sort] extends [never] ? undefined : ListSort<Sort>;\n};\n\n/** `adminList`'s input as its handler receives it: defaults applied, the page size clamped. */\nexport interface AdminListQuery<Filter extends string = string, Sort extends string = string> {\n readonly page: number;\n /** At least 1 and at most {@link ADMIN_MAX_PAGE_SIZE}. */\n readonly pageSize: number;\n /** Equality per declared field; `{}` for none. */\n readonly filter: { readonly [Field in Filter]?: FilterValue };\n /** The caller's sort, or `undefined` for the default order. */\n readonly sort: { readonly field: Sort; readonly direction: SortDirection } | undefined;\n}\n\n/** One page of `adminList`, as 4.1's `AdminListResponse`. */\nexport interface AdminPage<Item> {\n readonly items: Item[];\n /** Every row the filter matches. */\n readonly total: number;\n readonly page: number;\n readonly pageSize: number;\n /** `ceil(total / pageSize)`. */\n readonly totalPages: number;\n}\n\n/** The fields no admin write sets: the row's key and its timestamps. */\nexport type AdminNeverWritable = \"id\" | \"createdAt\" | \"updatedAt\" | \"created_at\" | \"updated_at\";\n\n/** The fields an admin write sets without `editable`: any of the entity's fields but `id` and the timestamps. */\nexport type AdminWritable<Row> = Exclude<keyof Row, AdminNeverWritable>;\n\n/**\n * The field values an admin write may set: those of `Field`, the fields\n * `admin.contract({ editable })` names, else any of the entity's fields but\n * `id` and the timestamps.\n */\nexport type AdminData<Row, Field extends PropertyKey = AdminWritable<Row>> = {\n readonly [Name in Field & keyof Row]?: Row[Name];\n};\n\n/** `adminCreate`: the new row's field values. */\nexport interface AdminCreateInput<Row, Field extends PropertyKey = AdminWritable<Row>> {\n readonly data: AdminData<Row, Field>;\n}\n\n/** `adminUpdate`: the row, and the field values to change. */\nexport interface AdminUpdateInput<Row, Field extends PropertyKey = AdminWritable<Row>> {\n readonly id: string;\n readonly data: AdminData<Row, Field>;\n}\n\n/** `adminCreate`'s input as its handler receives it: `data` without `undefined` values. */\nexport interface AdminCreateQuery {\n readonly data: Readonly<Record<string, unknown>>;\n}\n\n/** `adminUpdate`'s input as its handler receives it. */\nexport interface AdminUpdateQuery {\n readonly id: string;\n readonly data: Readonly<Record<string, unknown>>;\n}\n\n/** `adminMeta` takes nothing: no input, or `{}`. */\nexport type AdminMetaInput = Readonly<Record<string, never>>;\n\n/** A level a subscriber holds a row at: one entity room per level (RFC 0003 section 6). */\nexport type SubscriberLevel = Exclude<AccessLevel, \"Public\">;\n\n/** What `adminSubscribers` and `adminReemit` return: the sockets subscribed to one row. */\nexport interface AdminSubscribers {\n readonly id: string;\n /** Sockets subscribed to the row, at every level. */\n readonly count: number;\n /** The same per level: the sockets in each of the row's tier rooms. */\n readonly levels: { readonly [Level in SubscriberLevel]: number };\n /**\n * `true` when the counts cover every server. Behind a cluster adapter\n * (Redis) a server sees only its own sockets, and this is `false`.\n */\n readonly complete: boolean;\n}\n\ntype Issues = StandardSchemaV1.Issue[];\n\ntype UnknownRecord = Readonly<Record<string, unknown>>;\n\nconst LEVELS: readonly SubscriberLevel[] = Object.freeze([\"Read\", \"Moderate\", \"Admin\"]);\n\nfunction isCount(value: unknown, minimum = 0): boolean {\n return Number.isInteger(value) && (value as number) >= minimum;\n}\n\nfunction pageIssues(value: UnknownRecord): Issues {\n const { page, pageSize } = value;\n const issues: Issues = [];\n if (page !== undefined && !(isCount(page, 1) && (page as number) <= ADMIN_MAX_PAGE)) {\n issues.push({ message: `Expected a page number from 1 to ${ADMIN_MAX_PAGE}`, path: [\"page\"] });\n }\n if (pageSize !== undefined && !isCount(pageSize, 1)) {\n issues.push({ message: \"Expected a whole number of at least 1\", path: [\"pageSize\"] });\n }\n return issues;\n}\n\n/** The parsed input of a valid `adminList` call. */\nfunction listQueryOf(value: UnknownRecord): AdminListQuery {\n const sort = value.sort as ListSort | undefined;\n const pageSize = (value.pageSize as number | undefined) ?? ADMIN_DEFAULT_PAGE_SIZE;\n return {\n page: (value.page as number | undefined) ?? 1,\n pageSize: Math.min(pageSize, ADMIN_MAX_PAGE_SIZE),\n filter: { ...(value.filter as Readonly<Record<string, FilterValue>> | undefined) },\n sort:\n sort === undefined ? undefined : { field: sort.field, direction: sort.direction ?? \"asc\" },\n };\n}\n\n/**\n * `adminList`'s input: `{ page?, pageSize?, filter?, sort? }`, or nothing.\n * `entity` gives the filter fields' JSON Schema.\n */\nexport function adminListInput<Input, Query extends AdminListQuery>(\n fields: ListFields,\n entity: StandardSchemaV1,\n): KitSchema<Input, Query> {\n return kitSchema<Input, Query>(\n (input) => {\n const value = input ?? {};\n if (!isRecord(value)) {\n return invalid(\"Expected an object\");\n }\n const issues = [\n ...unknownKeys(value, [\"page\", \"pageSize\", \"filter\", \"sort\"]),\n ...filterIssues(value.filter, fields.filter),\n ...sortIssues(value.sort, fields.sort),\n ...pageIssues(value),\n ];\n return issues.length > 0 ? { issues } : { value: listQueryOf(value) as Query };\n },\n {\n input: (target) =>\n objectJson({\n ...filterSortJson(fields, entity, target),\n page: { type: \"integer\", minimum: 1, maximum: ADMIN_MAX_PAGE, default: 1 },\n pageSize: {\n type: \"integer\",\n minimum: 1,\n maximum: ADMIN_MAX_PAGE_SIZE,\n default: ADMIN_DEFAULT_PAGE_SIZE,\n },\n }),\n },\n );\n}\n\n/** The entity's JSON Schema, or nothing when it cannot be written for `target`. */\nfunction entityJson(\n entity: StandardSchemaV1,\n side: \"input\" | \"output\",\n target: string,\n): JsonSchema {\n try {\n return jsonOf(entity, side, target) ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * The entity's row as JSON Schema, apart from the definitions its `$ref`s\n * point into, which the document holding it carries at its root. Nothing is\n * required: the server leaves out fields the caller may not see.\n */\nfunction rowJson(entity: StandardSchemaV1, target: string): { row: JsonSchema; defs: JsonSchema } {\n const { definitions, $defs, required: _required, ...row } = entityJson(entity, \"output\", target);\n return {\n row,\n defs: {\n ...(definitions === undefined ? {} : { definitions }),\n ...($defs === undefined ? {} : { $defs }),\n },\n };\n}\n\n/** The JSON Schema of a write's `data`: the writable fields' own schemas, none required. */\nfunction dataJson(\n entity: StandardSchemaV1,\n writable: readonly string[],\n target: string,\n): { data: JsonSchema; defs: JsonSchema } {\n const json = entityJson(entity, \"input\", target);\n const properties = isRecord(json.properties) ? json.properties : {};\n const fields = writable\n .filter((name) => Object.hasOwn(properties, name))\n .map((name) => [name, properties[name] as JsonSchema]);\n const { definitions, $defs } = json;\n return {\n data: objectJson(Object.fromEntries(fields) as Record<string, JsonSchema>),\n defs: {\n ...(definitions === undefined ? {} : { definitions }),\n ...($defs === undefined ? {} : { $defs }),\n },\n };\n}\n\n/** A write's input: `{ data }`, with `id` too for an update. */\nfunction writeInput<Input, Parsed>(\n entity: StandardSchemaV1,\n writable: readonly string[],\n withId: boolean,\n): KitSchema<Input, Parsed> {\n const keys = withId ? [\"id\", \"data\"] : [\"data\"];\n return kitSchema<Input, Parsed>(\n async (input) => {\n if (!isRecord(input)) {\n return invalid(withId ? \"Expected { id, data }\" : \"Expected { data }\");\n }\n const issues = [...unknownKeys(input, keys)];\n if (withId && !isId(input.id)) {\n issues.push({ message: \"Expected a non-empty string\", path: [\"id\"] });\n }\n issues.push(...(await dataIssues(entity, writable, input.data, [\"data\"])));\n if (issues.length > 0) {\n return { issues };\n }\n const data = writtenData(input.data as UnknownRecord);\n return { value: (withId ? { id: input.id, data } : { data }) as Parsed };\n },\n {\n input: (target) => {\n const { data, defs } = dataJson(entity, writable, target);\n const properties: Record<string, JsonSchema> = withId ? { id: idJson(), data } : { data };\n return { ...objectJson(properties, keys), ...defs };\n },\n },\n );\n}\n\n/** `adminCreate`'s input: `{ data }`, the new row's values of `writable` fields. */\nexport function adminCreateInput<Row, Field extends PropertyKey = AdminWritable<Row>>(\n entity: StandardSchemaV1,\n writable: readonly string[],\n): KitSchema<AdminCreateInput<Row, Field>, AdminCreateQuery> {\n return writeInput(entity, writable, false);\n}\n\n/** `adminUpdate`'s input: `{ id, data }`, the values of `writable` fields to change. */\nexport function adminUpdateInput<Row, Field extends PropertyKey = AdminWritable<Row>>(\n entity: StandardSchemaV1,\n writable: readonly string[],\n): KitSchema<AdminUpdateInput<Row, Field>, AdminUpdateQuery> {\n return writeInput(entity, writable, true);\n}\n\nfunction rowIssues(value: unknown): Issues {\n return isRecord(value) && isId(value.id)\n ? []\n : [{ message: \"Expected a row with an id\", path: [] }];\n}\n\n/** One row of the entity, as `adminGet`, `adminCreate` and `adminUpdate` return it. */\nexport function adminRowOutput<Row>(entity: StandardSchemaV1): KitSchema<Row> {\n return kitSchema<Row>(\n (value) => {\n const issues = rowIssues(value);\n return issues.length > 0 ? { issues } : { value: value as Row };\n },\n {\n input: (target) => {\n const { row, defs } = rowJson(entity, target);\n return { ...row, ...defs };\n },\n },\n );\n}\n\nfunction pageCountIssues(value: UnknownRecord): Issues {\n const minimums: readonly [string, number][] = [\n [\"total\", 0],\n [\"page\", 1],\n [\"pageSize\", 1],\n [\"totalPages\", 0],\n ];\n return minimums.flatMap(([key, minimum]) =>\n isCount(value[key], minimum)\n ? []\n : [{ message: `Expected a count of at least ${minimum}`, path: [key] }],\n );\n}\n\n/** One page of `adminList`: `{ items, total, page, pageSize, totalPages }`. */\nexport function adminPageOutput<Item>(entity: StandardSchemaV1): KitSchema<AdminPage<Item>> {\n return kitSchema<AdminPage<Item>>(\n (value) => {\n if (!isRecord(value)) {\n return invalid(\"Expected a page\");\n }\n const issues = [\n ...unknownKeys(value, [\"items\", \"total\", \"page\", \"pageSize\", \"totalPages\"]),\n ...itemsIssues(value.items),\n ...pageCountIssues(value),\n ];\n return issues.length > 0 ? { issues } : { value: value as unknown as AdminPage<Item> };\n },\n {\n input: (target) => {\n const { row, defs } = rowJson(entity, target);\n const count = (minimum: number): JsonSchema => ({ type: \"integer\", minimum });\n return {\n ...objectJson(\n {\n items: { type: \"array\", items: row },\n total: count(0),\n page: count(1),\n pageSize: { type: \"integer\", minimum: 1, maximum: ADMIN_MAX_PAGE_SIZE },\n totalPages: count(0),\n },\n [\"items\", \"total\", \"page\", \"pageSize\", \"totalPages\"],\n ),\n ...defs,\n };\n },\n },\n );\n}\n\n/** `adminMeta`'s input: nothing, or `{}`. */\nexport function adminMetaInput(): KitSchema<AdminMetaInput | undefined, undefined> {\n return kitSchema<AdminMetaInput | undefined, undefined>(\n (input) => {\n if (input === undefined) {\n return { value: undefined };\n }\n if (!isRecord(input)) {\n return invalid(\"Expected nothing, or {}\");\n }\n const issues = unknownKeys(input, []);\n return issues.length > 0 ? { issues } : { value: undefined };\n },\n { input: () => objectJson({}) },\n );\n}\n\nconst STRING: JsonSchema = Object.freeze({ type: \"string\" });\nconst BOOLEAN: JsonSchema = Object.freeze({ type: \"boolean\" });\n\nfunction fieldConfigJson(): JsonSchema {\n return objectJson(\n {\n name: STRING,\n type: { type: \"string\", enum: [...ADMIN_FIELD_TYPES] },\n label: STRING,\n required: BOOLEAN,\n editable: BOOLEAN,\n showInTable: BOOLEAN,\n sortable: BOOLEAN,\n filterable: BOOLEAN,\n enumValues: { type: \"array\", items: STRING },\n relationService: STRING,\n kind: { type: \"string\", enum: [\"grants\"] },\n showInForm: BOOLEAN,\n },\n [\"name\", \"type\", \"label\", \"required\", \"editable\", \"showInTable\", \"sortable\"],\n );\n}\n\nfunction fieldIssues(fields: unknown): Issues {\n if (!Array.isArray(fields)) {\n return [{ message: \"Expected an array of fields\", path: [\"fields\"] }];\n }\n return fields.flatMap((field: unknown, index): Issues => {\n const valid =\n isRecord(field) &&\n typeof field.name === \"string\" &&\n ADMIN_FIELD_TYPES.some((type) => type === field.type);\n return valid ? [] : [{ message: \"Expected a field's configuration\", path: [\"fields\", index] }];\n });\n}\n\n/** `adminMeta`'s output: the service's name, display name and field configurations. */\nexport function adminMetaOutput(): KitSchema<AdminServiceMeta> {\n return kitSchema<AdminServiceMeta>(\n (value) => {\n if (!isRecord(value)) {\n return invalid(\"Expected { serviceName, displayName, fields }\");\n }\n const issues = [...unknownKeys(value, [\"serviceName\", \"displayName\", \"fields\"])];\n for (const key of [\"serviceName\", \"displayName\"]) {\n if (typeof value[key] !== \"string\") {\n issues.push({ message: \"Expected a string\", path: [key] });\n }\n }\n issues.push(...fieldIssues(value.fields));\n return issues.length > 0 ? { issues } : { value: value as unknown as AdminServiceMeta };\n },\n {\n input: () =>\n objectJson(\n {\n serviceName: STRING,\n displayName: STRING,\n fields: { type: \"array\", items: fieldConfigJson() },\n },\n [\"serviceName\", \"displayName\", \"fields\"],\n ),\n },\n );\n}\n\nfunction levelsIssues(levels: unknown): Issues {\n const valid =\n isRecord(levels) &&\n Object.keys(levels).length === LEVELS.length &&\n LEVELS.every((level) => isCount(levels[level]));\n return valid ? [] : [{ message: \"Expected a count per level\", path: [\"levels\"] }];\n}\n\n/** What `adminSubscribers` and `adminReemit` return: `{ id, count, levels, complete }`. */\nexport function adminSubscribersOutput(): KitSchema<AdminSubscribers> {\n return kitSchema<AdminSubscribers>(\n (value) => {\n if (!isRecord(value)) {\n return invalid(\"Expected { id, count, levels, complete }\");\n }\n const issues = [\n ...unknownKeys(value, [\"id\", \"count\", \"levels\", \"complete\"]),\n ...(isId(value.id) ? [] : [{ message: \"Expected a row id\", path: [\"id\"] }]),\n ...(isCount(value.count) ? [] : [{ message: \"Expected a count\", path: [\"count\"] }]),\n ...levelsIssues(value.levels),\n ...(typeof value.complete === \"boolean\"\n ? []\n : [{ message: \"Expected a boolean\", path: [\"complete\"] }]),\n ];\n return issues.length > 0 ? { issues } : { value: value as unknown as AdminSubscribers };\n },\n {\n input: () =>\n objectJson(\n {\n id: idJson(),\n count: { type: \"integer\", minimum: 0 },\n levels: objectJson(\n Object.fromEntries(LEVELS.map((level) => [level, { type: \"integer\", minimum: 0 }])),\n LEVELS,\n ),\n complete: BOOLEAN,\n },\n [\"id\", \"count\", \"levels\", \"complete\"],\n ),\n },\n );\n}\n","// The admin kit's contract half (RFC 0003 section 12.4). `admin.contract`\n// returns ordinary `query` and `mutation` entries to spread into a\n// contract's `methods`: the back-office methods 4.1's `installAdminMethods`\n// registered outside the type map (4.1 `src/server/BaseService.ts:1185-1333`),\n// so every app called them through untyped hooks:\n//\n// export const task = defineContract(\"taskService\", {\n// entity: taskSchema,\n// methods: {\n// ...admin.contract({ entity: taskSchema, filter: [\"status\"], sort: [\"createdAt\", \"title\"] }),\n// rename: mutation({ ... }),\n// },\n// });\n//\n// `adminList` pages every row by page number; `adminGet`, `adminCreate`,\n// `adminUpdate` and `adminDelete` read and write one row; `adminMeta`\n// describes the entity's fields for an admin screen; `adminSubscribers`\n// counts the sockets subscribed to a row and `adminReemit` sends it to them\n// again. `expose` picks the methods to add; all eight without it. `editable`\n// (finding R1.4 of the 5.0.0 review) names the only fields `adminCreate` and\n// `adminUpdate` take, in their checks, their JSON Schema (and so the MCP\n// tools made from it) and their types; without it they take every field but\n// `id` and the timestamps. The entity schema must describe itself as JSON\n// Schema (Zod 4.2 or later): the fields come from it, so `admin.contract`\n// refuses a schema that cannot.\n//\n// The server half (`admin.handlers` on `./server`) finds the kit's entries in\n// the contract by what they were made for (`adminSpecOf`), its types by their\n// tag (`AdminTag`), and the client adds `qd.<service>.admin`, every admin\n// method's member in one place.\n\nimport type { AnyContract, RowSchema } from \"../defineContract\";\nimport type { MethodName } from \"../infer\";\nimport { mutation, query, type MethodDef, type MutationDef, type QueryDef } from \"../methods\";\nimport { isStandardSchema, type InferOutput, type StandardSchemaV1 } from \"../standardSchema\";\nimport {\n ADMIN_NEVER_WRITABLE,\n entityFieldsOf,\n type AdminEntityField,\n type AdminServiceMeta,\n} from \"./adminFields\";\nimport {\n adminCreateInput,\n adminListInput,\n adminMetaInput,\n adminMetaOutput,\n adminPageOutput,\n adminRowOutput,\n adminSubscribersOutput,\n adminUpdateInput,\n type AdminCreateInput,\n type AdminCreateQuery,\n type AdminListInput,\n type AdminListQuery,\n type AdminMetaInput,\n type AdminPage,\n type AdminSubscribers,\n type AdminUpdateInput,\n type AdminUpdateQuery,\n type AdminWritable,\n} from \"./adminSchemas\";\nimport type { ScalarFieldOf } from \"./crud\";\nimport { idInput, nullOutput, type IdInput } from \"./crudSchemas\";\nimport type { KitSchema } from \"./schemas\";\n\n/** The methods the admin kit can add. */\nexport type AdminMethodName =\n | \"adminList\"\n | \"adminGet\"\n | \"adminCreate\"\n | \"adminUpdate\"\n | \"adminDelete\"\n | \"adminMeta\"\n | \"adminSubscribers\"\n | \"adminReemit\";\n\n/** Every method of the admin kit, in the order `expose` defaults to. */\nexport const ADMIN_METHODS: readonly AdminMethodName[] = Object.freeze([\n \"adminList\",\n \"adminGet\",\n \"adminCreate\",\n \"adminUpdate\",\n \"adminDelete\",\n \"adminMeta\",\n \"adminSubscribers\",\n \"adminReemit\",\n]);\n\n/** Type-only: marks a method the admin kit made, and which one. Never set. */\nexport interface AdminTag<Kind extends AdminMethodName> {\n readonly \"~admin\"?: Kind;\n}\n\n/** The names of a contract's methods the admin kit made. */\nexport type AdminMethodsOf<C extends AnyContract> = {\n [M in MethodName<C>]: \"~admin\" extends keyof C[\"methods\"][M] ? M : never;\n}[MethodName<C>];\n\n/** `admin.contract`'s options. */\nexport interface AdminContractOptions {\n /** The contract's entity schema, which must describe itself as JSON Schema (Zod 4.2 or later). */\n readonly entity: RowSchema;\n /** The fields `adminList` may filter on, by equality. */\n readonly filter?: readonly string[];\n /** The fields `adminList` may sort by; the first is the default order (else `id`). */\n readonly sort?: readonly string[];\n /**\n * The only fields `adminCreate` and `adminUpdate` take (never `id` or a\n * timestamp): their input checks, JSON Schema and types name just these,\n * and the server half writes just these. Without it, every field but `id`\n * and the timestamps. `admin.handlers` given a list too must give the same.\n */\n readonly editable?: readonly string[];\n /** The methods to add; all eight when absent. */\n readonly expose?: readonly AdminMethodName[];\n /** Descriptions for people and agents, per method; the kit's own for the rest. */\n readonly describe?: { readonly [Name in AdminMethodName]?: string };\n}\n\ntype RowOf<Entity> = Entity extends StandardSchemaV1 ? InferOutput<Entity> : never;\n\ntype Quoted<Names> = `\"${Names & string}\"`;\n\ntype FieldsIn<O, Key extends \"filter\" | \"sort\" | \"editable\"> = O extends {\n readonly [K in Key]: readonly (infer Field extends string)[];\n}\n ? Field\n : never;\n\n/** A broken option becomes a message: replacing the whole option keeps TypeScript from printing `never`. */\ntype Problem<Option extends \"filter\" | \"sort\", Wrong> = [Wrong] extends [never]\n ? unknown\n : {\n readonly [K in Option]: `admin.contract: ${Option}: ${Quoted<Wrong>} is not a field of the entity holding strings, numbers or booleans`;\n };\n\n/** `editable` naming a field the kit never writes, as a message. */\ntype EditableProblem<Wrong> = [Wrong] extends [never]\n ? unknown\n : {\n readonly editable: `admin.contract: editable: ${Quoted<Wrong>} is not a field of the entity the kit may write`;\n };\n\n/** The check of `filter`, `sort` and `editable` against the entity that the option types alone cannot state. */\ntype AdminChecks<O> = O extends { readonly entity: infer Entity }\n ? Problem<\"filter\", Exclude<FieldsIn<O, \"filter\">, ScalarFieldOf<RowOf<Entity>>>> &\n Problem<\"sort\", Exclude<FieldsIn<O, \"sort\">, ScalarFieldOf<RowOf<Entity>>>> &\n EditableProblem<Exclude<FieldsIn<O, \"editable\">, AdminWritable<RowOf<Entity>>>>\n : unknown;\n\nexport type AdminListDef<Row, Filter extends string, Sort extends string> = QueryDef<\n KitSchema<AdminListInput<Row, Filter, Sort> | undefined, AdminListQuery<Filter, Sort>>,\n KitSchema<AdminPage<Row>>\n> &\n AdminTag<\"adminList\">;\nexport type AdminGetDef<Row> = QueryDef<KitSchema<IdInput>, KitSchema<Row>> & AdminTag<\"adminGet\">;\nexport type AdminCreateDef<Row, Field extends PropertyKey = AdminWritable<Row>> = MutationDef<\n KitSchema<AdminCreateInput<Row, Field>, AdminCreateQuery>,\n KitSchema<Row>\n> &\n AdminTag<\"adminCreate\">;\nexport type AdminUpdateDef<Row, Field extends PropertyKey = AdminWritable<Row>> = MutationDef<\n KitSchema<AdminUpdateInput<Row, Field>, AdminUpdateQuery>,\n KitSchema<Row>\n> &\n AdminTag<\"adminUpdate\">;\nexport type AdminDeleteDef = MutationDef<KitSchema<IdInput>, KitSchema<null>> &\n AdminTag<\"adminDelete\">;\nexport type AdminMetaDef = QueryDef<\n KitSchema<AdminMetaInput | undefined, undefined>,\n KitSchema<AdminServiceMeta>\n> &\n AdminTag<\"adminMeta\">;\nexport type AdminSubscribersDef = QueryDef<KitSchema<IdInput>, KitSchema<AdminSubscribers>> &\n AdminTag<\"adminSubscribers\">;\nexport type AdminReemitDef = MutationDef<KitSchema<IdInput>, KitSchema<AdminSubscribers>> &\n AdminTag<\"adminReemit\">;\n\ntype EntityRowIn<O> = O extends { readonly entity: infer Entity } ? RowOf<Entity> : never;\n\n/** The fields the writes take: those `editable` names, else every field but `id` and the timestamps. */\ntype EditableIn<O> = O extends { readonly editable: readonly (infer Field extends string)[] }\n ? Field\n : AdminWritable<EntityRowIn<O>>;\n\ntype AdminDefOf<O, Name extends AdminMethodName> = {\n adminList: AdminListDef<EntityRowIn<O>, FieldsIn<O, \"filter\">, FieldsIn<O, \"sort\">>;\n adminGet: AdminGetDef<EntityRowIn<O>>;\n adminCreate: AdminCreateDef<EntityRowIn<O>, EditableIn<O>>;\n adminUpdate: AdminUpdateDef<EntityRowIn<O>, EditableIn<O>>;\n adminDelete: AdminDeleteDef;\n adminMeta: AdminMetaDef;\n adminSubscribers: AdminSubscribersDef;\n adminReemit: AdminReemitDef;\n}[Name];\n\ntype ExposedIn<O> = O extends { readonly expose: readonly (infer Name extends AdminMethodName)[] }\n ? Name\n : AdminMethodName;\n\n/** The entries `admin.contract(options)` returns: one per method it adds. */\nexport type AdminMethods<O> = { readonly [Name in ExposedIn<O>]: AdminDefOf<O, Name> };\n\n/** What the server half and the client need to know about a method the admin kit made. */\nexport interface AdminSpec {\n readonly method: AdminMethodName;\n /** The entity schema the kit was made for: the contract's own, which the server half checks. */\n readonly entity: RowSchema;\n /** The fields `adminList` may filter on. */\n readonly filter: readonly string[];\n /** The fields `adminList` may sort by. */\n readonly sort: readonly string[];\n /** The entity's fields, from its JSON Schema, in its order. */\n readonly fields: readonly AdminEntityField[];\n /** The only fields the writes take, as `editable` named them; `undefined` without it. */\n readonly editable: readonly string[] | undefined;\n}\n\nconst SPECS = new WeakMap<object, AdminSpec>();\n\n/** What the admin kit made `method` for, or `undefined` for any other method. */\nexport function adminSpecOf(method: unknown): AdminSpec | undefined {\n return typeof method === \"object\" && method !== null ? SPECS.get(method) : undefined;\n}\n\nconst DESCRIBE: Readonly<Record<AdminMethodName, string>> = Object.freeze({\n adminList:\n \"Lists every row for a service administrator, a page at a time (page numbers from 1, at most 100 rows a page), filtered and sorted by the declared fields.\",\n adminGet: \"Reads one row by id, as a service administrator sees it.\",\n adminCreate:\n \"Creates a row from data, the new row's field values; the database sets its id and timestamps.\",\n adminUpdate: \"Changes the given fields of one row; its id and timestamps cannot be changed.\",\n adminDelete: \"Deletes one row.\",\n adminMeta:\n \"Describes the service's fields for an admin screen: their types, labels, and which can be edited, sorted and filtered.\",\n adminSubscribers: \"Counts the sockets subscribed to one row, per access level.\",\n adminReemit: \"Sends one row as it is now to every socket subscribed to it.\",\n});\n\ntype UnknownRecord = Readonly<Record<string, unknown>>;\n\nconst OPTIONS = [\"entity\", \"filter\", \"sort\", \"editable\", \"expose\", \"describe\"];\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction fail(message: string): never {\n throw new TypeError(`admin.contract: ${message}`);\n}\n\nfunction quoted(names: readonly string[]): string {\n return names.map((name) => `\"${name}\"`).join(\", \");\n}\n\nfunction checkOptions(options: unknown): UnknownRecord & { readonly entity: RowSchema } {\n if (!isRecord(options)) {\n fail(\"options must be { entity, filter?, sort?, editable?, expose?, describe? }\");\n }\n const unknownKey = Object.keys(options).find((key) => !OPTIONS.includes(key));\n if (unknownKey !== undefined) {\n fail(`unknown option \"${unknownKey}\"; the options are ${OPTIONS.join(\", \")}`);\n }\n if (!isStandardSchema(options.entity)) {\n fail(\"entity must be the contract's entity schema\");\n }\n return options as UnknownRecord & { readonly entity: RowSchema };\n}\n\n/** `filter` or `sort`: distinct fields of the entity holding strings, numbers or booleans. */\nfunction checkFields(\n owner: \"filter\" | \"sort\",\n names: unknown,\n fields: readonly AdminEntityField[],\n): readonly string[] {\n if (names === undefined) {\n return Object.freeze([]);\n }\n const valid =\n Array.isArray(names) &&\n names.every((name) => typeof name === \"string\") &&\n new Set(names).size === names.length;\n if (!valid) {\n fail(`${owner} must be a list of distinct field names`);\n }\n for (const name of names as string[]) {\n const field = fields.find((candidate) => candidate.name === name);\n if (field === undefined || field.type === \"json\") {\n fail(`${owner}: \"${name}\" is not a field of the entity holding strings, numbers or booleans`);\n }\n }\n return Object.freeze([...(names as string[])]);\n}\n\n/** `editable`: distinct fields of the entity the kit may write, or `undefined` without it. */\nfunction checkEditable(\n names: unknown,\n fields: readonly AdminEntityField[],\n): readonly string[] | undefined {\n if (names === undefined) {\n return undefined;\n }\n const valid =\n Array.isArray(names) &&\n names.every((name) => typeof name === \"string\") &&\n new Set(names).size === names.length;\n if (!valid) {\n fail(\"editable must be a list of distinct field names\");\n }\n for (const name of names as string[]) {\n if (ADMIN_NEVER_WRITABLE.includes(name)) {\n fail(`editable: \"${name}\" is never editable; the database sets it`);\n }\n if (!fields.some((field) => field.name === name)) {\n fail(`editable: \"${name}\" is not a field of the entity`);\n }\n }\n return Object.freeze([...(names as string[])]);\n}\n\n/** The methods the options add: those `expose` names, or all of them. */\nfunction exposedOf(expose: unknown): readonly AdminMethodName[] {\n if (expose === undefined) {\n return ADMIN_METHODS;\n }\n const valid =\n Array.isArray(expose) &&\n expose.length > 0 &&\n expose.every((name) => ADMIN_METHODS.some((known) => known === name)) &&\n new Set(expose).size === expose.length;\n if (!valid) {\n fail(`expose must name one or more distinct admin methods: ${quoted(ADMIN_METHODS)}`);\n }\n return expose as AdminMethodName[];\n}\n\n/** The descriptions the options give, each for a method they add. */\nfunction describedOf(names: readonly AdminMethodName[], describe: unknown): UnknownRecord {\n if (describe === undefined) {\n return {};\n }\n if (!isRecord(describe)) {\n fail(\"describe must map method names to descriptions\");\n }\n for (const [name, text] of Object.entries(describe)) {\n if (!names.some((added) => added === name)) {\n fail(`describe names \"${name}\", which these options do not add`);\n }\n if (typeof text !== \"string\" || text.length === 0) {\n fail(`describe for \"${name}\" must be a non-empty string`);\n }\n }\n return describe;\n}\n\n/** What every entry is made from: the entity, its fields, and the declared filter and sort fields. */\ntype SpecBase = Omit<AdminSpec, \"method\">;\n\n/** The entry of one admin method; `writable` are the fields its writes may set. */\nfunction build(\n name: AdminMethodName,\n base: SpecBase,\n writable: readonly string[],\n describe: string,\n): MethodDef {\n const { entity } = base;\n switch (name) {\n case \"adminList\":\n return query({\n input: adminListInput(base, entity),\n output: adminPageOutput(entity),\n describe,\n });\n case \"adminGet\":\n return query({ input: idInput(), output: adminRowOutput(entity), describe });\n case \"adminCreate\":\n return mutation({\n input: adminCreateInput(entity, writable),\n output: adminRowOutput(entity),\n describe,\n });\n case \"adminUpdate\":\n return mutation({\n input: adminUpdateInput(entity, writable),\n output: adminRowOutput(entity),\n describe,\n });\n case \"adminDelete\":\n return mutation({ input: idInput(), output: nullOutput(), describe });\n case \"adminMeta\":\n return query({ input: adminMetaInput(), output: adminMetaOutput(), describe });\n case \"adminSubscribers\":\n return query({ input: idInput(), output: adminSubscribersOutput(), describe });\n default:\n return mutation({ input: idInput(), output: adminSubscribersOutput(), describe });\n }\n}\n\nfunction contract<const O extends AdminContractOptions>(\n options: O & NoInfer<AdminChecks<O>>,\n): AdminMethods<O> {\n const checked = checkOptions(options);\n const { entity } = checked;\n const fields = entityFieldsOf(entity, fail);\n const editable = checkEditable(checked.editable, fields);\n const base: SpecBase = Object.freeze({\n entity,\n filter: checkFields(\"filter\", checked.filter, fields),\n sort: checkFields(\"sort\", checked.sort, fields),\n fields,\n editable,\n });\n const names = exposedOf(checked.expose);\n const described = describedOf(names, checked.describe);\n const writable =\n editable ??\n fields.map((field) => field.name).filter((field) => !ADMIN_NEVER_WRITABLE.includes(field));\n const methods: Record<string, MethodDef> = {};\n for (const name of names) {\n const own = described[name];\n const def = build(name, base, writable, typeof own === \"string\" ? own : DESCRIBE[name]);\n SPECS.set(def, Object.freeze({ ...base, method: name }));\n methods[name] = def;\n }\n return Object.freeze(methods) as unknown as AdminMethods<O>;\n}\n\n/**\n * The admin kit's contract half: `admin.contract({ entity, filter?, sort?,\n * editable?, expose?, describe? })` makes the admin methods, which the server half\n * (`admin.handlers` on `./server`) implements, each open to a service-wide\n * `Admin` grant unless the service says otherwise.\n */\nexport const admin = Object.freeze({ contract });\n\nexport type {\n AdminEntityField,\n AdminFieldConfig,\n AdminFieldType,\n AdminServiceMeta,\n EntityFieldType,\n} from \"./adminFields\";\n"],"mappings":";;;;;;AA0HO,SAAS,MAId,KAK4C;AAM5C,QAAM,SAAS;AAAA,IACb,MAAM;AAAA,IACN,OAAO,IAAI;AAAA,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