@tier0/sdk-v2 0.9.3 → 0.9.4

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 (43) hide show
  1. package/README.md +5 -5
  2. package/dist/cjs/data/bootstrap.js +4 -0
  3. package/dist/cjs/data/bootstrap.js.map +1 -1
  4. package/dist/cjs/data/client.d.ts +9 -4
  5. package/dist/cjs/data/client.js +26 -13
  6. package/dist/cjs/data/client.js.map +1 -1
  7. package/dist/cjs/data/collection.d.ts +8 -7
  8. package/dist/cjs/data/collection.js +4 -3
  9. package/dist/cjs/data/collection.js.map +1 -1
  10. package/dist/cjs/data/declarations.d.ts +1 -1
  11. package/dist/cjs/data/declarations.js.map +1 -1
  12. package/dist/cjs/data/define.d.ts +7 -0
  13. package/dist/cjs/data/define.js +4 -0
  14. package/dist/cjs/data/define.js.map +1 -1
  15. package/dist/cjs/data/schema.d.ts +4 -4
  16. package/dist/cjs/data/schema.js +26 -5
  17. package/dist/cjs/data/schema.js.map +1 -1
  18. package/dist/cjs/data/subscribe.d.ts +9 -8
  19. package/dist/cjs/data/subscribe.js +5 -11
  20. package/dist/cjs/data/subscribe.js.map +1 -1
  21. package/dist/esm/data/bootstrap.js +4 -0
  22. package/dist/esm/data/bootstrap.js.map +1 -1
  23. package/dist/esm/data/client.d.ts +9 -4
  24. package/dist/esm/data/client.js +26 -13
  25. package/dist/esm/data/client.js.map +1 -1
  26. package/dist/esm/data/collection.d.ts +8 -7
  27. package/dist/esm/data/collection.js +4 -3
  28. package/dist/esm/data/collection.js.map +1 -1
  29. package/dist/esm/data/declarations.d.ts +1 -1
  30. package/dist/esm/data/declarations.js.map +1 -1
  31. package/dist/esm/data/define.d.ts +7 -0
  32. package/dist/esm/data/define.js +3 -0
  33. package/dist/esm/data/define.js.map +1 -1
  34. package/dist/esm/data/schema.d.ts +4 -4
  35. package/dist/esm/data/schema.js +27 -6
  36. package/dist/esm/data/schema.js.map +1 -1
  37. package/dist/esm/data/subscribe.d.ts +9 -8
  38. package/dist/esm/data/subscribe.js +5 -11
  39. package/dist/esm/data/subscribe.js.map +1 -1
  40. package/package.json +1 -1
  41. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/SKILL.md +2 -2
  42. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/modeling.md +16 -0
  43. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"collection.js","sourceRoot":"","sources":["../../../src/data/collection.ts"],"names":[],"mappings":";;;AAwFA,8CAWC;AAED,sBAMC;AAqND,kDAeC;AAnUD,yCAAuC;AACvC,2CAA+D;AAC/D,uCAAgF;AAEhF,sDAAsD;AACzC,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC;;;GAGG;AACU,QAAA,gBAAgB,GAAG,GAAG,CAAC;AAgEpC,iEAAiE;AACjE,SAAgB,iBAAiB,CAAC,SAAiB,EAAE,KAAa;IAChE,IAAI,KAAK,GAAG,wBAAgB,EAAE,CAAC;QAC7B,MAAM,IAAI,oBAAS,CAAC;YAClB,OAAO,EACL,GAAG,SAAS,oBAAoB,wBAAgB,0BAA0B,KAAK,IAAI;gBACnF,kCAAkC,wBAAgB,4DAA4D;gBAC9G,iGAAiG;YACnG,MAAM,EAAE,GAAG;YACX,IAAI,EAAE,sBAAsB;SAC7B,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,SAAgB,KAAK,CAAI,MAAiB;IACxC,OAAO;QACL,GAAI,MAAM,CAAC,IAAU;QACrB,GAAG,EAAE,MAAM,CAAC,EAAE;QACd,KAAK,EAAE,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE;KAC/F,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAa,MAAM;IAOE;IANX,QAAQ,CAAQ;IAChB,UAAU,CAAU;IACpB,UAA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,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,CAAC;YACxC,YAAY,EAAE,MAAM,CAAC,YAAY,IAAI,CAAC;YACtC,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,CAAC;YACxC,YAAY,EAAE,MAAM,CAAC,YAAY,IAAI,CAAC;YACtC,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,CAAC;YACxC,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC;YAC5C,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC;SAC7C,CAAC;IACJ,CAAC;CACF;AAvfD,gCAufC","sourcesContent":["/**\n * Mongo-driver-style collection handle over the UNS record operations\n * (`recordFind`, `recordBulkWrite`, ...).\n *\n * Stored records `{ id, data, revision, createdAt, updatedAt }` are exposed as\n * flat documents `{ _id, ...data, _meta: { revision, createdAt, updatedAt } }`;\n * filters, sorts and projections use the same paths (`status`,\n * `customer.id`, `_id`, `_meta.updatedAt`).\n */\nimport type { UnsV2OperationName } from '../uns-v2/generated.js';\nimport type { CallOptions, DataCall } from './call.js';\nimport type { CollectionDefinition, RecordMeta } from './define.js';\nimport { DataError } from './error.js';\nimport { validateDocument, validateUpdate } from './schema.js';\nimport { toSortPairs, type Filter, type Sort, type SortPairs } from './sort.js';\n\n/** UNS page limit for find / aggregate / distinct. */\nexport const MAX_PAGE_SIZE = 200;\n\n/**\n * UNS commits at most 200 items in one synchronous atomic batch\n * (insertMany, bulkWrite, data.transact).\n */\nexport const MAX_ATOMIC_ITEMS = 200;\n\nexport type WithMeta<T> = T & { _id: string; _meta: RecordMeta };\n/** A projection may omit business fields at any depth; array and tuple containers retain their shape. */\nexport type DeepPartial<T> = T extends readonly unknown[]\n ? { [K in keyof T]: DeepPartial<T[K]> }\n : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;\nexport type Projection = Record<string, 0 | 1 | boolean>;\nexport type Update = Record<string, unknown>;\n\nexport interface UnsRecord {\n id: string;\n data: Record<string, unknown>;\n revision: number;\n createdAt: number;\n updatedAt: number;\n}\n\ninterface PageInfo {\n hasMore: boolean;\n nextCursor?: string | null;\n nextPage?: number | null;\n}\n\n/** Position of the next page: an opaque cursor or a 1-based offset page number. */\ntype PageToken = string | number;\n\ninterface Page<T> {\n items: T[];\n /** Token of the following page; null when this was the last one. */\n next: PageToken | null;\n}\n\ninterface WriteResult {\n matchedCount?: number;\n modifiedCount?: number;\n deletedCount?: number;\n insertedCount?: number;\n upsertedId?: string | null;\n insertedIds?: Record<string, string>;\n upsertedIds?: Record<string, string>;\n upsertedCount?: number;\n writeErrors?: unknown[];\n hasMore?: boolean;\n}\n\n/** A page of `updateMany` / `deleteMany`, the only writes that continue with `resumeAfter`. */\ninterface ManyPage extends WriteResult {\n resumeAfter?: string | null;\n}\n\n/** Runtime services a collection handle needs from its client. */\nexport interface CollectionRuntime {\n call: DataCall;\n /** Collection ID of a declaration or declared alias, ensuring all declarations first. */\n resolve(target: CollectionDefinition | string): Promise<string>;\n /** Runs a call, re-ensuring and retrying once when its collection ID went stale (see bootstrap). */\n recover<R>(fn: () => Promise<R>, options?: { retry?: boolean }): Promise<R>;\n /** Data subject of the request being served. */\n subject(): string | undefined;\n /** Abort signal of the request being served. */\n signal(): AbortSignal | undefined;\n}\n\n/** Rejects batches UNS would refuse, before anything is sent. */\nexport function assertAtomicBatch(operation: string, count: number) {\n if (count > MAX_ATOMIC_ITEMS) {\n throw new DataError({\n message:\n `${operation} commits at most ${MAX_ATOMIC_ITEMS} items atomically; got ${count}. ` +\n `Split the input into chunks of ${MAX_ATOMIC_ITEMS} (each chunk commits on its own; give each chunk a stable ` +\n 'idempotencyKey or fixed _ids so a retry is safe), or keep all-or-nothing work within one batch.',\n status: 400,\n code: 'BATCH_LIMIT_EXCEEDED',\n });\n }\n}\n\nexport function toDoc<T>(record: UnsRecord): WithMeta<T> {\n return {\n ...(record.data as T),\n _id: record.id,\n _meta: { revision: record.revision, createdAt: record.createdAt, updatedAt: record.updatedAt },\n };\n}\n\n/**\n * Async-iterable result set. Pages hold at most 200 items; the page source\n * decides whether the next page is reached by cursor or by offset page number.\n */\nexport class Cursor<T> implements AsyncIterable<T> {\n private sortSpec?: Sort;\n private limitCount?: number;\n private projection?: Projection;\n private started = false;\n\n constructor(\n private readonly fetchPage: (state: {\n token: PageToken | null;\n size: number;\n sort?: SortPairs;\n projection?: Projection;\n }) => Promise<Page<T>>,\n options: { sort?: Sort; limit?: number; projection?: Projection } = {},\n ) {\n this.sortSpec = options.sort;\n this.limitCount = options.limit;\n this.projection = options.projection;\n }\n\n private assertNotStarted() {\n if (this.started) throw new Error('Cursor options must be set before iteration starts.');\n }\n\n sort(sort: Sort): this {\n this.assertNotStarted();\n this.sortSpec = sort;\n return this;\n }\n\n /** Total number of documents to return (pages are fetched ≤200 at a time). */\n limit(count: number): this {\n this.assertNotStarted();\n this.limitCount = count;\n return this;\n }\n\n project(projection: Projection): this {\n this.assertNotStarted();\n this.projection = projection;\n return this;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n this.started = true;\n const sort = toSortPairs(this.sortSpec);\n let remaining = this.limitCount ?? Number.POSITIVE_INFINITY;\n // One page size for the whole iteration: offset pages are only stable when it never changes.\n const size = Math.min(MAX_PAGE_SIZE, remaining);\n let token: PageToken | null = null;\n while (remaining > 0) {\n const page = await this.fetchPage({ token, size, sort, projection: this.projection });\n for (const item of page.items.slice(0, remaining)) yield item;\n remaining -= page.items.length;\n if (page.next === null || page.items.length === 0) return;\n token = page.next;\n }\n }\n\n async toArray(): Promise<T[]> {\n const out: T[] = [];\n for await (const item of this) out.push(item);\n return out;\n }\n}\n\n/** Pipelines made only of `$match` / `$sort` page by cursor; UNS requires offset paging for any other stage. */\nfunction isDirectPipeline(stages: readonly Record<string, unknown>[]): boolean {\n return stages.every((stage) => Object.keys(stage).every((key) => key === '$match' || key === '$sort'));\n}\n\nexport interface FindOptions {\n sort?: Sort;\n limit?: number;\n projection?: Projection;\n}\n\nexport interface FindPageOptions {\n sort?: Sort;\n /** 1-based page number. */\n page?: number;\n /** At most 200. */\n pageSize?: number;\n projection?: Projection;\n /** Count matches up to this many (1–100000); UNS defaults to 10000. */\n maxCount?: number;\n}\n\n/** A match count UNS stopped at its limit: `capped` means \"at least `count`\". */\nexport interface CappedCount {\n count: number;\n capped: boolean;\n}\n\n/** UNS reads at most 100 records by ID per request. */\nexport const MAX_GET_IDS = 100;\n\nexport interface FoundPage<T> {\n items: WithMeta<T>[];\n total: CappedCount;\n page: number;\n pageSize: number;\n}\n\nexport interface ValueCount {\n value: unknown;\n count: number;\n}\n\ninterface RecordGetResult {\n items: UnsRecord[];\n missing: string[];\n}\n\n/** One read of `data.queryBatch`, built by `collection.query.*`. */\nexport interface BatchQuery<R> {\n readonly collection: CollectionDefinition;\n /** The batch item without `id` and `collectionId`; resolves `$lookup` targets. */\n prepare(): Promise<Record<string, unknown>>;\n /** The item's result as the builder's caller sees it. */\n parse(data: unknown): R;\n}\n\nexport interface CollectionQueries<T> {\n /** First page (≤200, default 20); `maxCount` adds the capped total of all matches. */\n find(filter?: Filter, options?: { sort?: Sort; limit?: number; projection?: Projection; maxCount?: number }):\n BatchQuery<{ items: WithMeta<T>[]; hasMore: boolean; total?: CappedCount }>;\n /** Like `collection.findPage`. */\n findPage(filter?: Filter, options?: FindPageOptions): BatchQuery<FoundPage<T>>;\n count(filter?: Filter, options?: { maxCount?: number }): BatchQuery<CappedCount>;\n /** The 200 most frequent values. */\n countBy(field: string, filter?: Filter): BatchQuery<ValueCount[]>;\n /** The first 200 distinct values. */\n distinct(field: string, filter?: Filter): BatchQuery<unknown[]>;\n /** The first 200 output rows. */\n aggregate<R = Record<string, unknown>>(pipeline: Record<string, unknown>[]): BatchQuery<R[]>;\n /** 1–100 distinct records by ID, as `collection.get`. */\n get(ids: readonly string[], options?: { projection?: Projection }): BatchQuery<{ items: WithMeta<T>[]; missing: string[] }>;\n}\n\nexport interface UpdateOptions {\n upsert?: boolean;\n /** Reject the write with VERSION_CONFLICT unless the record is at this revision. */\n expectedRevision?: number;\n sort?: Sort;\n arrayFilters?: Record<string, unknown>[];\n idempotencyKey?: string;\n}\n\nexport interface FindOneAndOptions extends UpdateOptions {\n returnDocument?: 'before' | 'after';\n projection?: Projection;\n}\n\nexport type InsertOneOptions = { idempotencyKey?: string } & (\n | { returnDocument?: 'none'; projection?: never }\n | { returnDocument: 'after'; projection?: Projection }\n);\n\nexport type BulkOperation =\n | { insertOne: { document: Record<string, unknown> } }\n | { updateOne: { filter: Filter; update: Update; upsert?: boolean; sort?: Sort } }\n | { replaceOne: { filter: Filter; replacement: Record<string, unknown>; upsert?: boolean; sort?: Sort } }\n | { deleteOne: { filter: Filter; sort?: Sort } };\n\nfunction compact<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n\nfunction filterOrNothing(filter: Filter): Filter | undefined {\n return Object.keys(filter).length > 0 ? filter : undefined;\n}\n\n/** `recordAggregatePipeline` body of one numbered page with its capped total. */\nfunction pageRequest(filter: Filter, options: FindPageOptions) {\n const page = Math.max(1, Math.trunc(options.page ?? 1));\n const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(1, Math.trunc(options.pageSize ?? 20)));\n const pipeline: Record<string, unknown>[] = [];\n if (Object.keys(filter).length > 0) pipeline.push({ $match: filter });\n const sort = toSortPairs(options.sort);\n if (sort) pipeline.push({ $sort: sort });\n if (options.projection) pipeline.push({ $project: options.projection });\n const body = { pipeline, page: { mode: 'offset', page, size: pageSize }, count: options.maxCount === undefined ? {} : { max: options.maxCount } };\n return { body, page, pageSize };\n}\n\nfunction countByPipeline(field: string, filter: Filter): Record<string, unknown>[] {\n const pipeline: Record<string, unknown>[] = [];\n if (Object.keys(filter).length > 0) pipeline.push({ $match: filter });\n // `_id` breaks ties, so offset pages of equal counts neither repeat nor skip a group.\n pipeline.push({ $group: { _id: `$${field}`, count: { $sum: 1 } } }, { $sort: { count: -1, _id: 1 } });\n return pipeline;\n}\n\nconst toValueCount = (row: { _id: unknown; count: number }): ValueCount => ({ value: row._id ?? null, count: row.count });\n\nfunction idsInOrder(ids: Record<string, string> | undefined): string[] {\n return Object.entries(ids ?? {})\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([, id]) => id);\n}\n\n/**\n * Atomic batches pass no `committed` counts: their write errors rolled the\n * whole batch back. Non-atomic runs pass their cumulative counts; `details`\n * then has the shape `partialWrite` uses.\n */\nexport function assertNoWriteErrors(result: ManyPage, operation: string, committed?: Record<string, number>) {\n if (result.writeErrors && result.writeErrors.length > 0) {\n const counts = Object.entries(committed ?? {}).map(([name, value]) => `${name}=${value}`).join(', ');\n const changed = committed !== undefined && Object.values(committed).some((value) => value > 0);\n throw new DataError({\n message: `${operation} stopped on ${result.writeErrors.length} write error(s)${counts ? `; already committed: ${counts}` : ''}.`,\n status: 409,\n code: 'WRITE_ERRORS',\n execution: changed ? 'committed' : 'rolledBack',\n attempts: 1,\n details: committed\n ? { ...committed, status: changed ? 'partiallyCommitted' : 'failed', hasMore: Boolean(result.hasMore), resumeAfter: result.resumeAfter ?? null, writeErrors: result.writeErrors }\n : { writeErrors: result.writeErrors },\n });\n }\n}\n\n/**\n * A non-atomic run failed after some writes committed: on an earlier page, or\n * within the failed page (UNS then answers `execution: \"committed\"` with the\n * page's partial result as `data`). Like UNS, the error keeps its code and is\n * `committed` with `retry.safe: false`; `details` is the cumulative result\n * of the whole call in the shape of a success (`matchedCount` …, `status:\n * \"partiallyCommitted\"`, `hasMore`, `resumeAfter`). Continue by passing\n * `resumeAfter` back; repeating the call would apply `$inc` / `$push` twice.\n */\nfunction partialWrite(operation: string, totals: Record<string, number>, resumeAfter: string | undefined, cause: DataError): DataError {\n const counts = Object.entries(totals).map(([name, value]) => `${name}=${value}`).join(', ');\n const writeErrors = Array.isArray(cause.details.writeErrors) ? { writeErrors: cause.details.writeErrors } : {};\n return new DataError({\n message:\n `${operation} committed ${counts} and then failed: ${cause.message} ` +\n (resumeAfter\n ? `Continue with { resumeAfter: details.resumeAfter }${cause.outcomeUnknown ? ' after checking the failed page, whose outcome is unknown' : ''}; do not repeat the whole call.`\n : 'Read back what changed before writing again; do not repeat the whole call.'),\n status: cause.status,\n code: cause.code,\n reason: cause.reason,\n upstreamStatus: cause.upstreamStatus,\n requestId: cause.requestId,\n // Earlier writes took effect; the failed page too, perhaps, when its outcome is unknown.\n execution: cause.outcomeUnknown ? 'unknown' : 'committed',\n retry: { safe: false },\n attempts: cause.attempts,\n details: { ...totals, status: 'partiallyCommitted', hasMore: true, resumeAfter: resumeAfter ?? null, ...writeErrors },\n cause,\n });\n}\n\nexport class Collection<T extends object = Record<string, unknown>, TInput extends object = T> {\n constructor(\n readonly definition: CollectionDefinition,\n private readonly runtime: CollectionRuntime,\n ) {}\n\n get alias(): string {\n return this.definition.alias;\n }\n\n /**\n * One call with stale-ID recovery. A call continuing a cursor or\n * resumeAfter token of the old collection is not retried: the token means\n * nothing to a recreated collection.\n */\n private post<R>(operation: UnsV2OperationName, body: Record<string, unknown>, options: CallOptions = {}): Promise<R> {\n const page = body.page as { cursor?: unknown } | undefined;\n const continues = typeof body.cursor === 'string' || typeof body.resumeAfter === 'string' || typeof page?.cursor === 'string';\n return this.runtime.recover(() => this.send<R>(operation, body, options), { retry: !continues });\n }\n\n private async send<R>(operation: UnsV2OperationName, body: Record<string, unknown>, options: CallOptions = {}): Promise<R> {\n const collectionId = await this.runtime.resolve(this.definition);\n return this.runtime.call<R>(operation, { collectionId, ...compact(body) }, {\n dataSubject: this.runtime.subject(),\n signal: this.runtime.signal(),\n ...options,\n });\n }\n\n /* ---------------------------------- reads --------------------------------- */\n\n find(filter: Filter = {}, options: FindOptions = {}): Cursor<WithMeta<T>> {\n return new Cursor<WithMeta<T>>(async ({ token, size, sort, projection }) => {\n const result = await this.post<{ items: UnsRecord[]; pageInfo: PageInfo }>('recordFind', {\n filter: Object.keys(filter).length > 0 ? filter : undefined,\n sort,\n projection,\n limit: size,\n cursor: typeof token === 'string' ? token : undefined,\n });\n return {\n items: result.items.map((record) => toDoc<T>(record)),\n next: result.pageInfo.hasMore && result.pageInfo.nextCursor ? result.pageInfo.nextCursor : null,\n };\n }, options);\n }\n\n async findOne(filter: Filter = {}, options: Omit<FindOptions, 'limit'> = {}): Promise<WithMeta<T> | null> {\n const [first] = await this.find(filter, { ...options, limit: 1 }).toArray();\n return first ?? null;\n }\n\n /**\n * Records by ID, in the order asked for (each ID once, at its first\n * position); IDs that do not exist, are deleted or are hidden by employee\n * data rules are listed in `missing` alike. More than 100 IDs are read in\n * chunks of 100 (not one snapshot).\n */\n async get(ids: readonly string[], options: { projection?: Projection } = {}): Promise<{ items: WithMeta<T>[]; missing: string[] }> {\n const unique = [...new Set(ids)];\n const chunks: string[][] = [];\n for (let start = 0; start < unique.length; start += MAX_GET_IDS) chunks.push(unique.slice(start, start + MAX_GET_IDS));\n const results = await Promise.all(chunks.map((chunk) =>\n this.post<RecordGetResult>('recordGet', { ids: chunk, projection: options.projection })));\n return {\n items: results.flatMap((result) => result.items.map((record) => toDoc<T>(record))),\n missing: results.flatMap((result) => result.missing),\n };\n }\n\n /**\n * One numbered page plus the total match count, for paged list screens:\n * one `recordAggregatePipeline` offset page whose `count` runs in the same\n * snapshot. Show a capped total as \"10000+\".\n */\n async findPage(filter: Filter = {}, options: FindPageOptions = {}): Promise<FoundPage<T>> {\n const { body, page, pageSize } = pageRequest(filter, options);\n const result = await this.post<{ items: WithMeta<T>[]; total: CappedCount }>('recordAggregatePipeline', body);\n return { items: result.items, total: result.total, page, pageSize };\n }\n\n /**\n * Counts matches up to `maxCount` (1–100000, UNS default 100000). A\n * `capped` result means \"at least `count`\".\n */\n async countDocuments(filter: Filter = {}, options: { maxCount?: number } = {}): Promise<CappedCount> {\n const result = await this.post<CappedCount>('recordCount', { filter: filterOrNothing(filter), maxCount: options.maxCount });\n return { count: result.count, capped: result.capped };\n }\n\n /**\n * Match counts per value of `field`, largest first: one `$group` pipeline\n * instead of a count per value. Records without the field count under\n * `value: null`.\n */\n async countBy(field: string, filter: Filter = {}): Promise<ValueCount[]> {\n const rows = await this.aggregate<{ _id: unknown; count: number }>(countByPipeline(field, filter)).toArray();\n return rows.map(toValueCount);\n }\n\n /**\n * Builders for `data.queryBatch`: each describes one read of this\n * collection, run together with the others in one request and one\n * snapshot. Each returns one page (at most 200 rows), unlike the cursor\n * methods; `get` takes at most 100 IDs.\n */\n get query(): CollectionQueries<T> {\n const one = <R>(op: string, build: () => Promise<Record<string, unknown>>, parse: (data: never) => R): BatchQuery<R> => ({\n collection: this.definition,\n prepare: async () => ({ op, ...compact(await build()) }),\n parse: parse as (data: unknown) => R,\n });\n return {\n find: (filter = {}, options = {}) =>\n one('find', async () => ({\n filter: filterOrNothing(filter),\n sort: toSortPairs(options.sort),\n projection: options.projection,\n limit: Math.min(MAX_PAGE_SIZE, options.limit ?? 20),\n count: options.maxCount === undefined ? undefined : { max: options.maxCount },\n }), (data: { items: UnsRecord[]; pageInfo: PageInfo; total?: CappedCount }) => ({\n items: data.items.map((record) => toDoc<T>(record)),\n hasMore: data.pageInfo.hasMore,\n ...(data.total ? { total: data.total } : {}),\n })),\n findPage: (filter = {}, options = {}) => {\n const { body, page, pageSize } = pageRequest(filter, options);\n return one('aggregate', async () => body, (data: { items: WithMeta<T>[]; total: CappedCount }) => ({\n items: data.items, total: data.total, page, pageSize,\n }));\n },\n count: (filter = {}, options = {}) =>\n one('count', async () => ({ filter: filterOrNothing(filter), maxCount: options.maxCount }),\n (data: CappedCount) => ({ count: data.count, capped: data.capped })),\n countBy: (field, filter = {}) =>\n one('aggregate', async () => ({\n pipeline: await this.prepareStages(countByPipeline(field, filter)),\n page: { mode: 'offset', page: 1, size: MAX_PAGE_SIZE },\n }), (data: { items: { _id: unknown; count: number }[] }) => data.items.map(toValueCount)),\n distinct: (field, filter = {}) =>\n one('distinct', async () => ({ field, filter: filterOrNothing(filter), page: { mode: 'offset', page: 1, size: MAX_PAGE_SIZE } }),\n (data: { values: unknown[] }) => data.values),\n aggregate: <R = Record<string, unknown>>(pipeline: Record<string, unknown>[]) =>\n one('aggregate', async () => {\n const stages = await this.prepareStages(pipeline);\n const last = stages[stages.length - 1];\n // A final $count returns one row and forbids an explicit page.\n return last !== undefined && '$count' in last\n ? { pipeline: stages }\n : { pipeline: stages, page: isDirectPipeline(stages) ? { mode: 'cursor', size: MAX_PAGE_SIZE } : { mode: 'offset', page: 1, size: MAX_PAGE_SIZE } };\n }, (data: { items: R[] }) => data.items),\n get: (ids, options = {}) => {\n const unique = [...new Set(ids)];\n if (unique.length < 1 || unique.length > MAX_GET_IDS) {\n throw new TypeError(`query.get takes 1–${MAX_GET_IDS} distinct IDs; use collection.get for more.`);\n }\n return one('get', async () => ({ ids: unique, projection: options.projection }),\n (data: RecordGetResult) => ({ items: data.items.map((record) => toDoc<T>(record)), missing: data.missing }));\n },\n };\n }\n\n /** Distinct values of a field (every page). */\n async distinct(field: string, filter: Filter = {}): Promise<unknown[]> {\n const values: unknown[] = [];\n for (let page = 1; ; page += 1) {\n const result = await this.post<{ items: { _id: unknown }[]; pageInfo: PageInfo }>('recordAggregatePipeline', {\n pipeline: [{ $match: filter }, { $group: { _id: `$${field}` } }],\n page: { mode: 'offset', page, size: MAX_PAGE_SIZE },\n });\n values.push(...result.items.map(item => item._id));\n if (!result.pageInfo.hasMore) return values;\n }\n }\n\n /**\n * Runs a pipeline (`$match`, `$sort`, `$group`, `$project`, `$set`,\n * `$lookup`, `$unwind`, `$skip`, `$limit`, `$count`). `$sort` accepts\n * `{ field: 1 | -1 }`; `$lookup` takes `from` (a declared collection or\n * alias of this App) instead of a collection ID. Rows are whatever the\n * pipeline outputs, not wrapped records.\n *\n * Pipelines of only `$match` / `$sort` page by cursor; any other stage pages\n * by offset (UNS rejects cursors for transformed results). The `$exists`,\n * `$distinct` and `$frequencies` stages are listed in the UNS schema but not\n * executed by the record pipeline; use `countDocuments`, `distinct` or `$group`.\n */\n aggregate<R = Record<string, unknown>>(pipeline: Record<string, unknown>[]): Cursor<R> {\n // Recovery wraps stage preparation too, so a retry re-resolves `$lookup` IDs.\n return new Cursor<R>(({ token, size }) => this.runtime.recover(() => this.aggregatePage<R>(pipeline, token, size), { retry: typeof token !== 'string' }));\n }\n\n private async aggregatePage<R>(\n pipeline: Record<string, unknown>[],\n token: PageToken | null,\n size: number,\n ): Promise<Page<R>> {\n const stages = await this.prepareStages(pipeline);\n const last = stages[stages.length - 1];\n if (last !== undefined && '$count' in last) {\n // A final $count returns one row and forbids an explicit page.\n const result = await this.send<{ items: R[] }>('recordAggregatePipeline', { pipeline: stages });\n return { items: result.items, next: null };\n }\n if (isDirectPipeline(stages)) {\n const result = await this.send<{ items: R[]; pageInfo: PageInfo }>('recordAggregatePipeline', {\n pipeline: stages,\n page: { mode: 'cursor', size, ...(typeof token === 'string' ? { cursor: token } : {}) },\n });\n return { items: result.items, next: result.pageInfo.hasMore && result.pageInfo.nextCursor ? result.pageInfo.nextCursor : null };\n }\n const page = typeof token === 'number' ? token : 1;\n const result = await this.send<{ items: R[]; pageInfo: PageInfo }>('recordAggregatePipeline', {\n pipeline: stages,\n page: { mode: 'offset', page, size },\n });\n return {\n items: result.items,\n next: result.pageInfo.hasMore ? (result.pageInfo.nextPage ?? page + 1) : null,\n };\n }\n\n /** Converts Mongo-style `$sort` objects and resolves `$lookup.from`, recursively. */\n private async prepareStages(pipeline: readonly Record<string, unknown>[]): Promise<Record<string, unknown>[]> {\n return Promise.all(\n pipeline.map(async (stage) => {\n if ('$sort' in stage && !Array.isArray(stage.$sort)) {\n return { ...stage, $sort: toSortPairs(stage.$sort as Sort) };\n }\n if ('$lookup' in stage && stage.$lookup && typeof stage.$lookup === 'object') {\n const { from, pipeline: inner, ...lookup } = stage.$lookup as Record<string, unknown>;\n const resolved: Record<string, unknown> = { ...lookup };\n if (from !== undefined) resolved.collectionId = await this.runtime.resolve(from as CollectionDefinition | string);\n if (Array.isArray(inner)) resolved.pipeline = await this.prepareStages(inner as Record<string, unknown>[]);\n return { ...stage, $lookup: resolved };\n }\n return stage;\n }),\n );\n }\n\n /* --------------------------------- writes --------------------------------- */\n\n /** Returns the creation snapshot in the same write; replay preserves that snapshot and requires current read access. */\n async insertOne(document: TInput & { _id?: string }, options: Extract<InsertOneOptions, { returnDocument: 'after' }> & { projection?: never }): Promise<{ insertedId: string; value: WithMeta<T> }>;\n async insertOne(document: TInput & { _id?: string }, options: Extract<InsertOneOptions, { returnDocument: 'after' }>): Promise<{ insertedId: string; value: WithMeta<DeepPartial<T>> }>;\n async insertOne(document: TInput & { _id?: string }, options?: Extract<InsertOneOptions, { returnDocument?: 'none' }>): Promise<{ insertedId: string }>;\n async insertOne(document: TInput & { _id?: string }, options: InsertOneOptions): Promise<{ insertedId: string; value?: WithMeta<DeepPartial<T>> }>;\n async insertOne(document: TInput & { _id?: string }, options: InsertOneOptions = {}): Promise<{ insertedId: string; value?: WithMeta<T> | WithMeta<DeepPartial<T>> }> {\n const { id, data } = validateDocument(this.definition, document as Record<string, unknown>);\n const result = await this.post<{ insertedId: string; value: UnsRecord }>('recordInsertOne', {\n id, data, idempotencyKey: options.idempotencyKey, returnDocument: options.returnDocument, projection: options.projection,\n });\n if (options.returnDocument === 'after') return { insertedId: result.insertedId, value: toDoc<T>(result.value) };\n return { insertedId: result.insertedId };\n }\n\n /** Inserts up to 200 documents atomically (all or none). */\n async insertMany(\n documents: readonly (TInput & { _id?: string })[],\n options: { idempotencyKey?: string } = {},\n ): Promise<{ insertedCount: number; insertedIds: string[] }> {\n if (documents.length === 0) return { insertedCount: 0, insertedIds: [] };\n assertAtomicBatch('insertMany', documents.length);\n const prepared = documents.map((document) => validateDocument(this.definition, document as Record<string, unknown>));\n const result = await this.post<WriteResult>('recordBulkWrite', {\n operations: prepared.map(({ id, data }) => ({ insertOne: compact({ id, data }) })),\n ordered: true,\n atomic: true,\n idempotencyKey: options.idempotencyKey,\n });\n assertNoWriteErrors(result, 'insertMany');\n return { insertedCount: result.insertedCount ?? 0, insertedIds: idsInOrder(result.insertedIds) };\n }\n\n async updateOne(\n filter: Filter,\n update: Update,\n options: UpdateOptions = {},\n ): Promise<{ matchedCount: number; modifiedCount: number; upsertedId: string | null }> {\n const result = await this.post<WriteResult>('recordUpdateOne', {\n filter,\n update: validateUpdate(this.definition, update),\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n arrayFilters: options.arrayFilters,\n idempotencyKey: options.idempotencyKey,\n });\n return { matchedCount: result.matchedCount ?? 0, modifiedCount: result.modifiedCount ?? 0, upsertedId: result.upsertedId ?? null };\n }\n\n /**\n * Updates every match like Mongo's updateMany: documents commit one by one\n * (not atomically), following `resumeAfter` until every match is processed.\n * A failure after some documents committed keeps its code but is\n * `execution: \"committed\"`, with the cumulative counts and\n * `details.resumeAfter`; pass that back as `resumeAfter` to continue\n * instead of repeating the call. For all-or-nothing multi-document changes\n * use `data.transact` (≤200 items).\n */\n async updateMany(\n filter: Filter,\n update: Update,\n options: Pick<UpdateOptions, 'arrayFilters'> & { resumeAfter?: string } = {},\n ): Promise<{ matchedCount: number; modifiedCount: number }> {\n const validated = validateUpdate(this.definition, update);\n let matchedCount = 0;\n let modifiedCount = 0;\n await this.writeEach('updateMany', 'recordUpdateMany', { filter, update: validated, arrayFilters: options.arrayFilters }, options.resumeAfter, (result) => {\n matchedCount += result.matchedCount ?? 0;\n modifiedCount += result.modifiedCount ?? 0;\n return { matchedCount, modifiedCount };\n });\n return { matchedCount, modifiedCount };\n }\n\n /** Runs a non-atomic many-write page by page; see updateMany for failures. */\n private async writeEach(\n name: string,\n operation: UnsV2OperationName,\n body: Record<string, unknown>,\n from: string | undefined,\n add: (result: WriteResult) => Record<string, number>,\n ): Promise<void> {\n let resumeAfter = from;\n let committed: Record<string, number> | undefined;\n do {\n let result: ManyPage;\n try {\n result = await this.post<ManyPage>(operation, { ...body, atomic: false, resumeAfter });\n } catch (error) {\n if (!(error instanceof DataError)) throw error;\n // UNS reports what the failed page itself committed, with where to continue.\n const page = error.execution === 'committed' ? (error.details as ManyPage) : undefined;\n const totals = page ? add(page) : committed;\n // Nothing of this call took effect: the page's own error tells the truth.\n if (!totals || !Object.values(totals).some((value) => value > 0)) throw error;\n throw partialWrite(name, totals, page ? (page.resumeAfter ?? undefined) : resumeAfter, error);\n }\n committed = add(result);\n assertNoWriteErrors(result, name, committed);\n resumeAfter = result.hasMore && result.resumeAfter ? result.resumeAfter : undefined;\n } while (resumeAfter);\n }\n\n /**\n * Replaces the whole body. Fields written by another App version and not in\n * this declaration are lost — prefer `updateOne` with `$set`.\n */\n async replaceOne(\n filter: Filter,\n replacement: TInput,\n options: Omit<UpdateOptions, 'arrayFilters'> = {},\n ): Promise<{ matchedCount: number; modifiedCount: number; upsertedId: string | null }> {\n const { data } = validateDocument(this.definition, replacement as Record<string, unknown>);\n const result = await this.post<WriteResult>('recordReplaceOne', {\n filter,\n replacement: data,\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n idempotencyKey: options.idempotencyKey,\n });\n return { matchedCount: result.matchedCount ?? 0, modifiedCount: result.modifiedCount ?? 0, upsertedId: result.upsertedId ?? null };\n }\n\n /** Soft-deletes one record; requires `uns.delete` on the App key. */\n async deleteOne(filter: Filter, options: Pick<UpdateOptions, 'expectedRevision' | 'sort' | 'idempotencyKey'> = {}): Promise<{ deletedCount: number }> {\n const result = await this.post<WriteResult>(\n 'recordDeleteOne',\n { filter, expectedRevision: options.expectedRevision, sort: toSortPairs(options.sort), idempotencyKey: options.idempotencyKey },\n );\n return { deletedCount: result.deletedCount ?? 0 };\n }\n\n /**\n * Soft-deletes every match, one document at a time like Mongo's deleteMany\n * (not atomic), following `resumeAfter`; requires `uns.delete` on the App\n * key. Failures after committed deletes report them as updateMany does.\n */\n async deleteMany(filter: Filter, options: { resumeAfter?: string } = {}): Promise<{ deletedCount: number }> {\n let deletedCount = 0;\n await this.writeEach('deleteMany', 'recordDeleteMany', { filter }, options.resumeAfter, (result) => {\n deletedCount += result.deletedCount ?? 0;\n return { deletedCount };\n });\n return { deletedCount };\n }\n\n /**\n * Atomic read-modify-write. A state transition puts the expected state in\n * the filter: `findOneAndUpdate({ _id, status: \"DRAFT\" }, { $set: { status: \"SUBMITTED\" } })`\n * returns null when another request moved the record first.\n */\n async findOneAndUpdate(filter: Filter, update: Update, options: FindOneAndOptions = {}): Promise<WithMeta<T> | null> {\n const result = await this.post<{ value: UnsRecord | null }>('recordUpdateOne', {\n filter,\n update: validateUpdate(this.definition, update),\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n arrayFilters: options.arrayFilters,\n returnDocument: options.returnDocument ?? 'after',\n projection: options.projection,\n idempotencyKey: options.idempotencyKey,\n });\n return result.value ? toDoc<T>(result.value) : null;\n }\n\n async findOneAndReplace(\n filter: Filter,\n replacement: TInput,\n options: Omit<FindOneAndOptions, 'arrayFilters'> = {},\n ): Promise<WithMeta<T> | null> {\n const { data } = validateDocument(this.definition, replacement as Record<string, unknown>);\n const result = await this.post<{ value: UnsRecord | null }>('recordReplaceOne', {\n filter,\n replacement: data,\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n returnDocument: options.returnDocument ?? 'after',\n projection: options.projection,\n idempotencyKey: options.idempotencyKey,\n });\n return result.value ? toDoc<T>(result.value) : null;\n }\n\n async findOneAndDelete(\n filter: Filter,\n options: Pick<FindOneAndOptions, 'expectedRevision' | 'sort' | 'projection' | 'idempotencyKey'> = {},\n ): Promise<WithMeta<T> | null> {\n const result = await this.post<{ value: UnsRecord | null }>(\n 'recordDeleteOne',\n {\n filter,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n projection: options.projection,\n idempotencyKey: options.idempotencyKey,\n returnDocument: 'before',\n },\n );\n return result.value ? toDoc<T>(result.value) : null;\n }\n\n /** Up to 200 mixed single-record writes in one atomic call (insertOne / updateOne / replaceOne / deleteOne). */\n async bulkWrite(\n operations: readonly BulkOperation[],\n options: { idempotencyKey?: string } = {},\n ): Promise<{\n insertedCount: number;\n matchedCount: number;\n modifiedCount: number;\n deletedCount: number;\n upsertedCount: number;\n insertedIds: Record<number, string>;\n upsertedIds: Record<number, string>;\n }> {\n assertAtomicBatch('bulkWrite', operations.length);\n const mapped = operations.map((operation) => {\n if ('insertOne' in operation) {\n const { id, data } = validateDocument(this.definition, operation.insertOne.document);\n return { insertOne: compact({ id, data }) };\n }\n if ('updateOne' in operation) {\n const { filter, update, upsert, sort } = operation.updateOne;\n return { updateOne: compact({ filter, update: validateUpdate(this.definition, update), upsert, sort: toSortPairs(sort) }) };\n }\n if ('replaceOne' in operation) {\n const { filter, replacement, upsert, sort } = operation.replaceOne;\n const { data } = validateDocument(this.definition, replacement);\n return { replaceOne: compact({ filter, replacement: data, upsert, sort: toSortPairs(sort) }) };\n }\n if ('deleteOne' in operation) {\n return { deleteOne: compact({ filter: operation.deleteOne.filter, sort: toSortPairs(operation.deleteOne.sort) }) };\n }\n throw new Error(\n `Unsupported bulkWrite operation ${Object.keys(operation).join(', ')}; use updateMany() / deleteMany() or data.transact().`,\n );\n });\n if (mapped.length === 0) {\n return { insertedCount: 0, matchedCount: 0, modifiedCount: 0, deletedCount: 0, upsertedCount: 0, insertedIds: {}, upsertedIds: {} };\n }\n const result = await this.post<WriteResult>(\n 'recordBulkWrite',\n { operations: mapped, ordered: true, atomic: true, idempotencyKey: options.idempotencyKey },\n );\n assertNoWriteErrors(result, 'bulkWrite');\n const numericKeys = (ids: Record<string, string> | undefined) =>\n Object.fromEntries(Object.entries(ids ?? {}).map(([index, id]) => [Number(index), id]));\n return {\n insertedCount: result.insertedCount ?? 0,\n matchedCount: result.matchedCount ?? 0,\n modifiedCount: result.modifiedCount ?? 0,\n deletedCount: result.deletedCount ?? 0,\n upsertedCount: result.upsertedCount ?? 0,\n insertedIds: numericKeys(result.insertedIds),\n upsertedIds: numericKeys(result.upsertedIds),\n };\n }\n}\n"]}
1
+ {"version":3,"file":"collection.js","s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,IAAI,CAAC;YACtC,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,CAAC;YACxC,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC;YAC5C,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC;SAC7C,CAAC;IACJ,CAAC;CACF;AAvfD,gCAufC","sourcesContent":["/**\n * Mongo-driver-style collection handle over the UNS record operations\n * (`recordFind`, `recordBulkWrite`, ...).\n *\n * Stored records `{ id, data, revision, createdAt, updatedAt }` are exposed as\n * flat documents `{ _id, ...data, _meta: { revision, createdAt, updatedAt } }`;\n * filters, sorts and projections use the same paths (`status`,\n * `customer.id`, `_id`, `_meta.updatedAt`).\n */\nimport type { UnsV2OperationName } from '../uns-v2/generated.js';\nimport type { CallOptions, DataCall } from './call.js';\nimport { collectionLabel, type CollectionTarget, type RecordMeta } from './define.js';\nimport { DataError } from './error.js';\nimport { validateDocument, validateUpdate } from './schema.js';\nimport { toSortPairs, type Filter, type Sort, type SortPairs } from './sort.js';\n\n/** UNS page limit for find / aggregate / distinct. */\nexport const MAX_PAGE_SIZE = 200;\n\n/**\n * UNS commits at most 200 items in one synchronous atomic batch\n * (insertMany, bulkWrite, data.transact).\n */\nexport const MAX_ATOMIC_ITEMS = 200;\n\nexport type WithMeta<T> = T & { _id: string; _meta: RecordMeta };\n/** A projection may omit business fields at any depth; array and tuple containers retain their shape. */\nexport type DeepPartial<T> = T extends readonly unknown[]\n ? { [K in keyof T]: DeepPartial<T[K]> }\n : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;\nexport type Projection = Record<string, 0 | 1 | boolean>;\nexport type Update = Record<string, unknown>;\n\nexport interface UnsRecord {\n id: string;\n data: Record<string, unknown>;\n revision: number;\n createdAt: number;\n updatedAt: number;\n}\n\ninterface PageInfo {\n hasMore: boolean;\n nextCursor?: string | null;\n nextPage?: number | null;\n}\n\n/** Position of the next page: an opaque cursor or a 1-based offset page number. */\ntype PageToken = string | number;\n\ninterface Page<T> {\n items: T[];\n /** Token of the following page; null when this was the last one. */\n next: PageToken | null;\n}\n\ninterface WriteResult {\n matchedCount?: number;\n modifiedCount?: number;\n deletedCount?: number;\n insertedCount?: number;\n upsertedId?: string | null;\n insertedIds?: Record<string, string>;\n upsertedIds?: Record<string, string>;\n upsertedCount?: number;\n writeErrors?: unknown[];\n hasMore?: boolean;\n}\n\n/** A page of `updateMany` / `deleteMany`, the only writes that continue with `resumeAfter`. */\ninterface ManyPage extends WriteResult {\n resumeAfter?: string | null;\n}\n\n/** Runtime services a collection handle needs from its client. */\nexport interface CollectionRuntime {\n call: DataCall;\n /** Resolve an existing ID directly, or ensure a declared collection. */\n resolve(target: CollectionTarget | string): Promise<string>;\n /** Runs a call, re-ensuring and retrying once when its collection ID went stale (see bootstrap). */\n recover<R>(fn: () => Promise<R>, options: { collections: readonly CollectionTarget[]; retry?: boolean }): Promise<R>;\n /** Data subject of the request being served. */\n subject(): string | undefined;\n /** Abort signal of the request being served. */\n signal(): AbortSignal | undefined;\n}\n\n/** Rejects batches UNS would refuse, before anything is sent. */\nexport function assertAtomicBatch(operation: string, count: number) {\n if (count > MAX_ATOMIC_ITEMS) {\n throw new DataError({\n message:\n `${operation} commits at most ${MAX_ATOMIC_ITEMS} items atomically; got ${count}. ` +\n `Split the input into chunks of ${MAX_ATOMIC_ITEMS} (each chunk commits on its own; give each chunk a stable ` +\n 'idempotencyKey or fixed _ids so a retry is safe), or keep all-or-nothing work within one batch.',\n status: 400,\n code: 'BATCH_LIMIT_EXCEEDED',\n });\n }\n}\n\nexport function toDoc<T>(record: UnsRecord): WithMeta<T> {\n return {\n ...(record.data as T),\n _id: record.id,\n _meta: { revision: record.revision, createdAt: record.createdAt, updatedAt: record.updatedAt },\n };\n}\n\n/**\n * Async-iterable result set. Pages hold at most 200 items; the page source\n * decides whether the next page is reached by cursor or by offset page number.\n */\nexport class Cursor<T> implements AsyncIterable<T> {\n private sortSpec?: Sort;\n private limitCount?: number;\n private projection?: Projection;\n private started = false;\n\n constructor(\n private readonly fetchPage: (state: {\n token: PageToken | null;\n size: number;\n sort?: SortPairs;\n projection?: Projection;\n }) => Promise<Page<T>>,\n options: { sort?: Sort; limit?: number; projection?: Projection } = {},\n ) {\n this.sortSpec = options.sort;\n this.limitCount = options.limit;\n this.projection = options.projection;\n }\n\n private assertNotStarted() {\n if (this.started) throw new Error('Cursor options must be set before iteration starts.');\n }\n\n sort(sort: Sort): this {\n this.assertNotStarted();\n this.sortSpec = sort;\n return this;\n }\n\n /** Total number of documents to return (pages are fetched ≤200 at a time). */\n limit(count: number): this {\n this.assertNotStarted();\n this.limitCount = count;\n return this;\n }\n\n project(projection: Projection): this {\n this.assertNotStarted();\n this.projection = projection;\n return this;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n this.started = true;\n const sort = toSortPairs(this.sortSpec);\n let remaining = this.limitCount ?? Number.POSITIVE_INFINITY;\n // One page size for the whole iteration: offset pages are only stable when it never changes.\n const size = Math.min(MAX_PAGE_SIZE, remaining);\n let token: PageToken | null = null;\n while (remaining > 0) {\n const page = await this.fetchPage({ token, size, sort, projection: this.projection });\n for (const item of page.items.slice(0, remaining)) yield item;\n remaining -= page.items.length;\n if (page.next === null || page.items.length === 0) return;\n token = page.next;\n }\n }\n\n async toArray(): Promise<T[]> {\n const out: T[] = [];\n for await (const item of this) out.push(item);\n return out;\n }\n}\n\n/** Pipelines made only of `$match` / `$sort` page by cursor; UNS requires offset paging for any other stage. */\nfunction isDirectPipeline(stages: readonly Record<string, unknown>[]): boolean {\n return stages.every((stage) => Object.keys(stage).every((key) => key === '$match' || key === '$sort'));\n}\n\nexport interface FindOptions {\n sort?: Sort;\n limit?: number;\n projection?: Projection;\n}\n\nexport interface FindPageOptions {\n sort?: Sort;\n /** 1-based page number. */\n page?: number;\n /** At most 200. */\n pageSize?: number;\n projection?: Projection;\n /** Count matches up to this many (1–100000); UNS defaults to 10000. */\n maxCount?: number;\n}\n\n/** A match count UNS stopped at its limit: `capped` means \"at least `count`\". */\nexport interface CappedCount {\n count: number;\n capped: boolean;\n}\n\n/** UNS reads at most 100 records by ID per request. */\nexport const MAX_GET_IDS = 100;\n\nexport interface FoundPage<T> {\n items: WithMeta<T>[];\n total: CappedCount;\n page: number;\n pageSize: number;\n}\n\nexport interface ValueCount {\n value: unknown;\n count: number;\n}\n\ninterface RecordGetResult {\n items: UnsRecord[];\n missing: string[];\n}\n\n/** One read of `data.queryBatch`, built by `collection.query.*`. */\nexport interface BatchQuery<R> {\n readonly collection: CollectionTarget;\n /** The batch item without `id` and `collectionId`; resolves `$lookup` targets. */\n prepare(): Promise<Record<string, unknown>>;\n /** The item's result as the builder's caller sees it. */\n parse(data: unknown): R;\n}\n\nexport interface CollectionQueries<T> {\n /** First page (≤200, default 20); `maxCount` adds the capped total of all matches. */\n find(filter?: Filter, options?: { sort?: Sort; limit?: number; projection?: Projection; maxCount?: number }):\n BatchQuery<{ items: WithMeta<T>[]; hasMore: boolean; total?: CappedCount }>;\n /** Like `collection.findPage`. */\n findPage(filter?: Filter, options?: FindPageOptions): BatchQuery<FoundPage<T>>;\n count(filter?: Filter, options?: { maxCount?: number }): BatchQuery<CappedCount>;\n /** The 200 most frequent values. */\n countBy(field: string, filter?: Filter): BatchQuery<ValueCount[]>;\n /** The first 200 distinct values. */\n distinct(field: string, filter?: Filter): BatchQuery<unknown[]>;\n /** The first 200 output rows. */\n aggregate<R = Record<string, unknown>>(pipeline: Record<string, unknown>[]): BatchQuery<R[]>;\n /** 1–100 distinct records by ID, as `collection.get`. */\n get(ids: readonly string[], options?: { projection?: Projection }): BatchQuery<{ items: WithMeta<T>[]; missing: string[] }>;\n}\n\nexport interface UpdateOptions {\n upsert?: boolean;\n /** Reject the write with VERSION_CONFLICT unless the record is at this revision. */\n expectedRevision?: number;\n sort?: Sort;\n arrayFilters?: Record<string, unknown>[];\n idempotencyKey?: string;\n}\n\nexport interface FindOneAndOptions extends UpdateOptions {\n returnDocument?: 'before' | 'after';\n projection?: Projection;\n}\n\nexport type InsertOneOptions = { idempotencyKey?: string } & (\n | { returnDocument?: 'none'; projection?: never }\n | { returnDocument: 'after'; projection?: Projection }\n);\n\nexport type BulkOperation =\n | { insertOne: { document: Record<string, unknown> } }\n | { updateOne: { filter: Filter; update: Update; upsert?: boolean; sort?: Sort } }\n | { replaceOne: { filter: Filter; replacement: Record<string, unknown>; upsert?: boolean; sort?: Sort } }\n | { deleteOne: { filter: Filter; sort?: Sort } };\n\nfunction compact<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n\nfunction filterOrNothing(filter: Filter): Filter | undefined {\n return Object.keys(filter).length > 0 ? filter : undefined;\n}\n\n/** `recordAggregatePipeline` body of one numbered page with its capped total. */\nfunction pageRequest(filter: Filter, options: FindPageOptions) {\n const page = Math.max(1, Math.trunc(options.page ?? 1));\n const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(1, Math.trunc(options.pageSize ?? 20)));\n const pipeline: Record<string, unknown>[] = [];\n if (Object.keys(filter).length > 0) pipeline.push({ $match: filter });\n const sort = toSortPairs(options.sort);\n if (sort) pipeline.push({ $sort: sort });\n if (options.projection) pipeline.push({ $project: options.projection });\n const body = { pipeline, page: { mode: 'offset', page, size: pageSize }, count: options.maxCount === undefined ? {} : { max: options.maxCount } };\n return { body, page, pageSize };\n}\n\nfunction countByPipeline(field: string, filter: Filter): Record<string, unknown>[] {\n const pipeline: Record<string, unknown>[] = [];\n if (Object.keys(filter).length > 0) pipeline.push({ $match: filter });\n // `_id` breaks ties, so offset pages of equal counts neither repeat nor skip a group.\n pipeline.push({ $group: { _id: `$${field}`, count: { $sum: 1 } } }, { $sort: { count: -1, _id: 1 } });\n return pipeline;\n}\n\nconst toValueCount = (row: { _id: unknown; count: number }): ValueCount => ({ value: row._id ?? null, count: row.count });\n\nfunction idsInOrder(ids: Record<string, string> | undefined): string[] {\n return Object.entries(ids ?? {})\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([, id]) => id);\n}\n\n/**\n * Atomic batches pass no `committed` counts: their write errors rolled the\n * whole batch back. Non-atomic runs pass their cumulative counts; `details`\n * then has the shape `partialWrite` uses.\n */\nexport function assertNoWriteErrors(result: ManyPage, operation: string, committed?: Record<string, number>) {\n if (result.writeErrors && result.writeErrors.length > 0) {\n const counts = Object.entries(committed ?? {}).map(([name, value]) => `${name}=${value}`).join(', ');\n const changed = committed !== undefined && Object.values(committed).some((value) => value > 0);\n throw new DataError({\n message: `${operation} stopped on ${result.writeErrors.length} write error(s)${counts ? `; already committed: ${counts}` : ''}.`,\n status: 409,\n code: 'WRITE_ERRORS',\n execution: changed ? 'committed' : 'rolledBack',\n attempts: 1,\n details: committed\n ? { ...committed, status: changed ? 'partiallyCommitted' : 'failed', hasMore: Boolean(result.hasMore), resumeAfter: result.resumeAfter ?? null, writeErrors: result.writeErrors }\n : { writeErrors: result.writeErrors },\n });\n }\n}\n\n/**\n * A non-atomic run failed after some writes committed: on an earlier page, or\n * within the failed page (UNS then answers `execution: \"committed\"` with the\n * page's partial result as `data`). Like UNS, the error keeps its code and is\n * `committed` with `retry.safe: false`; `details` is the cumulative result\n * of the whole call in the shape of a success (`matchedCount` …, `status:\n * \"partiallyCommitted\"`, `hasMore`, `resumeAfter`). Continue by passing\n * `resumeAfter` back; repeating the call would apply `$inc` / `$push` twice.\n */\nfunction partialWrite(operation: string, totals: Record<string, number>, resumeAfter: string | undefined, cause: DataError): DataError {\n const counts = Object.entries(totals).map(([name, value]) => `${name}=${value}`).join(', ');\n const writeErrors = Array.isArray(cause.details.writeErrors) ? { writeErrors: cause.details.writeErrors } : {};\n return new DataError({\n message:\n `${operation} committed ${counts} and then failed: ${cause.message} ` +\n (resumeAfter\n ? `Continue with { resumeAfter: details.resumeAfter }${cause.outcomeUnknown ? ' after checking the failed page, whose outcome is unknown' : ''}; do not repeat the whole call.`\n : 'Read back what changed before writing again; do not repeat the whole call.'),\n status: cause.status,\n code: cause.code,\n reason: cause.reason,\n upstreamStatus: cause.upstreamStatus,\n requestId: cause.requestId,\n // Earlier writes took effect; the failed page too, perhaps, when its outcome is unknown.\n execution: cause.outcomeUnknown ? 'unknown' : 'committed',\n retry: { safe: false },\n attempts: cause.attempts,\n details: { ...totals, status: 'partiallyCommitted', hasMore: true, resumeAfter: resumeAfter ?? null, ...writeErrors },\n cause,\n });\n}\n\nexport class Collection<T extends object = Record<string, unknown>, TInput extends object = T> {\n constructor(\n readonly definition: CollectionTarget,\n private readonly runtime: CollectionRuntime,\n ) {}\n\n get alias(): string {\n return collectionLabel(this.definition);\n }\n\n /**\n * One call with stale-ID recovery. A call continuing a cursor or\n * resumeAfter token of the old collection is not retried: the token means\n * nothing to a recreated collection.\n */\n private post<R>(operation: UnsV2OperationName, body: Record<string, unknown>, options: CallOptions = {}): Promise<R> {\n const page = body.page as { cursor?: unknown } | undefined;\n const continues = typeof body.cursor === 'string' || typeof body.resumeAfter === 'string' || typeof page?.cursor === 'string';\n return this.runtime.recover(() => this.send<R>(operation, body, options), { collections: [this.definition], retry: !continues });\n }\n\n private async send<R>(operation: UnsV2OperationName, body: Record<string, unknown>, options: CallOptions = {}): Promise<R> {\n const collectionId = await this.runtime.resolve(this.definition);\n return this.runtime.call<R>(operation, { collectionId, ...compact(body) }, {\n dataSubject: this.runtime.subject(),\n signal: this.runtime.signal(),\n ...options,\n });\n }\n\n /* ---------------------------------- reads --------------------------------- */\n\n find(filter: Filter = {}, options: FindOptions = {}): Cursor<WithMeta<T>> {\n return new Cursor<WithMeta<T>>(async ({ token, size, sort, projection }) => {\n const result = await this.post<{ items: UnsRecord[]; pageInfo: PageInfo }>('recordFind', {\n filter: Object.keys(filter).length > 0 ? filter : undefined,\n sort,\n projection,\n limit: size,\n cursor: typeof token === 'string' ? token : undefined,\n });\n return {\n items: result.items.map((record) => toDoc<T>(record)),\n next: result.pageInfo.hasMore && result.pageInfo.nextCursor ? result.pageInfo.nextCursor : null,\n };\n }, options);\n }\n\n async findOne(filter: Filter = {}, options: Omit<FindOptions, 'limit'> = {}): Promise<WithMeta<T> | null> {\n const [first] = await this.find(filter, { ...options, limit: 1 }).toArray();\n return first ?? null;\n }\n\n /**\n * Records by ID, in the order asked for (each ID once, at its first\n * position); IDs that do not exist, are deleted or are hidden by employee\n * data rules are listed in `missing` alike. More than 100 IDs are read in\n * chunks of 100 (not one snapshot).\n */\n async get(ids: readonly string[], options: { projection?: Projection } = {}): Promise<{ items: WithMeta<T>[]; missing: string[] }> {\n const unique = [...new Set(ids)];\n const chunks: string[][] = [];\n for (let start = 0; start < unique.length; start += MAX_GET_IDS) chunks.push(unique.slice(start, start + MAX_GET_IDS));\n const results = await Promise.all(chunks.map((chunk) =>\n this.post<RecordGetResult>('recordGet', { ids: chunk, projection: options.projection })));\n return {\n items: results.flatMap((result) => result.items.map((record) => toDoc<T>(record))),\n missing: results.flatMap((result) => result.missing),\n };\n }\n\n /**\n * One numbered page plus the total match count, for paged list screens:\n * one `recordAggregatePipeline` offset page whose `count` runs in the same\n * snapshot. Show a capped total as \"10000+\".\n */\n async findPage(filter: Filter = {}, options: FindPageOptions = {}): Promise<FoundPage<T>> {\n const { body, page, pageSize } = pageRequest(filter, options);\n const result = await this.post<{ items: WithMeta<T>[]; total: CappedCount }>('recordAggregatePipeline', body);\n return { items: result.items, total: result.total, page, pageSize };\n }\n\n /**\n * Counts matches up to `maxCount` (1–100000, UNS default 100000). A\n * `capped` result means \"at least `count`\".\n */\n async countDocuments(filter: Filter = {}, options: { maxCount?: number } = {}): Promise<CappedCount> {\n const result = await this.post<CappedCount>('recordCount', { filter: filterOrNothing(filter), maxCount: options.maxCount });\n return { count: result.count, capped: result.capped };\n }\n\n /**\n * Match counts per value of `field`, largest first: one `$group` pipeline\n * instead of a count per value. Records without the field count under\n * `value: null`.\n */\n async countBy(field: string, filter: Filter = {}): Promise<ValueCount[]> {\n const rows = await this.aggregate<{ _id: unknown; count: number }>(countByPipeline(field, filter)).toArray();\n return rows.map(toValueCount);\n }\n\n /**\n * Builders for `data.queryBatch`: each describes one read of this\n * collection, run together with the others in one request and one\n * snapshot. Each returns one page (at most 200 rows), unlike the cursor\n * methods; `get` takes at most 100 IDs.\n */\n get query(): CollectionQueries<T> {\n const one = <R>(op: string, build: () => Promise<Record<string, unknown>>, parse: (data: never) => R): BatchQuery<R> => ({\n collection: this.definition,\n prepare: async () => ({ op, ...compact(await build()) }),\n parse: parse as (data: unknown) => R,\n });\n return {\n find: (filter = {}, options = {}) =>\n one('find', async () => ({\n filter: filterOrNothing(filter),\n sort: toSortPairs(options.sort),\n projection: options.projection,\n limit: Math.min(MAX_PAGE_SIZE, options.limit ?? 20),\n count: options.maxCount === undefined ? undefined : { max: options.maxCount },\n }), (data: { items: UnsRecord[]; pageInfo: PageInfo; total?: CappedCount }) => ({\n items: data.items.map((record) => toDoc<T>(record)),\n hasMore: data.pageInfo.hasMore,\n ...(data.total ? { total: data.total } : {}),\n })),\n findPage: (filter = {}, options = {}) => {\n const { body, page, pageSize } = pageRequest(filter, options);\n return one('aggregate', async () => body, (data: { items: WithMeta<T>[]; total: CappedCount }) => ({\n items: data.items, total: data.total, page, pageSize,\n }));\n },\n count: (filter = {}, options = {}) =>\n one('count', async () => ({ filter: filterOrNothing(filter), maxCount: options.maxCount }),\n (data: CappedCount) => ({ count: data.count, capped: data.capped })),\n countBy: (field, filter = {}) =>\n one('aggregate', async () => ({\n pipeline: await this.prepareStages(countByPipeline(field, filter)),\n page: { mode: 'offset', page: 1, size: MAX_PAGE_SIZE },\n }), (data: { items: { _id: unknown; count: number }[] }) => data.items.map(toValueCount)),\n distinct: (field, filter = {}) =>\n one('distinct', async () => ({ field, filter: filterOrNothing(filter), page: { mode: 'offset', page: 1, size: MAX_PAGE_SIZE } }),\n (data: { values: unknown[] }) => data.values),\n aggregate: <R = Record<string, unknown>>(pipeline: Record<string, unknown>[]) =>\n one('aggregate', async () => {\n const stages = await this.prepareStages(pipeline);\n const last = stages[stages.length - 1];\n // A final $count returns one row and forbids an explicit page.\n return last !== undefined && '$count' in last\n ? { pipeline: stages }\n : { pipeline: stages, page: isDirectPipeline(stages) ? { mode: 'cursor', size: MAX_PAGE_SIZE } : { mode: 'offset', page: 1, size: MAX_PAGE_SIZE } };\n }, (data: { items: R[] }) => data.items),\n get: (ids, options = {}) => {\n const unique = [...new Set(ids)];\n if (unique.length < 1 || unique.length > MAX_GET_IDS) {\n throw new TypeError(`query.get takes 1–${MAX_GET_IDS} distinct IDs; use collection.get for more.`);\n }\n return one('get', async () => ({ ids: unique, projection: options.projection }),\n (data: RecordGetResult) => ({ items: data.items.map((record) => toDoc<T>(record)), missing: data.missing }));\n },\n };\n }\n\n /** Distinct values of a field (every page). */\n async distinct(field: string, filter: Filter = {}): Promise<unknown[]> {\n const values: unknown[] = [];\n for (let page = 1; ; page += 1) {\n const result = await this.post<{ items: { _id: unknown }[]; pageInfo: PageInfo }>('recordAggregatePipeline', {\n pipeline: [{ $match: filter }, { $group: { _id: `$${field}` } }],\n page: { mode: 'offset', page, size: MAX_PAGE_SIZE },\n });\n values.push(...result.items.map(item => item._id));\n if (!result.pageInfo.hasMore) return values;\n }\n }\n\n /**\n * Runs a pipeline (`$match`, `$sort`, `$group`, `$project`, `$set`,\n * `$lookup`, `$unwind`, `$skip`, `$limit`, `$count`). `$sort` accepts\n * `{ field: 1 | -1 }`; `$lookup` takes `from` (a declared collection or\n * alias of this App) instead of a collection ID. Rows are whatever the\n * pipeline outputs, not wrapped records.\n *\n * Pipelines of only `$match` / `$sort` page by cursor; any other stage pages\n * by offset (UNS rejects cursors for transformed results). The `$exists`,\n * `$distinct` and `$frequencies` stages are listed in the UNS schema but not\n * executed by the record pipeline; use `countDocuments`, `distinct` or `$group`.\n */\n aggregate<R = Record<string, unknown>>(pipeline: Record<string, unknown>[]): Cursor<R> {\n // Recovery wraps stage preparation too, so a retry re-resolves `$lookup` IDs.\n return new Cursor<R>(({ token, size }) => this.runtime.recover(() => this.aggregatePage<R>(pipeline, token, size), { collections: [this.definition], retry: typeof token !== 'string' }));\n }\n\n private async aggregatePage<R>(\n pipeline: Record<string, unknown>[],\n token: PageToken | null,\n size: number,\n ): Promise<Page<R>> {\n const stages = await this.prepareStages(pipeline);\n const last = stages[stages.length - 1];\n if (last !== undefined && '$count' in last) {\n // A final $count returns one row and forbids an explicit page.\n const result = await this.send<{ items: R[] }>('recordAggregatePipeline', { pipeline: stages });\n return { items: result.items, next: null };\n }\n if (isDirectPipeline(stages)) {\n const result = await this.send<{ items: R[]; pageInfo: PageInfo }>('recordAggregatePipeline', {\n pipeline: stages,\n page: { mode: 'cursor', size, ...(typeof token === 'string' ? { cursor: token } : {}) },\n });\n return { items: result.items, next: result.pageInfo.hasMore && result.pageInfo.nextCursor ? result.pageInfo.nextCursor : null };\n }\n const page = typeof token === 'number' ? token : 1;\n const result = await this.send<{ items: R[]; pageInfo: PageInfo }>('recordAggregatePipeline', {\n pipeline: stages,\n page: { mode: 'offset', page, size },\n });\n return {\n items: result.items,\n next: result.pageInfo.hasMore ? (result.pageInfo.nextPage ?? page + 1) : null,\n };\n }\n\n /** Converts Mongo-style `$sort` objects and resolves `$lookup.from`, recursively. */\n private async prepareStages(pipeline: readonly Record<string, unknown>[]): Promise<Record<string, unknown>[]> {\n return Promise.all(\n pipeline.map(async (stage) => {\n if ('$sort' in stage && !Array.isArray(stage.$sort)) {\n return { ...stage, $sort: toSortPairs(stage.$sort as Sort) };\n }\n if ('$lookup' in stage && stage.$lookup && typeof stage.$lookup === 'object') {\n const { from, pipeline: inner, ...lookup } = stage.$lookup as Record<string, unknown>;\n const resolved: Record<string, unknown> = { ...lookup };\n if (from !== undefined) resolved.collectionId = await this.runtime.resolve(from as CollectionTarget | string);\n if (Array.isArray(inner)) resolved.pipeline = await this.prepareStages(inner as Record<string, unknown>[]);\n return { ...stage, $lookup: resolved };\n }\n return stage;\n }),\n );\n }\n\n /* --------------------------------- writes --------------------------------- */\n\n /** Returns the creation snapshot in the same write; replay preserves that snapshot and requires current read access. */\n async insertOne(document: TInput & { _id?: string }, options: Extract<InsertOneOptions, { returnDocument: 'after' }> & { projection?: never }): Promise<{ insertedId: string; value: WithMeta<T> }>;\n async insertOne(document: TInput & { _id?: string }, options: Extract<InsertOneOptions, { returnDocument: 'after' }>): Promise<{ insertedId: string; value: WithMeta<DeepPartial<T>> }>;\n async insertOne(document: TInput & { _id?: string }, options?: Extract<InsertOneOptions, { returnDocument?: 'none' }>): Promise<{ insertedId: string }>;\n async insertOne(document: TInput & { _id?: string }, options: InsertOneOptions): Promise<{ insertedId: string; value?: WithMeta<DeepPartial<T>> }>;\n async insertOne(document: TInput & { _id?: string }, options: InsertOneOptions = {}): Promise<{ insertedId: string; value?: WithMeta<T> | WithMeta<DeepPartial<T>> }> {\n const { id, data } = validateDocument(this.definition, document as Record<string, unknown>);\n const result = await this.post<{ insertedId: string; value: UnsRecord }>('recordInsertOne', {\n id, data, idempotencyKey: options.idempotencyKey, returnDocument: options.returnDocument, projection: options.projection,\n });\n if (options.returnDocument === 'after') return { insertedId: result.insertedId, value: toDoc<T>(result.value) };\n return { insertedId: result.insertedId };\n }\n\n /** Inserts up to 200 documents atomically (all or none). */\n async insertMany(\n documents: readonly (TInput & { _id?: string })[],\n options: { idempotencyKey?: string } = {},\n ): Promise<{ insertedCount: number; insertedIds: string[] }> {\n if (documents.length === 0) return { insertedCount: 0, insertedIds: [] };\n assertAtomicBatch('insertMany', documents.length);\n const prepared = documents.map((document) => validateDocument(this.definition, document as Record<string, unknown>));\n const result = await this.post<WriteResult>('recordBulkWrite', {\n operations: prepared.map(({ id, data }) => ({ insertOne: compact({ id, data }) })),\n ordered: true,\n atomic: true,\n idempotencyKey: options.idempotencyKey,\n });\n assertNoWriteErrors(result, 'insertMany');\n return { insertedCount: result.insertedCount ?? 0, insertedIds: idsInOrder(result.insertedIds) };\n }\n\n async updateOne(\n filter: Filter,\n update: Update,\n options: UpdateOptions = {},\n ): Promise<{ matchedCount: number; modifiedCount: number; upsertedId: string | null }> {\n const result = await this.post<WriteResult>('recordUpdateOne', {\n filter,\n update: validateUpdate(this.definition, update),\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n arrayFilters: options.arrayFilters,\n idempotencyKey: options.idempotencyKey,\n });\n return { matchedCount: result.matchedCount ?? 0, modifiedCount: result.modifiedCount ?? 0, upsertedId: result.upsertedId ?? null };\n }\n\n /**\n * Updates every match like Mongo's updateMany: documents commit one by one\n * (not atomically), following `resumeAfter` until every match is processed.\n * A failure after some documents committed keeps its code but is\n * `execution: \"committed\"`, with the cumulative counts and\n * `details.resumeAfter`; pass that back as `resumeAfter` to continue\n * instead of repeating the call. For all-or-nothing multi-document changes\n * use `data.transact` (≤200 items).\n */\n async updateMany(\n filter: Filter,\n update: Update,\n options: Pick<UpdateOptions, 'arrayFilters'> & { resumeAfter?: string } = {},\n ): Promise<{ matchedCount: number; modifiedCount: number }> {\n const validated = validateUpdate(this.definition, update);\n let matchedCount = 0;\n let modifiedCount = 0;\n await this.writeEach('updateMany', 'recordUpdateMany', { filter, update: validated, arrayFilters: options.arrayFilters }, options.resumeAfter, (result) => {\n matchedCount += result.matchedCount ?? 0;\n modifiedCount += result.modifiedCount ?? 0;\n return { matchedCount, modifiedCount };\n });\n return { matchedCount, modifiedCount };\n }\n\n /** Runs a non-atomic many-write page by page; see updateMany for failures. */\n private async writeEach(\n name: string,\n operation: UnsV2OperationName,\n body: Record<string, unknown>,\n from: string | undefined,\n add: (result: WriteResult) => Record<string, number>,\n ): Promise<void> {\n let resumeAfter = from;\n let committed: Record<string, number> | undefined;\n do {\n let result: ManyPage;\n try {\n result = await this.post<ManyPage>(operation, { ...body, atomic: false, resumeAfter });\n } catch (error) {\n if (!(error instanceof DataError)) throw error;\n // UNS reports what the failed page itself committed, with where to continue.\n const page = error.execution === 'committed' ? (error.details as ManyPage) : undefined;\n const totals = page ? add(page) : committed;\n // Nothing of this call took effect: the page's own error tells the truth.\n if (!totals || !Object.values(totals).some((value) => value > 0)) throw error;\n throw partialWrite(name, totals, page ? (page.resumeAfter ?? undefined) : resumeAfter, error);\n }\n committed = add(result);\n assertNoWriteErrors(result, name, committed);\n resumeAfter = result.hasMore && result.resumeAfter ? result.resumeAfter : undefined;\n } while (resumeAfter);\n }\n\n /**\n * Replaces the whole body. Fields written by another App version and not in\n * this declaration are lost — prefer `updateOne` with `$set`.\n */\n async replaceOne(\n filter: Filter,\n replacement: TInput,\n options: Omit<UpdateOptions, 'arrayFilters'> = {},\n ): Promise<{ matchedCount: number; modifiedCount: number; upsertedId: string | null }> {\n const { data } = validateDocument(this.definition, replacement as Record<string, unknown>);\n const result = await this.post<WriteResult>('recordReplaceOne', {\n filter,\n replacement: data,\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n idempotencyKey: options.idempotencyKey,\n });\n return { matchedCount: result.matchedCount ?? 0, modifiedCount: result.modifiedCount ?? 0, upsertedId: result.upsertedId ?? null };\n }\n\n /** Soft-deletes one record; requires `uns.delete` on the App key. */\n async deleteOne(filter: Filter, options: Pick<UpdateOptions, 'expectedRevision' | 'sort' | 'idempotencyKey'> = {}): Promise<{ deletedCount: number }> {\n const result = await this.post<WriteResult>(\n 'recordDeleteOne',\n { filter, expectedRevision: options.expectedRevision, sort: toSortPairs(options.sort), idempotencyKey: options.idempotencyKey },\n );\n return { deletedCount: result.deletedCount ?? 0 };\n }\n\n /**\n * Soft-deletes every match, one document at a time like Mongo's deleteMany\n * (not atomic), following `resumeAfter`; requires `uns.delete` on the App\n * key. Failures after committed deletes report them as updateMany does.\n */\n async deleteMany(filter: Filter, options: { resumeAfter?: string } = {}): Promise<{ deletedCount: number }> {\n let deletedCount = 0;\n await this.writeEach('deleteMany', 'recordDeleteMany', { filter }, options.resumeAfter, (result) => {\n deletedCount += result.deletedCount ?? 0;\n return { deletedCount };\n });\n return { deletedCount };\n }\n\n /**\n * Atomic read-modify-write. A state transition puts the expected state in\n * the filter: `findOneAndUpdate({ _id, status: \"DRAFT\" }, { $set: { status: \"SUBMITTED\" } })`\n * returns null when another request moved the record first.\n */\n async findOneAndUpdate(filter: Filter, update: Update, options: FindOneAndOptions = {}): Promise<WithMeta<T> | null> {\n const result = await this.post<{ value: UnsRecord | null }>('recordUpdateOne', {\n filter,\n update: validateUpdate(this.definition, update),\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n arrayFilters: options.arrayFilters,\n returnDocument: options.returnDocument ?? 'after',\n projection: options.projection,\n idempotencyKey: options.idempotencyKey,\n });\n return result.value ? toDoc<T>(result.value) : null;\n }\n\n async findOneAndReplace(\n filter: Filter,\n replacement: TInput,\n options: Omit<FindOneAndOptions, 'arrayFilters'> = {},\n ): Promise<WithMeta<T> | null> {\n const { data } = validateDocument(this.definition, replacement as Record<string, unknown>);\n const result = await this.post<{ value: UnsRecord | null }>('recordReplaceOne', {\n filter,\n replacement: data,\n upsert: options.upsert,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n returnDocument: options.returnDocument ?? 'after',\n projection: options.projection,\n idempotencyKey: options.idempotencyKey,\n });\n return result.value ? toDoc<T>(result.value) : null;\n }\n\n async findOneAndDelete(\n filter: Filter,\n options: Pick<FindOneAndOptions, 'expectedRevision' | 'sort' | 'projection' | 'idempotencyKey'> = {},\n ): Promise<WithMeta<T> | null> {\n const result = await this.post<{ value: UnsRecord | null }>(\n 'recordDeleteOne',\n {\n filter,\n expectedRevision: options.expectedRevision,\n sort: toSortPairs(options.sort),\n projection: options.projection,\n idempotencyKey: options.idempotencyKey,\n returnDocument: 'before',\n },\n );\n return result.value ? toDoc<T>(result.value) : null;\n }\n\n /** Up to 200 mixed single-record writes in one atomic call (insertOne / updateOne / replaceOne / deleteOne). */\n async bulkWrite(\n operations: readonly BulkOperation[],\n options: { idempotencyKey?: string } = {},\n ): Promise<{\n insertedCount: number;\n matchedCount: number;\n modifiedCount: number;\n deletedCount: number;\n upsertedCount: number;\n insertedIds: Record<number, string>;\n upsertedIds: Record<number, string>;\n }> {\n assertAtomicBatch('bulkWrite', operations.length);\n const mapped = operations.map((operation) => {\n if ('insertOne' in operation) {\n const { id, data } = validateDocument(this.definition, operation.insertOne.document);\n return { insertOne: compact({ id, data }) };\n }\n if ('updateOne' in operation) {\n const { filter, update, upsert, sort } = operation.updateOne;\n return { updateOne: compact({ filter, update: validateUpdate(this.definition, update), upsert, sort: toSortPairs(sort) }) };\n }\n if ('replaceOne' in operation) {\n const { filter, replacement, upsert, sort } = operation.replaceOne;\n const { data } = validateDocument(this.definition, replacement);\n return { replaceOne: compact({ filter, replacement: data, upsert, sort: toSortPairs(sort) }) };\n }\n if ('deleteOne' in operation) {\n return { deleteOne: compact({ filter: operation.deleteOne.filter, sort: toSortPairs(operation.deleteOne.sort) }) };\n }\n throw new Error(\n `Unsupported bulkWrite operation ${Object.keys(operation).join(', ')}; use updateMany() / deleteMany() or data.transact().`,\n );\n });\n if (mapped.length === 0) {\n return { insertedCount: 0, matchedCount: 0, modifiedCount: 0, deletedCount: 0, upsertedCount: 0, insertedIds: {}, upsertedIds: {} };\n }\n const result = await this.post<WriteResult>(\n 'recordBulkWrite',\n { operations: mapped, ordered: true, atomic: true, idempotencyKey: options.idempotencyKey },\n );\n assertNoWriteErrors(result, 'bulkWrite');\n const numericKeys = (ids: Record<string, string> | undefined) =>\n Object.fromEntries(Object.entries(ids ?? {}).map(([index, id]) => [Number(index), id]));\n return {\n insertedCount: result.insertedCount ?? 0,\n matchedCount: result.matchedCount ?? 0,\n modifiedCount: result.modifiedCount ?? 0,\n deletedCount: result.deletedCount ?? 0,\n upsertedCount: result.upsertedCount ?? 0,\n insertedIds: numericKeys(result.insertedIds),\n upsertedIds: numericKeys(result.upsertedIds),\n };\n }\n}\n"]}
@@ -6,6 +6,6 @@
6
6
  * while data reads and writes stay on the server (`@tier0/sdk-v2/data`).
7
7
  */
8
8
  export { defineCollection, MAX_COLLECTIONS } from './define.js';
9
- export type { CollectionDefinition, CollectionSchema, Doc, IndexSpec, NewDoc, RecordMeta, SeedDoc } from './define.js';
9
+ export type { CollectionDefinition, CollectionReference, CollectionSchema, CollectionTarget, Doc, IndexSpec, NewDoc, RecordMeta, SeedDoc } from './define.js';
10
10
  export { CollectionSchemaError, compileCollection, validateDocument } from './schema.js';
11
11
  export type { CompiledCollection, NormalizedIndex, RecordSchema, SchemaIssue } from './schema.js';
@@ -1 +1 @@
1
- {"version":3,"file":"declarations.js","sourceRoot":"","sources":["../../../src/data/declarations.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,yCAAgE;AAAvD,6GAAA,gBAAgB,OAAA;AAAE,4GAAA,eAAe,OAAA;AAE1C,yCAAyF;AAAhF,kHAAA,qBAAqB,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AAAE,6GAAA,gBAAgB,OAAA","sourcesContent":["/**\n * `@tier0/sdk-v2/data/define` — collection declarations, their types and the\n * schema compiler, without the runtime client. Safe for browser bundles: it\n * loads no Node built-ins, transport, request context or bootstrap, so\n * components and routes can import declarations and `Doc` types from here\n * while data reads and writes stay on the server (`@tier0/sdk-v2/data`).\n */\nexport { defineCollection, MAX_COLLECTIONS } from './define.js';\nexport type { CollectionDefinition, CollectionSchema, Doc, IndexSpec, NewDoc, RecordMeta, SeedDoc } from './define.js';\nexport { CollectionSchemaError, compileCollection, validateDocument } from './schema.js';\nexport type { CompiledCollection, NormalizedIndex, RecordSchema, SchemaIssue } from './schema.js';\n"]}
1
+ {"version":3,"file":"declarations.js","sourceRoot":"","sources":["../../../src/data/declarations.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,yCAAgE;AAAvD,6GAAA,gBAAgB,OAAA;AAAE,4GAAA,eAAe,OAAA;AAE1C,yCAAyF;AAAhF,kHAAA,qBAAqB,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AAAE,6GAAA,gBAAgB,OAAA","sourcesContent":["/**\n * `@tier0/sdk-v2/data/define` — collection declarations, their types and the\n * schema compiler, without the runtime client. Safe for browser bundles: it\n * loads no Node built-ins, transport, request context or bootstrap, so\n * components and routes can import declarations and `Doc` types from here\n * while data reads and writes stay on the server (`@tier0/sdk-v2/data`).\n */\nexport { defineCollection, MAX_COLLECTIONS } from './define.js';\nexport type { CollectionDefinition, CollectionReference, CollectionSchema, CollectionTarget, Doc, IndexSpec, NewDoc, RecordMeta, SeedDoc } from './define.js';\nexport { CollectionSchemaError, compileCollection, validateDocument } from './schema.js';\nexport type { CompiledCollection, NormalizedIndex, RecordSchema, SchemaIssue } from './schema.js';\n"]}
@@ -63,6 +63,13 @@ export interface CollectionDefinition<S extends CollectionSchema = CollectionSch
63
63
  */
64
64
  readonly seed?: readonly SeedDoc<S>[];
65
65
  }
66
+ /** An existing collection. The optional schema validates writes locally; it never changes storage. */
67
+ export interface CollectionReference<S extends CollectionSchema = CollectionSchema> {
68
+ readonly collectionId: string;
69
+ readonly schema?: S;
70
+ }
71
+ export type CollectionTarget = CollectionDefinition | CollectionReference;
72
+ export declare function collectionLabel(target: CollectionTarget): string;
66
73
  /** A stored record as services read it: `{ _id, ...fields, _meta }`. */
67
74
  export type Doc<C extends CollectionDefinition> = z.output<C['schema']> & {
68
75
  _id: string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MAX_SEED_DOCUMENTS = exports.MAX_NAME_LENGTH = exports.MAX_DESCRIPTION_LENGTH = exports.MAX_COLLECTIONS = exports.ALIAS_PATTERN = void 0;
4
+ exports.collectionLabel = collectionLabel;
4
5
  exports.defineCollection = defineCollection;
5
6
  exports.assertCollectionName = assertCollectionName;
6
7
  /** Collection alias: unique per App, case-insensitive. */
@@ -13,6 +14,9 @@ exports.MAX_DESCRIPTION_LENGTH = 512;
13
14
  exports.MAX_NAME_LENGTH = 63;
14
15
  /** Seeds are inserted in atomic chunks of 200 during the first request; keep them a baseline, not a data import. */
15
16
  exports.MAX_SEED_DOCUMENTS = 1000;
17
+ function collectionLabel(target) {
18
+ return 'collectionId' in target ? target.collectionId : target.alias;
19
+ }
16
20
  function defineCollection(definition) {
17
21
  if (!exports.ALIAS_PATTERN.test(definition.alias)) {
18
22
  throw new Error(`Collection alias "${definition.alias}" must match ${exports.ALIAS_PATTERN} (letters, digits, "_" or "-", starting with a letter).`);
@@ -1 +1 @@
1
- {"version":3,"file":"define.js","sourceRoot":"","sources":["../../../src/data/define.ts"],"names":[],"mappings":";;;AAiFA,4CA8BC;AAED,oDAIC;AAxGD,0DAA0D;AAC7C,QAAA,aAAa,GAAG,+BAA+B,CAAC;AAC7D,uFAAuF;AAC1E,QAAA,eAAe,GAAG,EAAE,CAAC;AAClC,wDAAwD;AAC3C,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAC1C,yEAAyE;AAC5D,QAAA,eAAe,GAAG,EAAE,CAAC;AAClC,oHAAoH;AACvG,QAAA,kBAAkB,GAAG,IAAI,CAAC;AA2DvC,SAAgB,gBAAgB,CAA6B,UAO5D;IACC,IAAI,CAAC,qBAAa,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CACb,qBAAqB,UAAU,CAAC,KAAK,gBAAgB,qBAAa,yDAAyD,CAC5H,CAAC;IACJ,CAAC;IACD,oBAAoB,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,UAAU,CAAC,WAAW,IAAI,CAAC,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC,MAAM,GAAG,8BAAsB,EAAE,CAAC;QAC1F,MAAM,IAAI,KAAK,CAAC,eAAe,UAAU,CAAC,KAAK,iCAAiC,8BAAsB,cAAc,CAAC,CAAC;IACxH,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,0BAAkB,EAAE,CAAC;QACnE,MAAM,IAAI,KAAK,CACb,eAAe,UAAU,CAAC,KAAK,cAAc,0BAAkB,wBAAwB,UAAU,CAAC,IAAI,CAAC,MAAM,iEAAiE,CAC/K,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,KAAK,EAAE,UAAU,CAAC,KAAK;QACvB,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;QACvD,GAAG,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1E,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC1E,CAAC,CAAC;AACL,CAAC;AAED,SAAgB,oBAAoB,CAAC,IAAa;IAChD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,uBAAe,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACvI,MAAM,IAAI,KAAK,CAAC,6CAA6C,uBAAe,kEAAkE,CAAC,CAAC;IAClJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Collection declarations — the single source of truth for App data.\n *\n * An App declares every collection with `defineCollection(...)` and passes the\n * list to `createDataClient({ collections })`. The client ensures that list in\n * one batch on first data access: a missing collection is created, a\n * declaration wider than storage widens it, and nothing is ever narrowed.\n *\n * This module is pure (Zod types only) so declarations, API input schemas and\n * build-time checks can import it without pulling in the runtime client.\n */\nimport type { z } from 'zod';\n\n/** Collection alias: unique per App, case-insensitive. */\nexport const ALIAS_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,62}$/;\n/** UNS: one ensure takes 1–64 declarations, and an App owns at most 64 collections. */\nexport const MAX_COLLECTIONS = 64;\n/** UNS: collection description length in characters. */\nexport const MAX_DESCRIPTION_LENGTH = 512;\n/** UNS: business-facing collection name length in Unicode characters. */\nexport const MAX_NAME_LENGTH = 63;\n/** Seeds are inserted in atomic chunks of 200 during the first request; keep them a baseline, not a data import. */\nexport const MAX_SEED_DOCUMENTS = 1000;\n\n/** Same shape as collection metadata indexes, limited to record indexes. */\nexport interface IndexSpec {\n /** Business field path without `data.`, e.g. `code` or `customer.id`. */\n path?: string;\n /** Compound index, at most 3 paths. Mutually exclusive with `path`. */\n paths?: string[];\n unique?: boolean;\n /** `btree` (default) or `gin` for one object/array path; GIN cannot be unique. */\n kind?: 'btree' | 'gin';\n /**\n * TTL index: UNS physically deletes a record this many seconds\n * (60–31536000) after the instant in `path`, an integer field of Unix\n * milliseconds. At most one per collection, on a single non-unique `path`. Expired\n * records cannot be restored. ensure may add a TTL or lengthen it;\n * shortening or removing it takes schema:replace.\n */\n expireAfterSeconds?: number;\n}\n\n/** System metadata of a stored record. Times are Unix milliseconds. */\nexport interface RecordMeta {\n revision: number;\n createdAt: number;\n updatedAt: number;\n}\n\nexport type CollectionSchema = z.ZodObject;\n\n/** A seed document: a full record plus the fixed `_id` it is inserted with. */\nexport type SeedDoc<S extends CollectionSchema> = z.input<S> & { _id: string };\n\nexport interface CollectionDefinition<S extends CollectionSchema = CollectionSchema> {\n readonly alias: string;\n /** Business-facing name, independent of the stable App alias. */\n readonly name: string;\n /** Zod 4 object schema of the record body (no `_id` / `_meta`). */\n readonly schema: S;\n readonly indexes: readonly IndexSpec[];\n readonly description?: string;\n /**\n * Baseline records, written only when ensure reports this collection as\n * `created`. Never re-applied to an existing collection.\n */\n readonly seed?: readonly SeedDoc<S>[];\n}\n\n/** A stored record as services read it: `{ _id, ...fields, _meta }`. */\nexport type Doc<C extends CollectionDefinition> = z.output<C['schema']> & {\n _id: string;\n _meta: RecordMeta;\n};\n\n/** A record to insert: the schema input plus an optional caller-chosen `_id`. */\nexport type NewDoc<C extends CollectionDefinition> = z.input<C['schema']> & {\n _id?: string;\n};\n\nexport function defineCollection<S extends CollectionSchema>(definition: {\n alias: string;\n name: string;\n schema: S;\n indexes?: IndexSpec[];\n description?: string;\n seed?: SeedDoc<S>[];\n}): CollectionDefinition<S> {\n if (!ALIAS_PATTERN.test(definition.alias)) {\n throw new Error(\n `Collection alias \"${definition.alias}\" must match ${ALIAS_PATTERN} (letters, digits, \"_\" or \"-\", starting with a letter).`,\n );\n }\n assertCollectionName(definition.name);\n if (definition.description && [...definition.description].length > MAX_DESCRIPTION_LENGTH) {\n throw new Error(`Collection \"${definition.alias}\": description is longer than ${MAX_DESCRIPTION_LENGTH} characters.`);\n }\n if (definition.seed && definition.seed.length > MAX_SEED_DOCUMENTS) {\n throw new Error(\n `Collection \"${definition.alias}\": at most ${MAX_SEED_DOCUMENTS} seed documents (got ${definition.seed.length}). Seeds are a baseline written on creation, not a bulk import.`,\n );\n }\n return Object.freeze({\n alias: definition.alias,\n name: definition.name,\n schema: definition.schema,\n indexes: Object.freeze([...(definition.indexes ?? [])]),\n ...(definition.description ? { description: definition.description } : {}),\n ...(definition.seed ? { seed: Object.freeze([...definition.seed]) } : {}),\n });\n}\n\nexport function assertCollectionName(name: unknown): asserts name is string {\n if (typeof name !== 'string' || name.length === 0 || name.trim() !== name || [...name].length > MAX_NAME_LENGTH || /[\\/\\0]/.test(name)) {\n throw new Error(`Collection name must be nonempty, at most ${MAX_NAME_LENGTH} Unicode characters, without surrounding whitespace, \"/\" or NUL.`);\n }\n}\n"]}
1
+ {"version":3,"file":"define.js","sourceRoot":"","sources":["../../../src/data/define.ts"],"names":[],"mappings":";;;AA8EA,0CAEC;AAaD,4CA8BC;AAED,oDAIC;AApHD,0DAA0D;AAC7C,QAAA,aAAa,GAAG,+BAA+B,CAAC;AAC7D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AAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;QACvD,GAAG,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1E,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC1E,CAAC,CAAC;AACL,CAAC;AAED,SAAgB,oBAAoB,CAAC,IAAa;IAChD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,uBAAe,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACvI,MAAM,IAAI,KAAK,CAAC,6CAA6C,uBAAe,kEAAkE,CAAC,CAAC;IAClJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Collection declarations — the single source of truth for App data.\n *\n * An App declares every collection with `defineCollection(...)` and passes the\n * list to `createDataClient({ collections })`. The client ensures that list in\n * one batch on first data access: a missing collection is created, a\n * declaration wider than storage widens it, and nothing is ever narrowed.\n *\n * This module is pure (Zod types only) so declarations, API input schemas and\n * build-time checks can import it without pulling in the runtime client.\n */\nimport type { z } from 'zod';\n\n/** Collection alias: unique per App, case-insensitive. */\nexport const ALIAS_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,62}$/;\n/** UNS: one ensure takes 1–64 declarations, and an App owns at most 64 collections. */\nexport const MAX_COLLECTIONS = 64;\n/** UNS: collection description length in characters. */\nexport const MAX_DESCRIPTION_LENGTH = 512;\n/** UNS: business-facing collection name length in Unicode characters. */\nexport const MAX_NAME_LENGTH = 63;\n/** Seeds are inserted in atomic chunks of 200 during the first request; keep them a baseline, not a data import. */\nexport const MAX_SEED_DOCUMENTS = 1000;\n\n/** Same shape as collection metadata indexes, limited to record indexes. */\nexport interface IndexSpec {\n /** Business field path without `data.`, e.g. `code` or `customer.id`. */\n path?: string;\n /** Compound index, at most 3 paths. Mutually exclusive with `path`. */\n paths?: string[];\n unique?: boolean;\n /** `btree` (default) or `gin` for one object/array path; GIN cannot be unique. */\n kind?: 'btree' | 'gin';\n /**\n * TTL index: UNS physically deletes a record this many seconds\n * (60–31536000) after the instant in `path`, an integer field of Unix\n * milliseconds. At most one per collection, on a single non-unique `path`. Expired\n * records cannot be restored. ensure may add a TTL or lengthen it;\n * shortening or removing it takes schema:replace.\n */\n expireAfterSeconds?: number;\n}\n\n/** System metadata of a stored record. Times are Unix milliseconds. */\nexport interface RecordMeta {\n revision: number;\n createdAt: number;\n updatedAt: number;\n}\n\nexport type CollectionSchema = z.ZodObject;\n\n/** A seed document: a full record plus the fixed `_id` it is inserted with. */\nexport type SeedDoc<S extends CollectionSchema> = z.input<S> & { _id: string };\n\nexport interface CollectionDefinition<S extends CollectionSchema = CollectionSchema> {\n readonly alias: string;\n /** Business-facing name, independent of the stable App alias. */\n readonly name: string;\n /** Zod 4 object schema of the record body (no `_id` / `_meta`). */\n readonly schema: S;\n readonly indexes: readonly IndexSpec[];\n readonly description?: string;\n /**\n * Baseline records, written only when ensure reports this collection as\n * `created`. Never re-applied to an existing collection.\n */\n readonly seed?: readonly SeedDoc<S>[];\n}\n\n/** An existing collection. The optional schema validates writes locally; it never changes storage. */\nexport interface CollectionReference<S extends CollectionSchema = CollectionSchema> {\n readonly collectionId: string;\n readonly schema?: S;\n}\n\nexport type CollectionTarget = CollectionDefinition | CollectionReference;\n\nexport function collectionLabel(target: CollectionTarget): string {\n return 'collectionId' in target ? target.collectionId : target.alias;\n}\n\n/** A stored record as services read it: `{ _id, ...fields, _meta }`. */\nexport type Doc<C extends CollectionDefinition> = z.output<C['schema']> & {\n _id: string;\n _meta: RecordMeta;\n};\n\n/** A record to insert: the schema input plus an optional caller-chosen `_id`. */\nexport type NewDoc<C extends CollectionDefinition> = z.input<C['schema']> & {\n _id?: string;\n};\n\nexport function defineCollection<S extends CollectionSchema>(definition: {\n alias: string;\n name: string;\n schema: S;\n indexes?: IndexSpec[];\n description?: string;\n seed?: SeedDoc<S>[];\n}): CollectionDefinition<S> {\n if (!ALIAS_PATTERN.test(definition.alias)) {\n throw new Error(\n `Collection alias \"${definition.alias}\" must match ${ALIAS_PATTERN} (letters, digits, \"_\" or \"-\", starting with a letter).`,\n );\n }\n assertCollectionName(definition.name);\n if (definition.description && [...definition.description].length > MAX_DESCRIPTION_LENGTH) {\n throw new Error(`Collection \"${definition.alias}\": description is longer than ${MAX_DESCRIPTION_LENGTH} characters.`);\n }\n if (definition.seed && definition.seed.length > MAX_SEED_DOCUMENTS) {\n throw new Error(\n `Collection \"${definition.alias}\": at most ${MAX_SEED_DOCUMENTS} seed documents (got ${definition.seed.length}). Seeds are a baseline written on creation, not a bulk import.`,\n );\n }\n return Object.freeze({\n alias: definition.alias,\n name: definition.name,\n schema: definition.schema,\n indexes: Object.freeze([...(definition.indexes ?? [])]),\n ...(definition.description ? { description: definition.description } : {}),\n ...(definition.seed ? { seed: Object.freeze([...definition.seed]) } : {}),\n });\n}\n\nexport function assertCollectionName(name: unknown): asserts name is string {\n if (typeof name !== 'string' || name.length === 0 || name.trim() !== name || [...name].length > MAX_NAME_LENGTH || /[\\/\\0]/.test(name)) {\n throw new Error(`Collection name must be nonempty, at most ${MAX_NAME_LENGTH} Unicode characters, without surrounding whitespace, \"/\" or NUL.`);\n }\n}\n"]}
@@ -10,7 +10,7 @@
10
10
  * time) instead of on the first request.
11
11
  */
12
12
  import { z } from 'zod';
13
- import { type CollectionDefinition } from './define.js';
13
+ import { type CollectionDefinition, type CollectionTarget } from './define.js';
14
14
  export type RecordSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean';
15
15
  export type EnumValue = string | number | boolean;
16
16
  export interface RecordSchema {
@@ -74,7 +74,7 @@ export declare function recordSchemaAt(schema: RecordSchema, path: string): Reco
74
74
  /** Ensure payload for one declaration; memoized per definition object. */
75
75
  export declare function compileCollection(definition: CollectionDefinition): CompiledCollection;
76
76
  /** Splits `_id` / `_meta` off a document and strictly validates the body. */
77
- export declare function validateDocument(definition: CollectionDefinition, document: Record<string, unknown>): {
77
+ export declare function validateDocument(definition: CollectionTarget, document: Record<string, unknown>): {
78
78
  id?: string;
79
79
  data: Record<string, unknown>;
80
80
  };
@@ -83,7 +83,7 @@ export declare function validateDocument(definition: CollectionDefinition, docum
83
83
  * (`data.<field>...`) are checked only for being declared; every literal
84
84
  * field is strictly validated, and other required fields must be present.
85
85
  */
86
- export declare function validateStepData(definition: CollectionDefinition, data: Record<string, unknown>, boundFields: readonly string[]): Record<string, unknown>;
86
+ export declare function validateStepData(definition: CollectionTarget, data: Record<string, unknown>, boundFields: readonly string[]): Record<string, unknown>;
87
87
  /** Validates update-operator documents against the declaration (paths and values). */
88
- export declare function validateUpdate(definition: CollectionDefinition, update: Record<string, unknown>): Record<string, unknown>;
88
+ export declare function validateUpdate(definition: CollectionTarget, update: Record<string, unknown>): Record<string, unknown>;
89
89
  export {};
@@ -492,6 +492,19 @@ function compileCollection(definition) {
492
492
  compiled.set(definition, result);
493
493
  return result;
494
494
  }
495
+ const referenceSchemas = new WeakMap();
496
+ function validationSchema(target) {
497
+ if (!('collectionId' in target))
498
+ return compileCollection(target).recordSchema;
499
+ if (!target.schema)
500
+ return undefined;
501
+ let schema = referenceSchemas.get(target);
502
+ if (!schema) {
503
+ schema = toRecordSchema(target.collectionId, target.schema);
504
+ referenceSchemas.set(target, schema);
505
+ }
506
+ return schema;
507
+ }
495
508
  function unknownKeyIssues(schema, value, path, out) {
496
509
  if (!schema)
497
510
  return;
@@ -559,7 +572,9 @@ function validateDocument(definition, document) {
559
572
  if (_id !== undefined && (typeof _id !== 'string' || _id.length === 0 || _id.length > 128)) {
560
573
  throw validationError(['_id'], '`_id` must be a string of 1–128 characters.', _id);
561
574
  }
562
- const { recordSchema } = compileCollection(definition);
575
+ if (!definition.schema)
576
+ return { ...(typeof _id === 'string' ? { id: _id } : {}), data: body };
577
+ const recordSchema = validationSchema(definition);
563
578
  const data = strictParse(definition.schema, recordSchema, body, []);
564
579
  return { ...(typeof _id === 'string' ? { id: _id } : {}), data };
565
580
  }
@@ -574,12 +589,14 @@ function validateStepData(definition, data, boundFields) {
574
589
  if ('_id' in data || '_meta' in data) {
575
590
  throw validationError(['data', '_id' in data ? '_id' : '_meta'], 'A transaction step sets the record ID with `id`, not `data._id`; `_meta` is read-only.', data);
576
591
  }
577
- const { recordSchema } = compileCollection(definition);
592
+ if (!definition.schema)
593
+ return data;
594
+ const recordSchema = validationSchema(definition);
578
595
  const properties = recordSchema.properties ?? {};
579
596
  const bound = new Set(boundFields.filter((field) => field in properties));
580
597
  const unknownBound = boundFields.filter((field) => !(field in properties));
581
598
  if (unknownBound.length > 0) {
582
- throw validationError(['bindings'], `Bound field${unknownBound.length > 1 ? 's' : ''} ${unknownBound.join(', ')} not declared in "${definition.alias}".`, boundFields);
599
+ throw validationError(['bindings'], `Bound field${unknownBound.length > 1 ? 's' : ''} ${unknownBound.join(', ')} not declared in "${(0, define_js_1.collectionLabel)(definition)}".`, boundFields);
583
600
  }
584
601
  if (bound.size === 0)
585
602
  return strictParse(definition.schema, recordSchema, data, ['data']);
@@ -602,7 +619,7 @@ function validateUpdate(definition, update) {
602
619
  if (!isPlainObject(update) || Object.keys(update).length === 0) {
603
620
  throw validationError([], 'An update needs at least one operator such as `$set`.', update);
604
621
  }
605
- const { recordSchema } = compileCollection(definition);
622
+ const recordSchema = validationSchema(definition);
606
623
  const out = {};
607
624
  for (const [operator, fields] of Object.entries(update)) {
608
625
  if (!operator.startsWith('$')) {
@@ -616,10 +633,14 @@ function validateUpdate(definition, update) {
616
633
  if (path === '_id' || path === '_meta' || path.startsWith('_meta.')) {
617
634
  throw validationError(issuePath, '`_id` and `_meta` are read-only.', value);
618
635
  }
636
+ if (!definition.schema || !recordSchema) {
637
+ next[path] = value;
638
+ continue;
639
+ }
619
640
  const target = recordSchemaAt(recordSchema, path);
620
641
  const zodTarget = zodAt(definition.schema, path);
621
642
  if (!target || !zodTarget) {
622
- throw validationError(issuePath, `"${path}" is not a declared field of "${definition.alias}".`, value);
643
+ throw validationError(issuePath, `"${path}" is not a declared field of "${(0, define_js_1.collectionLabel)(definition)}".`, value);
623
644
  }
624
645
  if (VALUE_OPERATORS.has(operator)) {
625
646
  if (value === undefined)