@tier0/sdk-v2 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/cjs/data/bootstrap.js +5 -5
- package/dist/cjs/data/bootstrap.js.map +1 -1
- package/dist/cjs/data/define.d.ts +6 -0
- package/dist/cjs/data/define.js +11 -1
- package/dist/cjs/data/define.js.map +1 -1
- package/dist/cjs/data/schema.d.ts +1 -0
- package/dist/cjs/data/schema.js +7 -0
- package/dist/cjs/data/schema.js.map +1 -1
- package/dist/cjs/uns-v2/generated.d.ts +8 -7
- package/dist/cjs/uns-v2/generated.js +7 -7
- package/dist/cjs/uns-v2/generated.js.map +1 -1
- package/dist/esm/data/bootstrap.js +5 -5
- package/dist/esm/data/bootstrap.js.map +1 -1
- package/dist/esm/data/define.d.ts +6 -0
- package/dist/esm/data/define.js +9 -0
- package/dist/esm/data/define.js.map +1 -1
- package/dist/esm/data/schema.d.ts +1 -0
- package/dist/esm/data/schema.js +8 -1
- package/dist/esm/data/schema.js.map +1 -1
- package/dist/esm/uns-v2/generated.d.ts +8 -7
- package/dist/esm/uns-v2/generated.js +7 -7
- package/dist/esm/uns-v2/generated.js.map +1 -1
- package/package.json +1 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/SKILL.md +3 -0
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/consistency.md +3 -3
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/errors.md +1 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/modeling.md +6 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/read-write.md +3 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/schema-evolution.md +6 -4
- package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/create.md +6 -0
- package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/read.md +2 -0
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/create.md +1 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/namespace.md +4 -0
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
* changed. Rebuilds are limited to one per REBUILD_INTERVAL_MS per client;
|
|
23
23
|
* APP_GRANT_REVOKED is never retried (ensure itself reports it).
|
|
24
24
|
* - `ignored` notes never fail a request. ensure never writes annotations, so
|
|
25
|
-
* an edited `.describe()` or collection description comes back as
|
|
25
|
+
* an edited name, `.describe()` or collection description comes back as
|
|
26
26
|
* ANNOTATION_NOT_APPLIED; it is logged as a warning pointing at
|
|
27
|
-
*
|
|
27
|
+
* metadata:updateOne for names, or schema:replace for schema annotations.
|
|
28
28
|
*/
|
|
29
29
|
import { createHash } from 'node:crypto';
|
|
30
30
|
import { assertNoWriteErrors, MAX_ATOMIC_ITEMS } from './collection.js';
|
|
@@ -65,7 +65,7 @@ const CONFLICT_HINTS = {
|
|
|
65
65
|
LIMIT_EXCEEDED: 'the joined schema exceeds a UNS limit (depth, properties, enum values or indexes); split the structure',
|
|
66
66
|
OPEN_OBJECT: 'every object must be closed; declare it with z.object',
|
|
67
67
|
ALIAS_IN_USE: 'the alias belongs to another collection; pick another alias',
|
|
68
|
-
NAME_IN_USE: 'the name belongs to another collection; pick another alias',
|
|
68
|
+
NAME_IN_USE: 'the business name belongs to another collection in this folder; pick another name and keep the stable alias',
|
|
69
69
|
INVALID_INDEX: 'fix the index declaration',
|
|
70
70
|
JOIN_UNSUPPORTED: 'the stored schema holds a node the declaration cannot widen (e.g. enum values outside its range); repair it with schema:replace via the tier0 MCP',
|
|
71
71
|
DATA_RULE_FIELD: 'an employee data rule (ownerField / stateField) uses this field; keep it required with the same type, or ask a workspace admin to change the rule',
|
|
@@ -197,8 +197,8 @@ export function createBootstrap(config) {
|
|
|
197
197
|
}
|
|
198
198
|
if (annotations.length > 0) {
|
|
199
199
|
// A hint, not an error: storage keeps its annotations and serves as before.
|
|
200
|
-
logger.warn(`[data] ensure does not change stored titles/descriptions; not applied: ${annotations.map((note) => notePath(result.alias, note)).join(', ')}. ` +
|
|
201
|
-
`
|
|
200
|
+
logger.warn(`[data] ensure does not change stored names/titles/descriptions; not applied: ${annotations.map((note) => notePath(result.alias, note)).join(', ')}. ` +
|
|
201
|
+
`Rename with metadata:updateOne via the tier0 MCP; apply schema annotations with schema:replace, selecting alias, recordSchema, indexes and description from compileCollection(...).`);
|
|
202
202
|
}
|
|
203
203
|
}
|
|
204
204
|
await writeSeeds(results);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../src/data/bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAA2B,MAAM,aAAa,CAAC;AAyD3F,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,8DAA8D;AAC9D,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AAEnC,kEAAkE;AAClE,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAE1C;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAAc;IACnD,OAAO,CACL,KAAK,YAAY,SAAS;QAC1B,CAAC,KAAK,CAAC,MAAM,KAAK,cAAc,CAAC,UAAU,IAAI,KAAK,CAAC,MAAM,KAAK,cAAc,CAAC,QAAQ,CAAC,CACzF,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,CAAc,EAAE,CAAc;IACvD,IAAI,CAAC,CAAC,aAAa,CAAC,IAAI,KAAK,CAAC,CAAC,aAAa,CAAC,IAAI;QAAE,OAAO,KAAK,CA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,OAAO,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,KAAkB,CAAC,CAAC;YAC1D,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,KAAK,KAAK;gBAAE,MAAM,KAAK,CAAC;YACrD,OAAO,EAAE,EAAE,CAAC;QACd,CAAC;IACH,CAAC;IAED,KAAK,UAAU,OAAO,CAAC,UAAgC;QACrD,MAAM,KAAK,GAAG,MAAM,MAAM,EAAE,CAAC;QAC7B,MAAM,EAAE,GAAG,KAAK,CAAC,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC;QACnE,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,MAAM,IAAI,SAAS,CAAC;gBAClB,OAAO,EAAE,eAAe,UAAU,CAAC,KAAK,kEAAkE;gBAC1G,MAAM,EAAE,GAAG;gBACX,IAAI,EAAE,wBAAwB;aAC/B,CAAC,CAAC;QACL,CAAC;QACD,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC/C,CAAC","sourcesContent":["/**\n * First-access bootstrap: one batched `ensure` of every declared collection.\n *\n * - ensure only creates or widens; storage never narrows from here, so old\n * and new code may cold-start in any order.\n * - The result is memoized per client, i.e. per server process; a client\n * built from edited declarations ensures again.\n * Failures are not memoized: a later call retries (an imported App may\n * answer \"hosted App is not ready\").\n * - Seed documents are inserted only for collections ensure reports as\n * `created`: fixed `_id`s, atomic chunks of 200 with a stable idempotency\n * key per chunk, so a failed chunk (outcome unknown, or marked safe to\n * resend) is replayed after a short wait instead of duplicated. Seed writes\n * never carry a data subject.\n * - Preview throws on SCHEMA_CONFLICT and warnings so the worker sees them;\n * a deployment logs them and keeps serving with the IDs it has.\n * - Self-healing: a Preview reset hard-deletes collections, and a worker or\n * admin may archive one, while this process still holds the old IDs. A\n * record call that fails with `data.reason` COLLECTION_NOT_FOUND or\n * COLLECTION_NOT_GRANTED drops the memo, ensures again (seeding what is created)\n * and retries the call once, but only when a collection ID actually\n * changed. Rebuilds are limited to one per REBUILD_INTERVAL_MS per client;\n * APP_GRANT_REVOKED is never retried (ensure itself reports it).\n * - `ignored` notes never fail a request. ensure never writes annotations, so\n * an edited `.describe()` or collection description comes back as\n * ANNOTATION_NOT_APPLIED; it is logged as a warning pointing at\n * schema:replace, which is the only way to change stored annotations.\n */\nimport { createHash } from 'node:crypto';\nimport type { DataCall } from './call.js';\nimport { assertNoWriteErrors, MAX_ATOMIC_ITEMS } from './collection.js';\nimport type { CollectionDefinition } from './define.js';\nimport { ACCESS_REASONS, DataError } from './error.js';\nimport { compileCollection, validateDocument, type CompiledCollection } from './schema.js';\n\nexport type DataEnvironment = 'preview' | 'deployed';\n\nexport interface EnsureWarning {\n code: string;\n path?: string;\n message?: string;\n}\n\nexport interface EnsureNote {\n path: string;\n reason?: string;\n message?: string;\n}\n\nexport interface EnsureResult {\n alias: string;\n collectionId: string;\n revision: number;\n status: 'created' | 'unchanged' | 'widened';\n ignored?: EnsureNote[];\n warnings?: EnsureWarning[];\n indexStatus?: unknown[];\n}\n\nexport interface EnsureConflict {\n alias: string;\n collectionId?: string;\n path?: string;\n reason?: string;\n current?: string;\n declared?: string;\n}\n\nexport interface EnsureState {\n appId?: string;\n results: EnsureResult[];\n /** Lower-cased alias → collection ID. */\n collectionIds: Map<string, string>;\n /** Declarations that conflicted in a deployment (served with their existing ID, if any). */\n conflicts: EnsureConflict[];\n}\n\nexport interface Logger {\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\nexport interface BootstrapConfig {\n call: DataCall;\n collections: readonly CollectionDefinition[];\n environment: DataEnvironment;\n logger: Logger;\n}\n\nconst SEED_ATTEMPTS = 3;\n/** Wait before replaying seed chunk attempt n+1: n × this. */\nexport const SEED_RETRY_MS = 1_000;\n\n/** At most one self-healing rebuild per client in this window. */\nexport const REBUILD_INTERVAL_MS = 30_000;\n\n/**\n * Whether a record call failed because the collection ID it used is gone or\n * no longer granted, by UNS's stable `data.reason` code. Archive and Preview\n * purge also remove the App grant, so most stale IDs answer\n * COLLECTION_NOT_GRANTED or COLLECTION_NOT_FOUND. APP_PERMISSION_MISSING (the\n * key lacks e.g. `uns.delete`) and APP_GRANT_REVOKED are not stale IDs.\n */\nexport function isStaleCollectionError(error: unknown): boolean {\n return (\n error instanceof DataError &&\n (error.reason === ACCESS_REASONS.notGranted || error.reason === ACCESS_REASONS.notFound)\n );\n}\n\nfunction sameCollectionIds(a: EnsureState, b: EnsureState): boolean {\n if (a.collectionIds.size !== b.collectionIds.size) return false;\n for (const [alias, id] of a.collectionIds) {\n if (b.collectionIds.get(alias) !== id) return false;\n }\n return true;\n}\n\n/** Idempotency key of one seed chunk (UNS keys are at most 96 characters). */\nfunction seedChunkKey(collectionId: string, chunk: number): string {\n return `seed-${createHash('sha256').update(collectionId).digest('hex').slice(0, 40)}-${chunk}`;\n}\n\n/** What to do about each SCHEMA_CONFLICT reason (CloudAppCollectionConflict.reason). */\nconst CONFLICT_HINTS: Record<string, string> = {\n TYPE_CONFLICT: \"a field's type cannot change; use a new field name and backfill with updateMany\",\n LIMIT_EXCEEDED: 'the joined schema exceeds a UNS limit (depth, properties, enum values or indexes); split the structure',\n OPEN_OBJECT: 'every object must be closed; declare it with z.object',\n ALIAS_IN_USE: 'the alias belongs to another collection; pick another alias',\n NAME_IN_USE: 'the name belongs to another collection; pick another alias',\n INVALID_INDEX: 'fix the index declaration',\n JOIN_UNSUPPORTED:\n 'the stored schema holds a node the declaration cannot widen (e.g. enum values outside its range); repair it with schema:replace via the tier0 MCP',\n DATA_RULE_FIELD:\n 'an employee data rule (ownerField / stateField) uses this field; keep it required with the same type, or ask a workspace admin to change the rule',\n};\n\nfunction describeConflicts(conflicts: EnsureConflict[]): string {\n return conflicts\n .map((conflict) => {\n const where = `${conflict.alias}${conflict.path ? `.${conflict.path}` : ''}`;\n const types = conflict.current || conflict.declared ? ` (stored ${conflict.current ?? '?'}, declared ${conflict.declared ?? '?'})` : '';\n const hint = conflict.reason && CONFLICT_HINTS[conflict.reason] ? ` — ${CONFLICT_HINTS[conflict.reason]}` : '';\n return ` - ${where}: ${conflict.reason ?? 'conflict'}${types}${hint}`;\n })\n .join('\\n');\n}\n\nfunction notePath(alias: string, note: EnsureNote): string {\n return note.path ? `${alias}.${note.path}` : alias;\n}\n\nfunction describeWarnings(results: EnsureResult[]): string {\n return results\n .flatMap((result) =>\n (result.warnings ?? []).map(\n (warning) => ` - ${result.alias}${warning.path ? `.${warning.path}` : ''}: ${warning.code}${warning.message ? ` — ${warning.message}` : ''}`,\n ),\n )\n .join('\\n');\n}\n\nexport function createBootstrap(config: BootstrapConfig) {\n const { call, collections, environment, logger } = config;\n let pending: Promise<EnsureState> | null = null;\n let lastRebuild = Number.NEGATIVE_INFINITY;\n\n async function requestEnsure(items: CompiledCollection[]) {\n // ensure is App-level work: it never carries the employee data subject.\n return call<{ appId?: string; results: EnsureResult[] }>('appCollectionsEnsure', { collections: items });\n }\n\n async function insertSeedChunk(collectionId: string, chunk: number, documents: { id?: string; data: Record<string, unknown> }[]) {\n for (let attempt = 1; ; attempt += 1) {\n try {\n const result = await call<{ writeErrors?: Record<string, unknown>[] }>('recordBulkWrite', {\n collectionId,\n operations: documents.map(document => ({ insertOne: document })),\n ordered: true,\n atomic: true,\n idempotencyKey: seedChunkKey(collectionId, chunk),\n });\n assertNoWriteErrors(result, 'seed');\n return;\n } catch (error) {\n // The chunk key is stable, so replaying is safe even when the outcome is unknown: a chunk\n // that did commit replays its receipt. Wait first, so a write still running can finish.\n if (!(error instanceof DataError) || !(error.outcomeUnknown || error.retry.safe) || attempt >= SEED_ATTEMPTS) throw error;\n await new Promise((resolve) => setTimeout(resolve, SEED_RETRY_MS * attempt));\n }\n }\n }\n\n async function writeSeeds(results: EnsureResult[]) {\n for (const result of results) {\n if (result.status !== 'created') continue;\n const definition = collections.find((candidate) => candidate.alias.toLowerCase() === result.alias.toLowerCase());\n const seed = definition?.seed;\n if (!definition || !seed || seed.length === 0) continue;\n try {\n const documents = seed.map((document) => {\n const { id, data } = validateDocument(definition, document as Record<string, unknown>);\n return { id, data };\n });\n for (let start = 0; start < documents.length; start += MAX_ATOMIC_ITEMS) {\n await insertSeedChunk(result.collectionId, start / MAX_ATOMIC_ITEMS, documents.slice(start, start + MAX_ATOMIC_ITEMS));\n }\n logger.info(`[data] seeded ${documents.length} record(s) into \"${result.alias}\"`);\n } catch (error) {\n // The collection exists now; a later ensure reports \"unchanged\" and\n // never re-seeds, so the failure must be visible in the server log.\n logger.error(`[data] seed for new collection \"${result.alias}\" failed; it keeps the chunks written so far:`, error);\n }\n }\n }\n\n async function run(payload: CompiledCollection[]): Promise<EnsureState> {\n const conflicts: EnsureConflict[] = [];\n let remaining = payload;\n let response: { appId?: string; results: EnsureResult[] } = { results: [] };\n while (remaining.length > 0) {\n try {\n response = await requestEnsure(remaining);\n break;\n } catch (error) {\n if (!(error instanceof DataError) || error.code !== 'SCHEMA_CONFLICT') throw error;\n const reported = Array.isArray(error.details.conflicts) ? (error.details.conflicts as EnsureConflict[]) : [];\n const summary = describeConflicts(reported);\n if (environment === 'preview') {\n throw new DataError({\n message:\n `The collection declarations conflict with the stored collection schemas; nothing was changed:\\n${summary}`,\n status: 409,\n code: 'SCHEMA_CONFLICT',\n upstreamStatus: error.upstreamStatus,\n requestId: error.requestId,\n execution: error.execution,\n attempts: error.attempts,\n details: error.details,\n });\n }\n // A deployment keeps serving: drop the conflicting declarations (the\n // whole batch was rejected) and ensure the rest again.\n const conflicting = new Set(reported.map((conflict) => conflict.alias.toLowerCase()));\n const next = remaining.filter((item) => !conflicting.has(item.alias.toLowerCase()));\n if (next.length === remaining.length) throw error;\n logger.error(`[data] ensure: declarations conflict with stored schemas; serving them unchanged:\\n${summary}`);\n conflicts.push(...reported);\n remaining = next;\n }\n }\n\n const results = response.results ?? [];\n const collectionIds = new Map<string, string>();\n for (const conflict of conflicts) {\n if (conflict.collectionId) collectionIds.set(conflict.alias.toLowerCase(), conflict.collectionId);\n }\n for (const result of results) {\n collectionIds.set(result.alias.toLowerCase(), result.collectionId);\n const notes = result.ignored ?? [];\n const annotations = notes.filter((note) => note.reason === 'ANNOTATION_NOT_APPLIED');\n const wider = notes.filter((note) => note.reason !== 'ANNOTATION_NOT_APPLIED');\n if (wider.length > 0) {\n logger.info(\n `[data] \"${result.alias}\" storage is wider than this declaration (or has retired parts); ignored: ` +\n wider.map((note) => `${note.path || '(root)'} ${note.reason ?? ''}`.trim()).join(', '),\n );\n }\n if (annotations.length > 0) {\n // A hint, not an error: storage keeps its annotations and serves as before.\n logger.warn(\n `[data] ensure does not change stored titles/descriptions; not applied: ${annotations.map((note) => notePath(result.alias, note)).join(', ')}. ` +\n `Apply them with schema:replace via the tier0 MCP, using compileCollection(...) of the declaration as the body.`,\n );\n }\n }\n\n await writeSeeds(results);\n\n const warnings = describeWarnings(results);\n if (warnings) {\n if (environment === 'preview') {\n throw new DataError({\n message:\n `Collections were ensured with warnings:\\n${warnings}\\n` +\n 'REQUIRED_NOT_ENFORCED: make the field optional again or narrow explicitly with schema:replace via the tier0 MCP. ' +\n 'INDEX_BUILD_FAILED: fix the duplicate or invalid data, then the next ensure retries the index.',\n status: 500,\n code: 'SCHEMA_WARNINGS',\n // ensure did apply; only the warnings fail the Preview request.\n execution: 'committed',\n details: { results },\n });\n }\n logger.warn(`[data] ensure warnings:\\n${warnings}`);\n }\n\n return { appId: response.appId, results, collectionIds, conflicts };\n }\n\n /** Ensures every declaration once per client; a failure is forgotten so the next call retries. */\n function ensure(): Promise<EnsureState> {\n pending ??= Promise.resolve()\n .then(() => run(collections.map(compileCollection)))\n .catch((error) => {\n pending = null;\n throw error;\n });\n return pending;\n }\n\n /**\n * Re-ensures after `before` turned out stale. Joins a rebuild already in\n * flight; otherwise rebuilds at most once per REBUILD_INTERVAL_MS. Resolves\n * whether any collection ID changed; ensure errors (APP_GRANT_REVOKED, …)\n * propagate.\n */\n async function rebuild(before: EnsureState, cause: DataError): Promise<boolean> {\n const current = ensure();\n const latest = await current;\n if (latest !== before) return !sameCollectionIds(before, latest);\n if (pending !== current) return !sameCollectionIds(before, await ensure());\n const now = Date.now();\n if (now - lastRebuild < REBUILD_INTERVAL_MS) return false;\n lastRebuild = now;\n logger.warn(`[data] a collection ID is no longer usable (${cause.code}: ${cause.message}); ensuring collections again`);\n pending = null;\n return !sameCollectionIds(before, await ensure());\n }\n\n /**\n * Runs one data call; when it fails on a stale collection ID, rebuilds and\n * runs it once more if an ID changed. `retry: false` (calls continuing a\n * cursor or resumeAfter token of the old collection) only rebuilds.\n */\n async function recover<R>(fn: () => Promise<R>, options: { retry?: boolean } = {}): Promise<R> {\n const before = await ensure();\n try {\n return await fn();\n } catch (error) {\n if (!isStaleCollectionError(error)) throw error;\n const changed = await rebuild(before, error as DataError);\n if (!changed || options.retry === false) throw error;\n return fn();\n }\n }\n\n async function resolve(definition: CollectionDefinition): Promise<string> {\n const state = await ensure();\n const id = state.collectionIds.get(definition.alias.toLowerCase());\n if (!id) {\n throw new DataError({\n message: `Collection \"${definition.alias}\" is unavailable: ensure did not return it (see the server log).`,\n status: 503,\n code: 'COLLECTION_UNAVAILABLE',\n });\n }\n return id;\n }\n\n return { ensure, resolve, recover, rebuild };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../src/data/bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAA2B,MAAM,aAAa,CAAC;AAyD3F,MAAM,aAAa,GAAG,CAAC,CAAC;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bootstrap: one batched `ensure` of every declared collection.\n *\n * - ensure only creates or widens; storage never narrows from here, so old\n * and new code may cold-start in any order.\n * - The result is memoized per client, i.e. per server process; a client\n * built from edited declarations ensures again.\n * Failures are not memoized: a later call retries (an imported App may\n * answer \"hosted App is not ready\").\n * - Seed documents are inserted only for collections ensure reports as\n * `created`: fixed `_id`s, atomic chunks of 200 with a stable idempotency\n * key per chunk, so a failed chunk (outcome unknown, or marked safe to\n * resend) is replayed after a short wait instead of duplicated. Seed writes\n * never carry a data subject.\n * - Preview throws on SCHEMA_CONFLICT and warnings so the worker sees them;\n * a deployment logs them and keeps serving with the IDs it has.\n * - Self-healing: a Preview reset hard-deletes collections, and a worker or\n * admin may archive one, while this process still holds the old IDs. A\n * record call that fails with `data.reason` COLLECTION_NOT_FOUND or\n * COLLECTION_NOT_GRANTED drops the memo, ensures again (seeding what is created)\n * and retries the call once, but only when a collection ID actually\n * changed. Rebuilds are limited to one per REBUILD_INTERVAL_MS per client;\n * APP_GRANT_REVOKED is never retried (ensure itself reports it).\n * - `ignored` notes never fail a request. ensure never writes annotations, so\n * an edited name, `.describe()` or collection description comes back as\n * ANNOTATION_NOT_APPLIED; it is logged as a warning pointing at\n * metadata:updateOne for names, or schema:replace for schema annotations.\n */\nimport { createHash } from 'node:crypto';\nimport type { DataCall } from './call.js';\nimport { assertNoWriteErrors, MAX_ATOMIC_ITEMS } from './collection.js';\nimport type { CollectionDefinition } from './define.js';\nimport { ACCESS_REASONS, DataError } from './error.js';\nimport { compileCollection, validateDocument, type CompiledCollection } from './schema.js';\n\nexport type DataEnvironment = 'preview' | 'deployed';\n\nexport interface EnsureWarning {\n code: string;\n path?: string;\n message?: string;\n}\n\nexport interface EnsureNote {\n path: string;\n reason?: string;\n message?: string;\n}\n\nexport interface EnsureResult {\n alias: string;\n collectionId: string;\n revision: number;\n status: 'created' | 'unchanged' | 'widened';\n ignored?: EnsureNote[];\n warnings?: EnsureWarning[];\n indexStatus?: unknown[];\n}\n\nexport interface EnsureConflict {\n alias: string;\n collectionId?: string;\n path?: string;\n reason?: string;\n current?: string;\n declared?: string;\n}\n\nexport interface EnsureState {\n appId?: string;\n results: EnsureResult[];\n /** Lower-cased alias → collection ID. */\n collectionIds: Map<string, string>;\n /** Declarations that conflicted in a deployment (served with their existing ID, if any). */\n conflicts: EnsureConflict[];\n}\n\nexport interface Logger {\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\nexport interface BootstrapConfig {\n call: DataCall;\n collections: readonly CollectionDefinition[];\n environment: DataEnvironment;\n logger: Logger;\n}\n\nconst SEED_ATTEMPTS = 3;\n/** Wait before replaying seed chunk attempt n+1: n × this. */\nexport const SEED_RETRY_MS = 1_000;\n\n/** At most one self-healing rebuild per client in this window. */\nexport const REBUILD_INTERVAL_MS = 30_000;\n\n/**\n * Whether a record call failed because the collection ID it used is gone or\n * no longer granted, by UNS's stable `data.reason` code. Archive and Preview\n * purge also remove the App grant, so most stale IDs answer\n * COLLECTION_NOT_GRANTED or COLLECTION_NOT_FOUND. APP_PERMISSION_MISSING (the\n * key lacks e.g. `uns.delete`) and APP_GRANT_REVOKED are not stale IDs.\n */\nexport function isStaleCollectionError(error: unknown): boolean {\n return (\n error instanceof DataError &&\n (error.reason === ACCESS_REASONS.notGranted || error.reason === ACCESS_REASONS.notFound)\n );\n}\n\nfunction sameCollectionIds(a: EnsureState, b: EnsureState): boolean {\n if (a.collectionIds.size !== b.collectionIds.size) return false;\n for (const [alias, id] of a.collectionIds) {\n if (b.collectionIds.get(alias) !== id) return false;\n }\n return true;\n}\n\n/** Idempotency key of one seed chunk (UNS keys are at most 96 characters). */\nfunction seedChunkKey(collectionId: string, chunk: number): string {\n return `seed-${createHash('sha256').update(collectionId).digest('hex').slice(0, 40)}-${chunk}`;\n}\n\n/** What to do about each SCHEMA_CONFLICT reason (CloudAppCollectionConflict.reason). */\nconst CONFLICT_HINTS: Record<string, string> = {\n TYPE_CONFLICT: \"a field's type cannot change; use a new field name and backfill with updateMany\",\n LIMIT_EXCEEDED: 'the joined schema exceeds a UNS limit (depth, properties, enum values or indexes); split the structure',\n OPEN_OBJECT: 'every object must be closed; declare it with z.object',\n ALIAS_IN_USE: 'the alias belongs to another collection; pick another alias',\n NAME_IN_USE: 'the business name belongs to another collection in this folder; pick another name and keep the stable alias',\n INVALID_INDEX: 'fix the index declaration',\n JOIN_UNSUPPORTED:\n 'the stored schema holds a node the declaration cannot widen (e.g. enum values outside its range); repair it with schema:replace via the tier0 MCP',\n DATA_RULE_FIELD:\n 'an employee data rule (ownerField / stateField) uses this field; keep it required with the same type, or ask a workspace admin to change the rule',\n};\n\nfunction describeConflicts(conflicts: EnsureConflict[]): string {\n return conflicts\n .map((conflict) => {\n const where = `${conflict.alias}${conflict.path ? `.${conflict.path}` : ''}`;\n const types = conflict.current || conflict.declared ? ` (stored ${conflict.current ?? '?'}, declared ${conflict.declared ?? '?'})` : '';\n const hint = conflict.reason && CONFLICT_HINTS[conflict.reason] ? ` — ${CONFLICT_HINTS[conflict.reason]}` : '';\n return ` - ${where}: ${conflict.reason ?? 'conflict'}${types}${hint}`;\n })\n .join('\\n');\n}\n\nfunction notePath(alias: string, note: EnsureNote): string {\n return note.path ? `${alias}.${note.path}` : alias;\n}\n\nfunction describeWarnings(results: EnsureResult[]): string {\n return results\n .flatMap((result) =>\n (result.warnings ?? []).map(\n (warning) => ` - ${result.alias}${warning.path ? `.${warning.path}` : ''}: ${warning.code}${warning.message ? ` — ${warning.message}` : ''}`,\n ),\n )\n .join('\\n');\n}\n\nexport function createBootstrap(config: BootstrapConfig) {\n const { call, collections, environment, logger } = config;\n let pending: Promise<EnsureState> | null = null;\n let lastRebuild = Number.NEGATIVE_INFINITY;\n\n async function requestEnsure(items: CompiledCollection[]) {\n // ensure is App-level work: it never carries the employee data subject.\n return call<{ appId?: string; results: EnsureResult[] }>('appCollectionsEnsure', { collections: items });\n }\n\n async function insertSeedChunk(collectionId: string, chunk: number, documents: { id?: string; data: Record<string, unknown> }[]) {\n for (let attempt = 1; ; attempt += 1) {\n try {\n const result = await call<{ writeErrors?: Record<string, unknown>[] }>('recordBulkWrite', {\n collectionId,\n operations: documents.map(document => ({ insertOne: document })),\n ordered: true,\n atomic: true,\n idempotencyKey: seedChunkKey(collectionId, chunk),\n });\n assertNoWriteErrors(result, 'seed');\n return;\n } catch (error) {\n // The chunk key is stable, so replaying is safe even when the outcome is unknown: a chunk\n // that did commit replays its receipt. Wait first, so a write still running can finish.\n if (!(error instanceof DataError) || !(error.outcomeUnknown || error.retry.safe) || attempt >= SEED_ATTEMPTS) throw error;\n await new Promise((resolve) => setTimeout(resolve, SEED_RETRY_MS * attempt));\n }\n }\n }\n\n async function writeSeeds(results: EnsureResult[]) {\n for (const result of results) {\n if (result.status !== 'created') continue;\n const definition = collections.find((candidate) => candidate.alias.toLowerCase() === result.alias.toLowerCase());\n const seed = definition?.seed;\n if (!definition || !seed || seed.length === 0) continue;\n try {\n const documents = seed.map((document) => {\n const { id, data } = validateDocument(definition, document as Record<string, unknown>);\n return { id, data };\n });\n for (let start = 0; start < documents.length; start += MAX_ATOMIC_ITEMS) {\n await insertSeedChunk(result.collectionId, start / MAX_ATOMIC_ITEMS, documents.slice(start, start + MAX_ATOMIC_ITEMS));\n }\n logger.info(`[data] seeded ${documents.length} record(s) into \"${result.alias}\"`);\n } catch (error) {\n // The collection exists now; a later ensure reports \"unchanged\" and\n // never re-seeds, so the failure must be visible in the server log.\n logger.error(`[data] seed for new collection \"${result.alias}\" failed; it keeps the chunks written so far:`, error);\n }\n }\n }\n\n async function run(payload: CompiledCollection[]): Promise<EnsureState> {\n const conflicts: EnsureConflict[] = [];\n let remaining = payload;\n let response: { appId?: string; results: EnsureResult[] } = { results: [] };\n while (remaining.length > 0) {\n try {\n response = await requestEnsure(remaining);\n break;\n } catch (error) {\n if (!(error instanceof DataError) || error.code !== 'SCHEMA_CONFLICT') throw error;\n const reported = Array.isArray(error.details.conflicts) ? (error.details.conflicts as EnsureConflict[]) : [];\n const summary = describeConflicts(reported);\n if (environment === 'preview') {\n throw new DataError({\n message:\n `The collection declarations conflict with the stored collection schemas; nothing was changed:\\n${summary}`,\n status: 409,\n code: 'SCHEMA_CONFLICT',\n upstreamStatus: error.upstreamStatus,\n requestId: error.requestId,\n execution: error.execution,\n attempts: error.attempts,\n details: error.details,\n });\n }\n // A deployment keeps serving: drop the conflicting declarations (the\n // whole batch was rejected) and ensure the rest again.\n const conflicting = new Set(reported.map((conflict) => conflict.alias.toLowerCase()));\n const next = remaining.filter((item) => !conflicting.has(item.alias.toLowerCase()));\n if (next.length === remaining.length) throw error;\n logger.error(`[data] ensure: declarations conflict with stored schemas; serving them unchanged:\\n${summary}`);\n conflicts.push(...reported);\n remaining = next;\n }\n }\n\n const results = response.results ?? [];\n const collectionIds = new Map<string, string>();\n for (const conflict of conflicts) {\n if (conflict.collectionId) collectionIds.set(conflict.alias.toLowerCase(), conflict.collectionId);\n }\n for (const result of results) {\n collectionIds.set(result.alias.toLowerCase(), result.collectionId);\n const notes = result.ignored ?? [];\n const annotations = notes.filter((note) => note.reason === 'ANNOTATION_NOT_APPLIED');\n const wider = notes.filter((note) => note.reason !== 'ANNOTATION_NOT_APPLIED');\n if (wider.length > 0) {\n logger.info(\n `[data] \"${result.alias}\" storage is wider than this declaration (or has retired parts); ignored: ` +\n wider.map((note) => `${note.path || '(root)'} ${note.reason ?? ''}`.trim()).join(', '),\n );\n }\n if (annotations.length > 0) {\n // A hint, not an error: storage keeps its annotations and serves as before.\n logger.warn(\n `[data] ensure does not change stored names/titles/descriptions; not applied: ${annotations.map((note) => notePath(result.alias, note)).join(', ')}. ` +\n `Rename with metadata:updateOne via the tier0 MCP; apply schema annotations with schema:replace, selecting alias, recordSchema, indexes and description from compileCollection(...).`,\n );\n }\n }\n\n await writeSeeds(results);\n\n const warnings = describeWarnings(results);\n if (warnings) {\n if (environment === 'preview') {\n throw new DataError({\n message:\n `Collections were ensured with warnings:\\n${warnings}\\n` +\n 'REQUIRED_NOT_ENFORCED: make the field optional again or narrow explicitly with schema:replace via the tier0 MCP. ' +\n 'INDEX_BUILD_FAILED: fix the duplicate or invalid data, then the next ensure retries the index.',\n status: 500,\n code: 'SCHEMA_WARNINGS',\n // ensure did apply; only the warnings fail the Preview request.\n execution: 'committed',\n details: { results },\n });\n }\n logger.warn(`[data] ensure warnings:\\n${warnings}`);\n }\n\n return { appId: response.appId, results, collectionIds, conflicts };\n }\n\n /** Ensures every declaration once per client; a failure is forgotten so the next call retries. */\n function ensure(): Promise<EnsureState> {\n pending ??= Promise.resolve()\n .then(() => run(collections.map(compileCollection)))\n .catch((error) => {\n pending = null;\n throw error;\n });\n return pending;\n }\n\n /**\n * Re-ensures after `before` turned out stale. Joins a rebuild already in\n * flight; otherwise rebuilds at most once per REBUILD_INTERVAL_MS. Resolves\n * whether any collection ID changed; ensure errors (APP_GRANT_REVOKED, …)\n * propagate.\n */\n async function rebuild(before: EnsureState, cause: DataError): Promise<boolean> {\n const current = ensure();\n const latest = await current;\n if (latest !== before) return !sameCollectionIds(before, latest);\n if (pending !== current) return !sameCollectionIds(before, await ensure());\n const now = Date.now();\n if (now - lastRebuild < REBUILD_INTERVAL_MS) return false;\n lastRebuild = now;\n logger.warn(`[data] a collection ID is no longer usable (${cause.code}: ${cause.message}); ensuring collections again`);\n pending = null;\n return !sameCollectionIds(before, await ensure());\n }\n\n /**\n * Runs one data call; when it fails on a stale collection ID, rebuilds and\n * runs it once more if an ID changed. `retry: false` (calls continuing a\n * cursor or resumeAfter token of the old collection) only rebuilds.\n */\n async function recover<R>(fn: () => Promise<R>, options: { retry?: boolean } = {}): Promise<R> {\n const before = await ensure();\n try {\n return await fn();\n } catch (error) {\n if (!isStaleCollectionError(error)) throw error;\n const changed = await rebuild(before, error as DataError);\n if (!changed || options.retry === false) throw error;\n return fn();\n }\n }\n\n async function resolve(definition: CollectionDefinition): Promise<string> {\n const state = await ensure();\n const id = state.collectionIds.get(definition.alias.toLowerCase());\n if (!id) {\n throw new DataError({\n message: `Collection \"${definition.alias}\" is unavailable: ensure did not return it (see the server log).`,\n status: 503,\n code: 'COLLECTION_UNAVAILABLE',\n });\n }\n return id;\n }\n\n return { ensure, resolve, recover, rebuild };\n}\n"]}
|
|
@@ -16,6 +16,8 @@ export declare const ALIAS_PATTERN: RegExp;
|
|
|
16
16
|
export declare const MAX_COLLECTIONS = 64;
|
|
17
17
|
/** UNS: collection description length in characters. */
|
|
18
18
|
export declare const MAX_DESCRIPTION_LENGTH = 512;
|
|
19
|
+
/** UNS: business-facing collection name length in Unicode characters. */
|
|
20
|
+
export declare const MAX_NAME_LENGTH = 63;
|
|
19
21
|
/** Seeds are inserted in atomic chunks of 200 during the first request; keep them a baseline, not a data import. */
|
|
20
22
|
export declare const MAX_SEED_DOCUMENTS = 1000;
|
|
21
23
|
/** Same shape as collection metadata indexes, limited to record indexes. */
|
|
@@ -49,6 +51,8 @@ export type SeedDoc<S extends CollectionSchema> = z.input<S> & {
|
|
|
49
51
|
};
|
|
50
52
|
export interface CollectionDefinition<S extends CollectionSchema = CollectionSchema> {
|
|
51
53
|
readonly alias: string;
|
|
54
|
+
/** Business-facing name, independent of the stable App alias. */
|
|
55
|
+
readonly name: string;
|
|
52
56
|
/** Zod 4 object schema of the record body (no `_id` / `_meta`). */
|
|
53
57
|
readonly schema: S;
|
|
54
58
|
readonly indexes: readonly IndexSpec[];
|
|
@@ -70,8 +74,10 @@ export type NewDoc<C extends CollectionDefinition> = z.input<C['schema']> & {
|
|
|
70
74
|
};
|
|
71
75
|
export declare function defineCollection<S extends CollectionSchema>(definition: {
|
|
72
76
|
alias: string;
|
|
77
|
+
name: string;
|
|
73
78
|
schema: S;
|
|
74
79
|
indexes?: IndexSpec[];
|
|
75
80
|
description?: string;
|
|
76
81
|
seed?: SeedDoc<S>[];
|
|
77
82
|
}): CollectionDefinition<S>;
|
|
83
|
+
export declare function assertCollectionName(name: unknown): asserts name is string;
|
package/dist/esm/data/define.js
CHANGED
|
@@ -4,12 +4,15 @@ export const ALIAS_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,62}$/;
|
|
|
4
4
|
export const MAX_COLLECTIONS = 64;
|
|
5
5
|
/** UNS: collection description length in characters. */
|
|
6
6
|
export const MAX_DESCRIPTION_LENGTH = 512;
|
|
7
|
+
/** UNS: business-facing collection name length in Unicode characters. */
|
|
8
|
+
export const MAX_NAME_LENGTH = 63;
|
|
7
9
|
/** Seeds are inserted in atomic chunks of 200 during the first request; keep them a baseline, not a data import. */
|
|
8
10
|
export const MAX_SEED_DOCUMENTS = 1000;
|
|
9
11
|
export function defineCollection(definition) {
|
|
10
12
|
if (!ALIAS_PATTERN.test(definition.alias)) {
|
|
11
13
|
throw new Error(`Collection alias "${definition.alias}" must match ${ALIAS_PATTERN} (letters, digits, "_" or "-", starting with a letter).`);
|
|
12
14
|
}
|
|
15
|
+
assertCollectionName(definition.name);
|
|
13
16
|
if (definition.description && [...definition.description].length > MAX_DESCRIPTION_LENGTH) {
|
|
14
17
|
throw new Error(`Collection "${definition.alias}": description is longer than ${MAX_DESCRIPTION_LENGTH} characters.`);
|
|
15
18
|
}
|
|
@@ -18,10 +21,16 @@ export function defineCollection(definition) {
|
|
|
18
21
|
}
|
|
19
22
|
return Object.freeze({
|
|
20
23
|
alias: definition.alias,
|
|
24
|
+
name: definition.name,
|
|
21
25
|
schema: definition.schema,
|
|
22
26
|
indexes: Object.freeze([...(definition.indexes ?? [])]),
|
|
23
27
|
...(definition.description ? { description: definition.description } : {}),
|
|
24
28
|
...(definition.seed ? { seed: Object.freeze([...definition.seed]) } : {}),
|
|
25
29
|
});
|
|
26
30
|
}
|
|
31
|
+
export function assertCollectionName(name) {
|
|
32
|
+
if (typeof name !== 'string' || name.length === 0 || name.trim() !== name || [...name].length > MAX_NAME_LENGTH || /[\/\0]/.test(name)) {
|
|
33
|
+
throw new Error(`Collection name must be nonempty, at most ${MAX_NAME_LENGTH} Unicode characters, without surrounding whitespace, "/" or NUL.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
27
36
|
//# sourceMappingURL=define.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../../src/data/define.ts"],"names":[],"mappings":"AAaA,0DAA0D;AAC1D,MAAM,CAAC,MAAM,aAAa,GAAG,+BAA+B,CAAC;AAC7D,uFAAuF;AACvF,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAClC,wDAAwD;AACxD,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAC1C,oHAAoH;AACpH,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../../src/data/define.ts"],"names":[],"mappings":"AAaA,0DAA0D;AAC1D,MAAM,CAAC,MAAM,aAAa,GAAG,+BAA+B,CAAC;AAC7D,uFAAuF;AACvF,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAClC,wDAAwD;AACxD,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAC1C,yEAAyE;AACzE,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAClC,oHAAoH;AACpH,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;AA2DvC,MAAM,UAAU,gBAAgB,CAA6B,UAO5D;IACC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CACb,qBAAqB,UAAU,CAAC,KAAK,gBAAgB,aAAa,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,sBAAsB,EAAE,CAAC;QAC1F,MAAM,IAAI,KAAK,CAAC,eAAe,UAAU,CA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/**\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"]}
|
|
@@ -37,6 +37,7 @@ export interface NormalizedIndex {
|
|
|
37
37
|
/** One ensure item, exactly as it is sent to `/uns/app/collections/ensure`. */
|
|
38
38
|
export interface CompiledCollection {
|
|
39
39
|
alias: string;
|
|
40
|
+
name: string;
|
|
40
41
|
recordSchema: RecordSchema;
|
|
41
42
|
indexes: NormalizedIndex[];
|
|
42
43
|
description?: string;
|
package/dist/esm/data/schema.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* time) instead of on the first request.
|
|
11
11
|
*/
|
|
12
12
|
import { z } from 'zod';
|
|
13
|
-
import { ALIAS_PATTERN } from './define.js';
|
|
13
|
+
import { ALIAS_PATTERN, assertCollectionName } from './define.js';
|
|
14
14
|
export class CollectionSchemaError extends Error {
|
|
15
15
|
alias;
|
|
16
16
|
issues;
|
|
@@ -460,6 +460,12 @@ export function compileCollection(definition) {
|
|
|
460
460
|
if (!ALIAS_PATTERN.test(definition.alias)) {
|
|
461
461
|
throw new CollectionSchemaError(definition.alias, [{ path: 'alias', message: `Alias must match ${ALIAS_PATTERN}.` }]);
|
|
462
462
|
}
|
|
463
|
+
try {
|
|
464
|
+
assertCollectionName(definition.name);
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
throw new CollectionSchemaError(definition.alias, [{ path: 'name', message: error instanceof Error ? error.message : String(error) }]);
|
|
468
|
+
}
|
|
463
469
|
const recordSchema = toRecordSchema(definition.alias, definition.schema);
|
|
464
470
|
const issues = [];
|
|
465
471
|
const indexes = normalizeIndexes(definition.alias, definition.indexes, recordSchema, issues);
|
|
@@ -467,6 +473,7 @@ export function compileCollection(definition) {
|
|
|
467
473
|
throw new CollectionSchemaError(definition.alias, issues);
|
|
468
474
|
const result = {
|
|
469
475
|
alias: definition.alias,
|
|
476
|
+
name: definition.name,
|
|
470
477
|
recordSchema,
|
|
471
478
|
indexes,
|
|
472
479
|
...(definition.description ? { description: definition.description } : {}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/data/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,aAAa,EAA6C,MAAM,aAAa,CAAC;AAyCvF,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IACrC,KAAK,CAAS;IACd,MAAM,CAAgB;IAE/B,YAAY,KAAa,EAAE,MAAqB;QAC9C,KAAK,CACH;YACE,eAAe,KAAK,4BAA4B;YAChD,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,CAAC,IAAI,IAAI,QAAQ,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC;SAC5E,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED,sGAAsG;AACtG,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,KAAK,EAAE,CAAC;IACR,UAAU,EAAE,GAAG;IACf,UAAU,EAAE,GAAG;IACf,KAAK,EAAE,GAAG;IACV,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,EAAE;IACX,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IACb,qBAAqB,EAAE,EAAE;IACzB,qBAAqB,EAAE,UAAU;CACzB,CAAC;AAEX,MAAM,kBAAkB,GAAG,MAAM,CAAC,gBAAgB,CAAC;AACnD,mCAAmC;AACnC,MAAM,sBAAsB,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAW,CAAC;AAC/E,MAAM,YAAY,G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H,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Zod 4 → UNS record schema normalizer, plus write-time validation.\n *\n * UNS stores one closed JSON-schema subset per collection: `type`,\n * `properties`, `required`, `additionalProperties: false`, `items`, `enum`,\n * `minimum`, `maximum`, declared `format`, `title`, `description`. `toRecordSchema` converts the\n * `z.toJSONSchema` output into exactly that subset and rejects every other\n * keyword with a concrete replacement, so a declaration that cannot be stored\n * fails when it is compiled (an App can compile its declarations at build\n * time) instead of on the first request.\n */\nimport { z } from 'zod';\nimport { ALIAS_PATTERN, type CollectionDefinition, type IndexSpec } from './define.js';\n\nexport type RecordSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean';\nexport type EnumValue = string | number | boolean;\n\nexport interface RecordSchema {\n type: RecordSchemaType;\n /** Display annotation; does not add range/date checks or convert stored values. */\n format?: 'int32' | 'float' | 'double' | 'date-time';\n title?: string;\n description?: string;\n properties?: Record<string, RecordSchema>;\n required?: string[];\n additionalProperties?: false;\n items?: RecordSchema;\n enum?: EnumValue[];\n minimum?: number;\n maximum?: number;\n}\n\nexport interface NormalizedIndex {\n path?: string;\n paths?: string[];\n unique?: true;\n kind?: 'gin';\n expireAfterSeconds?: number;\n}\n\n/** One ensure item, exactly as it is sent to `/uns/app/collections/ensure`. */\nexport interface CompiledCollection {\n alias: string;\n recordSchema: RecordSchema;\n indexes: NormalizedIndex[];\n description?: string;\n}\n\nexport interface SchemaIssue {\n path: string;\n message: string;\n}\n\nexport class CollectionSchemaError extends Error {\n readonly alias: string;\n readonly issues: SchemaIssue[];\n\n constructor(alias: string, issues: SchemaIssue[]) {\n super(\n [\n `Collection \"${alias}\" cannot be stored in UNS:`,\n ...issues.map((issue) => ` - ${issue.path || '(root)'}: ${issue.message}`),\n ].join('\\n'),\n );\n this.name = 'CollectionSchemaError';\n this.alias = alias;\n this.issues = issues;\n }\n}\n\n/** UNS limits (unsmeta Schema.validate and collection indexes); title/description are UTF-8 bytes. */\nexport const SCHEMA_LIMITS = {\n depth: 8,\n properties: 128,\n enumValues: 100,\n title: 512,\n description: 2048,\n indexes: 16,\n indexPaths: 3,\n ttlIndexes: 1,\n minExpireAfterSeconds: 60,\n maxExpireAfterSeconds: 31_536_000,\n} as const;\n\nconst SAFE_INTEGER_BOUND = Number.MAX_SAFE_INTEGER;\n// 新声明必须携带明确数值格式;只补注解,不改变范围校验或已有集合。\nconst DEFAULT_NUMERIC_FORMAT = { integer: 'int32', number: 'double' } as const;\nconst SCHEMA_TYPES = new Set<string>(['object', 'array', 'string', 'number', 'integer', 'boolean']);\nconst KEPT_KEYWORDS = new Set([\n 'type',\n 'format',\n 'title',\n 'description',\n 'properties',\n 'required',\n 'additionalProperties',\n 'items',\n 'enum',\n 'minimum',\n 'maximum',\n]);\nconst RESERVED_FIELDS = new Set(['_id', '_meta']);\n\nconst NULLABLE_HINT =\n '`.nullable()`, `.nullish()` and `z.union()` are not storable. Make the field `.optional()` and leave it out instead of storing null; model alternatives as one type or as separate optional fields.';\nconst API_INPUT_HINT = 'Keep the collection schema plain and enforce this rule in the API input schema.';\nconst OPEN_OBJECT_HINT =\n '`z.record()`, `z.looseObject()` and `.catchall()` are not storable: every stored object is closed. Declare fixed properties, or store an array of `{ key, value }` objects.';\n\nconst KEYWORD_HINTS: Record<string, string> = {\n anyOf: NULLABLE_HINT,\n oneOf: NULLABLE_HINT,\n allOf: '`z.intersection()` / `.and()` is not storable. Merge the objects with `.extend()`.',\n not: 'Negated schemas are not storable.',\n default: '`.default()` / `.prefault()` / `.catch()` is not storable. Apply defaults in the service when building the document.',\n format: `Strings only support the declaration \\`z.string().meta({ format: 'date-time' })\\`, which does not validate or convert dates. Other string formats (\\`z.email()\\`, \\`z.uuid()\\`...) are not storable. ${API_INPUT_HINT}`,\n pattern: `\\`.regex()\\`, \\`.startsWith()\\` and similar patterns are not storable. Use \\`z.string()\\`. ${API_INPUT_HINT}`,\n minLength: `String length limits are not storable. Use \\`z.string()\\`. ${API_INPUT_HINT}`,\n maxLength: `String length limits are not storable. Use \\`z.string()\\`. ${API_INPUT_HINT}`,\n contentEncoding: 'Encoded string content is not storable. Use `z.string()`.',\n const: '`z.literal()` is not storable. Use `z.enum([...])`.',\n exclusiveMinimum: '`.gt()` / `.positive()` (exclusive bounds) are not storable. Use inclusive `.min()` (`.min(1)` for a positive integer).',\n exclusiveMaximum: '`.lt()` / `.negative()` are not storable. Use inclusive `.max()`.',\n multipleOf: `\\`.multipleOf()\\` / \\`.step()\\` is not storable. ${API_INPUT_HINT}`,\n minItems: `Array length limits are not storable. ${API_INPUT_HINT}`,\n maxItems: `Array length limits are not storable. ${API_INPUT_HINT}`,\n uniqueItems: `Array uniqueness is not storable. ${API_INPUT_HINT}`,\n prefixItems: '`z.tuple()` is not storable. Use an object with named fields.',\n propertyNames: OPEN_OBJECT_HINT,\n patternProperties: OPEN_OBJECT_HINT,\n minProperties: OPEN_OBJECT_HINT,\n maxProperties: OPEN_OBJECT_HINT,\n $ref: 'Recursive or shared `$ref` schemas are not storable. Inline the structure or keep child records in their own collection.',\n $defs: 'Recursive or shared `$ref` schemas are not storable. Inline the structure or keep child records in their own collection.',\n readOnly: '`.readonly()` is not storable; remove it from the collection schema.',\n};\n\ntype JsonNode = Record<string, unknown>;\n\nconst encoder = new TextEncoder();\n\nfunction utf8Bytes(value: string): number {\n return encoder.encode(value).length;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction joinPath(base: string, key: string | number): string {\n if (typeof key === 'number') return `${base}[${key}]`;\n return base ? `${base}.${key}` : key;\n}\n\nfunction validFieldName(key: string): string | null {\n if (RESERVED_FIELDS.has(key)) return `\"${key}\" is a system field and cannot be declared.`;\n if (key.length === 0 || key === '[]') return `Field name \"${key}\" is reserved.`;\n if (/[.$\\\\]/.test(key)) return `Field name \"${key}\" must not contain \".\", \"$\" or \"\\\\\".`;\n return null;\n}\n\nfunction inferEnumType(values: unknown[]): RecordSchemaType | null {\n if (values.length === 0) return null;\n if (values.every((value) => typeof value === 'string')) return 'string';\n if (values.every((value) => typeof value === 'boolean')) return 'boolean';\n if (values.every((value) => typeof value === 'number')) {\n return values.every((value) => Number.isInteger(value)) ? 'integer' : 'number';\n }\n return null;\n}\n\nfunction normalizeNode(node: unknown, path: string, depth: number, issues: SchemaIssue[]): RecordSchema | null {\n if (!isPlainObject(node)) {\n issues.push({ path, message: 'Expected a schema object.' });\n return null;\n }\n if (depth > SCHEMA_LIMITS.depth) {\n issues.push({ path, message: `Nesting deeper than ${SCHEMA_LIMITS.depth} levels is not storable. Flatten the structure.` });\n return null;\n }\n\n let valid = true;\n for (const key of Object.keys(node)) {\n if (KEPT_KEYWORDS.has(key) || (depth === 0 && key === '$schema')) continue;\n valid = false;\n issues.push({\n path,\n message: `\\`${key}\\` is not supported. ${KEYWORD_HINTS[key] ?? 'Only type, properties, items, enum, minimum, maximum, declared format, title and description are storable; remove this constraint from the collection schema.'}`,\n });\n }\n\n const rawEnum = Array.isArray(node.enum) ? node.enum : undefined;\n let type = node.type;\n if (type === undefined && rawEnum) type = inferEnumType(rawEnum) ?? undefined;\n if (Array.isArray(type)) {\n issues.push({ path, message: `A field must have one type, got [${type.join(', ')}]. ${NULLABLE_HINT}` });\n return null;\n }\n if (type === 'null') {\n issues.push({ path, message: '`z.null()` is not storable. Make the field optional and leave it out.' });\n return null;\n }\n if (typeof type !== 'string' || !SCHEMA_TYPES.has(type)) {\n if (type === undefined && !('anyOf' in node) && !('oneOf' in node) && !('allOf' in node)) {\n issues.push({\n path,\n message: 'Every field needs a concrete type; `z.any()`, `z.unknown()` and `z.json()` are not storable. Declare the actual shape.',\n });\n }\n return null;\n }\n\n const out: RecordSchema = { type: type as RecordSchemaType };\n const format = node.format === undefined && (type === 'integer' || type === 'number')\n ? DEFAULT_NUMERIC_FORMAT[type]\n : node.format;\n if (format !== undefined) {\n if ((type === 'integer' && format === 'int32') || (type === 'number' && (format === 'float' || format === 'double')) || (type === 'string' && format === 'date-time')) {\n out.format = format;\n } else {\n issues.push({\n path,\n message: type === 'string'\n ? KEYWORD_HINTS.format\n : '`format` must be \"int32\" on integer fields, \"float\" / \"double\" on number fields, or \"date-time\" on string fields. Other types and formats are not storable.',\n });\n valid = false;\n }\n }\n for (const key of ['title', 'description'] as const) {\n const value = node[key];\n if (value === undefined) continue;\n const limit = key === 'title' ? SCHEMA_LIMITS.title : SCHEMA_LIMITS.description;\n // UNS measures these with Go len(): UTF-8 bytes, so CJK text uses 3 per character.\n if (typeof value !== 'string' || utf8Bytes(value) > limit) {\n issues.push({ path, message: `\\`${key}\\` must be a string of at most ${limit} UTF-8 bytes.` });\n valid = false;\n } else if (value) {\n out[key] = value;\n }\n }\n\n if (type === 'object') {\n if (node.additionalProperties !== undefined && node.additionalProperties !== false) {\n issues.push({ path, message: OPEN_OBJECT_HINT });\n valid = false;\n }\n const rawProperties = isPlainObject(node.properties) ? node.properties : {};\n const names = Object.keys(rawProperties);\n if (names.length > SCHEMA_LIMITS.properties) {\n issues.push({ path, message: `More than ${SCHEMA_LIMITS.properties} properties is not storable. Split the object.` });\n valid = false;\n }\n const properties: Record<string, RecordSchema> = {};\n for (const name of names) {\n const fieldPath = joinPath(path, name);\n const nameProblem = validFieldName(name);\n if (nameProblem) {\n issues.push({ path: fieldPath, message: nameProblem });\n valid = false;\n continue;\n }\n const child = normalizeNode(rawProperties[name], fieldPath, depth + 1, issues);\n if (child) properties[name] = child;\n else valid = false;\n }\n out.properties = properties;\n const required = Array.isArray(node.required)\n ? [...new Set(node.required.filter((name): name is string => typeof name === 'string' && name in rawProperties))].sort()\n : [];\n if (required.length > 0) out.required = required;\n out.additionalProperties = false;\n } else if (node.properties !== undefined || node.required !== undefined || node.additionalProperties !== undefined) {\n issues.push({ path, message: 'Only objects may declare properties.' });\n valid = false;\n }\n\n if (type === 'array') {\n const items = node.items;\n if (!isPlainObject(items)) {\n issues.push({ path, message: 'Arrays need one item schema (`z.array(item)`).' });\n valid = false;\n } else {\n const child = normalizeNode(items, `${path}[]`, depth + 1, issues);\n if (child) out.items = child;\n else valid = false;\n }\n }\n\n if (rawEnum) {\n const values: EnumValue[] = [];\n for (const value of rawEnum) {\n const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n const fits =\n scalar &&\n (type === 'string'\n ? typeof value === 'string'\n : type === 'boolean'\n ? typeof value === 'boolean'\n : type === 'integer'\n ? Number.isInteger(value)\n : type === 'number'\n ? typeof value === 'number'\n : false);\n if (!fits) {\n issues.push({ path, message: `Enum value ${JSON.stringify(value)} does not match type ${type}.` });\n valid = false;\n } else if (!values.some((existing) => existing === value)) {\n values.push(value as EnumValue);\n }\n }\n if (values.length > SCHEMA_LIMITS.enumValues) {\n issues.push({ path, message: `More than ${SCHEMA_LIMITS.enumValues} enum values is not storable. Use a reference collection.` });\n valid = false;\n }\n if (values.length > 0) out.enum = values;\n }\n\n for (const key of ['minimum', 'maximum'] as const) {\n const value = node[key];\n if (value === undefined) continue;\n if (type !== 'number' && type !== 'integer') {\n issues.push({ path, message: `\\`${key}\\` is only valid on numbers.` });\n valid = false;\n continue;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n issues.push({ path, message: `\\`${key}\\` must be a finite number.` });\n valid = false;\n continue;\n }\n // z.number().int() always emits the safe-integer range; it is not a business bound.\n if (type === 'integer' && Math.abs(value) === SAFE_INTEGER_BOUND) continue;\n out[key] = value;\n }\n if (out.minimum !== undefined && out.maximum !== undefined && out.minimum > out.maximum) {\n issues.push({ path, message: '`minimum` is greater than `maximum`.' });\n valid = false;\n }\n\n return valid ? out : null;\n}\n\n/** Raw `z.toJSONSchema` output; exported for the snapshot tests. */\nexport function zodJsonSchema(schema: z.ZodType): JsonNode {\n return z.toJSONSchema(schema, { io: 'output', unrepresentable: 'throw', cycles: 'throw' }) as JsonNode;\n}\n\n/** Converts a Zod object schema to the UNS record-schema subset or throws `CollectionSchemaError`. */\nexport function toRecordSchema(alias: string, schema: z.ZodType): RecordSchema {\n let raw: JsonNode;\n try {\n raw = zodJsonSchema(schema);\n } catch (error) {\n throw new CollectionSchemaError(alias, [\n {\n path: '',\n message: `${error instanceof Error ? error.message : String(error)}. \\`z.date()\\`, \\`z.bigint()\\`, \\`.transform()\\`, \\`z.map()\\`, \\`z.set()\\`, \\`z.custom()\\` and recursive schemas are not storable; store instants as ISO-8601 UTC strings from \\`toISOString()\\` and dates as \"YYYY-MM-DD\" strings, and keep transforms in the API input schema.`,\n },\n ]);\n }\n const issues: SchemaIssue[] = [];\n const normalized = normalizeNode(raw, '', 0, issues);\n if (normalized && normalized.type !== 'object') {\n issues.push({ path: '', message: 'A collection schema must be `z.object({...})`.' });\n }\n if (issues.length > 0 || !normalized) throw new CollectionSchemaError(alias, issues);\n return normalized;\n}\n\n/** Resolves a dotted business path in a record schema; array levels accept index segments. */\nexport function recordSchemaAt(schema: RecordSchema, path: string): RecordSchema | undefined {\n let current: RecordSchema | undefined = schema;\n for (const segment of path.split('.')) {\n if (!current) return undefined;\n if (current.type === 'array' && isArraySegment(segment)) {\n current = current.items;\n } else if (current.type === 'object') {\n current = current.properties?.[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\nfunction isArraySegment(segment: string): boolean {\n return /^(?:\\d+|\\$|\\$\\[[A-Za-z0-9_]*\\])$/.test(segment);\n}\n\n/**\n * Index paths follow object properties only: a path that continues past an\n * array (`items.sku`) would index values inside array items, which UNS\n * expression indexes cannot do.\n */\nfunction indexPathProblem(alias: string, schema: RecordSchema, path: string, kind: 'btree' | 'gin'): string | null {\n const segments = path.split('.');\n let current: RecordSchema | undefined = schema;\n for (const [position, segment] of segments.entries()) {\n if (current?.type === 'array') {\n const arrayPath = segments.slice(0, position).join('.');\n return `\"${path}\" reaches into the items of array \"${arrayPath}\"; index the array itself with kind: \"gin\", or copy the value to a top-level field.`;\n }\n current = current?.type === 'object' ? current.properties?.[segment] : undefined;\n if (!current) return `\"${path}\" is not a declared field of \"${alias}\".`;\n }\n const target = current as RecordSchema;\n if (kind === 'btree' && (target.type === 'object' || target.type === 'array')) {\n return `\"${path}\" is an ${target.type}; index a scalar field or use kind: \"gin\".`;\n }\n if (kind === 'gin' && target.type !== 'object' && target.type !== 'array') {\n return `\"${path}\" is a ${target.type}; a GIN index covers an object or array field.`;\n }\n return null;\n}\n\n/** A TTL index expires records by one integer field of Unix milliseconds. */\nfunction ttlProblem(alias: string, schema: RecordSchema, index: IndexSpec, kind: 'btree' | 'gin'): string | null {\n const seconds = index.expireAfterSeconds as number;\n if (!Number.isInteger(seconds) || seconds < SCHEMA_LIMITS.minExpireAfterSeconds || seconds > SCHEMA_LIMITS.maxExpireAfterSeconds) {\n return `\\`expireAfterSeconds\\` is an integer from ${SCHEMA_LIMITS.minExpireAfterSeconds} to ${SCHEMA_LIMITS.maxExpireAfterSeconds} (one year).`;\n }\n if (index.path === undefined || kind !== 'btree' || index.unique) return 'A TTL index covers a single `path` and is neither unique nor GIN.';\n const target = recordSchemaAt(schema, index.path);\n if (target?.type !== 'integer') {\n return `TTL field \"${index.path}\" of \"${alias}\" must be declared \\`z.number().int()\\` holding Unix milliseconds (e.g. \\`Date.now()\\`).`;\n }\n return null;\n}\n\nfunction normalizeIndexes(alias: string, indexes: readonly IndexSpec[], schema: RecordSchema, issues: SchemaIssue[]): NormalizedIndex[] {\n const out: NormalizedIndex[] = [];\n const seen = new Set<string>();\n let ttl = 0;\n if (indexes.length > SCHEMA_LIMITS.indexes) {\n issues.push({ path: 'indexes', message: `At most ${SCHEMA_LIMITS.indexes} indexes per collection.` });\n }\n indexes.forEach((index, position) => {\n const at = `indexes[${position}]`;\n const paths = index.paths ?? (index.path !== undefined ? [index.path] : []);\n if ((index.path !== undefined) === (index.paths !== undefined)) {\n issues.push({ path: at, message: 'Set exactly one of `path` or `paths`.' });\n return;\n }\n if (paths.length === 0 || paths.length > SCHEMA_LIMITS.indexPaths) {\n issues.push({ path: at, message: `A compound index has 1–${SCHEMA_LIMITS.indexPaths} paths.` });\n return;\n }\n const kind = index.kind ?? 'btree';\n if (kind !== 'btree' && kind !== 'gin') {\n issues.push({ path: at, message: '`kind` is \"btree\" or \"gin\".' });\n return;\n }\n if (kind === 'gin' && (paths.length !== 1 || index.unique)) {\n issues.push({ path: at, message: 'A GIN index covers one object/array path and cannot be unique.' });\n return;\n }\n if (new Set(paths).size !== paths.length) {\n issues.push({ path: at, message: 'A compound index lists each path once.' });\n return;\n }\n for (const fieldPath of paths) {\n const problem = indexPathProblem(alias, schema, fieldPath, kind);\n if (problem) {\n issues.push({ path: at, message: problem });\n return;\n }\n }\n if (index.expireAfterSeconds !== undefined) {\n const problem = ttlProblem(alias, schema, index, kind);\n if (problem) {\n issues.push({ path: at, message: problem });\n return;\n }\n ttl += 1;\n if (ttl > SCHEMA_LIMITS.ttlIndexes) {\n issues.push({ path: at, message: 'A collection has at most one TTL index (`expireAfterSeconds`).' });\n return;\n }\n }\n const normalized: NormalizedIndex = index.paths ? { paths: [...paths] } : { path: paths[0] };\n if (index.unique) normalized.unique = true;\n if (kind === 'gin') normalized.kind = 'gin';\n if (index.expireAfterSeconds !== undefined) normalized.expireAfterSeconds = index.expireAfterSeconds;\n const key = JSON.stringify(normalized);\n if (!seen.has(key)) {\n seen.add(key);\n out.push(normalized);\n }\n });\n // A TTL index is an ordinary B-tree on its path as well: a plain index on the same path would duplicate it.\n const ttlPaths = new Set(out.filter((index) => index.expireAfterSeconds !== undefined).map((index) => index.path));\n return out.filter((index) => index.expireAfterSeconds !== undefined || index.unique || index.kind || !ttlPaths.has(index.path));\n}\n\nconst compiled = new WeakMap<CollectionDefinition, CompiledCollection>();\n\n/** Ensure payload for one declaration; memoized per definition object. */\nexport function compileCollection(definition: CollectionDefinition): CompiledCollection {\n const cached = compiled.get(definition);\n if (cached) return cached;\n if (!ALIAS_PATTERN.test(definition.alias)) {\n throw new CollectionSchemaError(definition.alias, [{ path: 'alias', message: `Alias must match ${ALIAS_PATTERN}.` }]);\n }\n const recordSchema = toRecordSchema(definition.alias, definition.schema);\n const issues: SchemaIssue[] = [];\n const indexes = normalizeIndexes(definition.alias, definition.indexes, recordSchema, issues);\n if (issues.length > 0) throw new CollectionSchemaError(definition.alias, issues);\n const result: CompiledCollection = {\n alias: definition.alias,\n recordSchema,\n indexes,\n ...(definition.description ? { description: definition.description } : {}),\n };\n compiled.set(definition, result);\n return result;\n}\n\n/* ------------------------------------------------------------------ */\n/* Write validation */\n/* ------------------------------------------------------------------ */\n\ntype IssuePath = (string | number)[];\n\nfunction unknownKeyIssues(schema: RecordSchema | undefined, value: unknown, path: IssuePath, out: z.core.$ZodIssue[]) {\n if (!schema) return;\n if (schema.type === 'object' && isPlainObject(value)) {\n const properties = schema.properties ?? {};\n const unknown = Object.keys(value).filter((key) => !(key in properties));\n if (unknown.length > 0) {\n out.push({\n code: 'unrecognized_keys',\n keys: unknown,\n path,\n message: `Unknown field${unknown.length > 1 ? 's' : ''} ${unknown.map((key) => `\"${key}\"`).join(', ')}: declare ${unknown.length > 1 ? 'them' : 'it'} in the collection schema first.`,\n input: value,\n } as z.core.$ZodIssue);\n }\n for (const [key, child] of Object.entries(value)) {\n if (key in properties) unknownKeyIssues(properties[key], child, [...path, key], out);\n }\n } else if (schema.type === 'array' && Array.isArray(value)) {\n value.forEach((item, index) => unknownKeyIssues(schema.items, item, [...path, index], out));\n }\n}\n\nfunction strictParse<T>(zodSchema: z.ZodType<T>, recordSchema: RecordSchema | undefined, value: unknown, path: IssuePath): T {\n const issues: z.core.$ZodIssue[] = [];\n unknownKeyIssues(recordSchema, value, path, issues);\n const result = zodSchema.safeParse(value);\n if (!result.success) {\n for (const issue of result.error.issues) issues.push({ ...issue, path: [...path, ...issue.path] } as z.core.$ZodIssue);\n }\n if (issues.length > 0) throw new z.ZodError(issues);\n return result.data as T;\n}\n\nfunction zodAt(schema: z.ZodType, path: string): z.ZodType | undefined {\n let current: z.ZodType | undefined = schema;\n for (const segment of path.split('.')) {\n while (current instanceof z.ZodOptional) current = current.unwrap() as z.ZodType;\n if (current instanceof z.ZodObject) {\n current = (current.shape as Record<string, z.ZodType>)[segment];\n } else if (current instanceof z.ZodArray && isArraySegment(segment)) {\n current = current.element as z.ZodType;\n } else {\n return undefined;\n }\n if (!current) return undefined;\n }\n return current;\n}\n\nfunction validationError(path: IssuePath, message: string, input: unknown): z.ZodError {\n return new z.ZodError([{ code: 'custom', path, message, input } as z.core.$ZodIssue]);\n}\n\n/** Splits `_id` / `_meta` off a document and strictly validates the body. */\nexport function validateDocument(\n definition: CollectionDefinition,\n document: Record<string, unknown>,\n): { id?: string; data: Record<string, unknown> } {\n if (!isPlainObject(document)) throw validationError([], 'Expected a document object.', document);\n const { _id, _meta, ...body } = document;\n void _meta;\n if (_id !== undefined && (typeof _id !== 'string' || _id.length === 0 || _id.length > 128)) {\n throw validationError(['_id'], '`_id` must be a string of 1–128 characters.', _id);\n }\n const { recordSchema } = compileCollection(definition);\n const data = strictParse(definition.schema, recordSchema, body, []) as Record<string, unknown>;\n return { ...(typeof _id === 'string' ? { id: _id } : {}), data };\n}\n\n/**\n * Validates `data` of a transaction step. Fields filled by `bindings`\n * (`data.<field>...`) are checked only for being declared; every literal\n * field is strictly validated, and other required fields must be present.\n */\nexport function validateStepData(\n definition: CollectionDefinition,\n data: Record<string, unknown>,\n boundFields: readonly string[],\n): Record<string, unknown> {\n if (!isPlainObject(data)) throw validationError(['data'], 'Expected a document object.', data);\n if ('_id' in data || '_meta' in data) {\n 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);\n }\n const { recordSchema } = compileCollection(definition);\n const properties = recordSchema.properties ?? {};\n const bound = new Set(boundFields.filter((field) => field in properties));\n const unknownBound = boundFields.filter((field) => !(field in properties));\n if (unknownBound.length > 0) {\n throw validationError(['bindings'], `Bound field${unknownBound.length > 1 ? 's' : ''} ${unknownBound.join(', ')} not declared in \"${definition.alias}\".`, boundFields);\n }\n if (bound.size === 0) return strictParse(definition.schema, recordSchema, data, ['data']) as Record<string, unknown>;\n\n const literal = Object.fromEntries(Object.entries(data).filter(([key]) => !bound.has(key)));\n const omit = Object.fromEntries([...bound].map((field) => [field, true as const]));\n const literalSchema: RecordSchema = {\n ...recordSchema,\n properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !bound.has(key))),\n required: recordSchema.required?.filter((key) => !bound.has(key)),\n };\n const parsed = strictParse(definition.schema.omit(omit as never), literalSchema, literal, ['data']) as Record<string, unknown>;\n const boundValues = Object.fromEntries(Object.entries(data).filter(([key]) => bound.has(key)));\n return { ...parsed, ...boundValues };\n}\n\nconst VALUE_OPERATORS = new Set(['$set', '$setOnInsert']);\nconst ELEMENT_OPERATORS = new Set(['$push', '$addToSet']);\nconst NUMERIC_OPERATORS = new Set(['$inc', '$mul']);\n\n/** Validates update-operator documents against the declaration (paths and values). */\nexport function validateUpdate(definition: CollectionDefinition, update: Record<string, unknown>): Record<string, unknown> {\n if (!isPlainObject(update) || Object.keys(update).length === 0) {\n throw validationError([], 'An update needs at least one operator such as `$set`.', update);\n }\n const { recordSchema } = compileCollection(definition);\n const out: Record<string, unknown> = {};\n\n for (const [operator, fields] of Object.entries(update)) {\n if (!operator.startsWith('$')) {\n throw validationError([operator], \"Updates use operators (`{ $set: { status: \\\"DONE\\\" } }`); use replaceOne() to replace a whole document.\", update);\n }\n if (!isPlainObject(fields)) throw validationError([operator], `\\`${operator}\\` takes an object of field paths.`, fields);\n const next: Record<string, unknown> = {};\n\n for (const [path, value] of Object.entries(fields)) {\n const issuePath = [operator, path];\n if (path === '_id' || path === '_meta' || path.startsWith('_meta.')) {\n throw validationError(issuePath, '`_id` and `_meta` are read-only.', value);\n }\n const target = recordSchemaAt(recordSchema, path);\n const zodTarget = zodAt(definition.schema, path);\n if (!target || !zodTarget) {\n throw validationError(issuePath, `\"${path}\" is not a declared field of \"${definition.alias}\".`, value);\n }\n\n if (VALUE_OPERATORS.has(operator)) {\n if (value === undefined) continue;\n next[path] = strictParse(zodTarget, target, value, issuePath);\n } else if (ELEMENT_OPERATORS.has(operator)) {\n const element = zodTarget instanceof z.ZodOptional ? zodTarget.unwrap() : zodTarget;\n if (target.type !== 'array' || !(element instanceof z.ZodArray)) {\n throw validationError(issuePath, `\\`${operator}\\` needs an array field; \"${path}\" is ${target.type}.`, value);\n }\n const each = isPlainObject(value) && Array.isArray(value.$each);\n const items = each ? ((value as { $each: unknown[] }).$each) : [value];\n const parsed = items.map((item, index) =>\n strictParse(element.element as z.ZodType, target.items, item, each ? [...issuePath, '$each', index] : issuePath),\n );\n next[path] = each ? { ...(value as Record<string, unknown>), $each: parsed } : parsed[0];\n } else if (NUMERIC_OPERATORS.has(operator)) {\n if (target.type !== 'number' && target.type !== 'integer') {\n throw validationError(issuePath, `\\`${operator}\\` needs a numeric field; \"${path}\" is ${target.type}.`, value);\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw validationError(issuePath, `\\`${operator}\\` needs a finite number.`, value);\n }\n next[path] = value;\n } else if (operator === '$rename') {\n if (typeof value !== 'string' || !recordSchemaAt(recordSchema, value)) {\n throw validationError(issuePath, `\\`$rename\\` target \"${String(value)}\" is not a declared field.`, value);\n }\n next[path] = value;\n } else {\n // $unset, $min, $max, $currentDate, $pop, $pull, $pullAll: the path is\n // declared; UNS validates the resulting document.\n next[path] = value;\n }\n }\n if (Object.keys(next).length > 0) out[operator] = next;\n }\n if (Object.keys(out).length === 0) {\n throw validationError([], 'Nothing to update: undefined values are dropped; clear a field with `$unset`.', update);\n }\n return out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/data/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAA6C,MAAM,aAAa,CAAC;AA0C7G,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IACrC,KAAK,CAAS;IACd,MAAM,CAAgB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A+E,EAAE,MAAM,CAAC,CAAC;IACrH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Zod 4 → UNS record schema normalizer, plus write-time validation.\n *\n * UNS stores one closed JSON-schema subset per collection: `type`,\n * `properties`, `required`, `additionalProperties: false`, `items`, `enum`,\n * `minimum`, `maximum`, declared `format`, `title`, `description`. `toRecordSchema` converts the\n * `z.toJSONSchema` output into exactly that subset and rejects every other\n * keyword with a concrete replacement, so a declaration that cannot be stored\n * fails when it is compiled (an App can compile its declarations at build\n * time) instead of on the first request.\n */\nimport { z } from 'zod';\nimport { ALIAS_PATTERN, assertCollectionName, type CollectionDefinition, type IndexSpec } from './define.js';\n\nexport type RecordSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean';\nexport type EnumValue = string | number | boolean;\n\nexport interface RecordSchema {\n type: RecordSchemaType;\n /** Display annotation; does not add range/date checks or convert stored values. */\n format?: 'int32' | 'float' | 'double' | 'date-time';\n title?: string;\n description?: string;\n properties?: Record<string, RecordSchema>;\n required?: string[];\n additionalProperties?: false;\n items?: RecordSchema;\n enum?: EnumValue[];\n minimum?: number;\n maximum?: number;\n}\n\nexport interface NormalizedIndex {\n path?: string;\n paths?: string[];\n unique?: true;\n kind?: 'gin';\n expireAfterSeconds?: number;\n}\n\n/** One ensure item, exactly as it is sent to `/uns/app/collections/ensure`. */\nexport interface CompiledCollection {\n alias: string;\n name: string;\n recordSchema: RecordSchema;\n indexes: NormalizedIndex[];\n description?: string;\n}\n\nexport interface SchemaIssue {\n path: string;\n message: string;\n}\n\nexport class CollectionSchemaError extends Error {\n readonly alias: string;\n readonly issues: SchemaIssue[];\n\n constructor(alias: string, issues: SchemaIssue[]) {\n super(\n [\n `Collection \"${alias}\" cannot be stored in UNS:`,\n ...issues.map((issue) => ` - ${issue.path || '(root)'}: ${issue.message}`),\n ].join('\\n'),\n );\n this.name = 'CollectionSchemaError';\n this.alias = alias;\n this.issues = issues;\n }\n}\n\n/** UNS limits (unsmeta Schema.validate and collection indexes); title/description are UTF-8 bytes. */\nexport const SCHEMA_LIMITS = {\n depth: 8,\n properties: 128,\n enumValues: 100,\n title: 512,\n description: 2048,\n indexes: 16,\n indexPaths: 3,\n ttlIndexes: 1,\n minExpireAfterSeconds: 60,\n maxExpireAfterSeconds: 31_536_000,\n} as const;\n\nconst SAFE_INTEGER_BOUND = Number.MAX_SAFE_INTEGER;\n// 新声明必须携带明确数值格式;只补注解,不改变范围校验或已有集合。\nconst DEFAULT_NUMERIC_FORMAT = { integer: 'int32', number: 'double' } as const;\nconst SCHEMA_TYPES = new Set<string>(['object', 'array', 'string', 'number', 'integer', 'boolean']);\nconst KEPT_KEYWORDS = new Set([\n 'type',\n 'format',\n 'title',\n 'description',\n 'properties',\n 'required',\n 'additionalProperties',\n 'items',\n 'enum',\n 'minimum',\n 'maximum',\n]);\nconst RESERVED_FIELDS = new Set(['_id', '_meta']);\n\nconst NULLABLE_HINT =\n '`.nullable()`, `.nullish()` and `z.union()` are not storable. Make the field `.optional()` and leave it out instead of storing null; model alternatives as one type or as separate optional fields.';\nconst API_INPUT_HINT = 'Keep the collection schema plain and enforce this rule in the API input schema.';\nconst OPEN_OBJECT_HINT =\n '`z.record()`, `z.looseObject()` and `.catchall()` are not storable: every stored object is closed. Declare fixed properties, or store an array of `{ key, value }` objects.';\n\nconst KEYWORD_HINTS: Record<string, string> = {\n anyOf: NULLABLE_HINT,\n oneOf: NULLABLE_HINT,\n allOf: '`z.intersection()` / `.and()` is not storable. Merge the objects with `.extend()`.',\n not: 'Negated schemas are not storable.',\n default: '`.default()` / `.prefault()` / `.catch()` is not storable. Apply defaults in the service when building the document.',\n format: `Strings only support the declaration \\`z.string().meta({ format: 'date-time' })\\`, which does not validate or convert dates. Other string formats (\\`z.email()\\`, \\`z.uuid()\\`...) are not storable. ${API_INPUT_HINT}`,\n pattern: `\\`.regex()\\`, \\`.startsWith()\\` and similar patterns are not storable. Use \\`z.string()\\`. ${API_INPUT_HINT}`,\n minLength: `String length limits are not storable. Use \\`z.string()\\`. ${API_INPUT_HINT}`,\n maxLength: `String length limits are not storable. Use \\`z.string()\\`. ${API_INPUT_HINT}`,\n contentEncoding: 'Encoded string content is not storable. Use `z.string()`.',\n const: '`z.literal()` is not storable. Use `z.enum([...])`.',\n exclusiveMinimum: '`.gt()` / `.positive()` (exclusive bounds) are not storable. Use inclusive `.min()` (`.min(1)` for a positive integer).',\n exclusiveMaximum: '`.lt()` / `.negative()` are not storable. Use inclusive `.max()`.',\n multipleOf: `\\`.multipleOf()\\` / \\`.step()\\` is not storable. ${API_INPUT_HINT}`,\n minItems: `Array length limits are not storable. ${API_INPUT_HINT}`,\n maxItems: `Array length limits are not storable. ${API_INPUT_HINT}`,\n uniqueItems: `Array uniqueness is not storable. ${API_INPUT_HINT}`,\n prefixItems: '`z.tuple()` is not storable. Use an object with named fields.',\n propertyNames: OPEN_OBJECT_HINT,\n patternProperties: OPEN_OBJECT_HINT,\n minProperties: OPEN_OBJECT_HINT,\n maxProperties: OPEN_OBJECT_HINT,\n $ref: 'Recursive or shared `$ref` schemas are not storable. Inline the structure or keep child records in their own collection.',\n $defs: 'Recursive or shared `$ref` schemas are not storable. Inline the structure or keep child records in their own collection.',\n readOnly: '`.readonly()` is not storable; remove it from the collection schema.',\n};\n\ntype JsonNode = Record<string, unknown>;\n\nconst encoder = new TextEncoder();\n\nfunction utf8Bytes(value: string): number {\n return encoder.encode(value).length;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction joinPath(base: string, key: string | number): string {\n if (typeof key === 'number') return `${base}[${key}]`;\n return base ? `${base}.${key}` : key;\n}\n\nfunction validFieldName(key: string): string | null {\n if (RESERVED_FIELDS.has(key)) return `\"${key}\" is a system field and cannot be declared.`;\n if (key.length === 0 || key === '[]') return `Field name \"${key}\" is reserved.`;\n if (/[.$\\\\]/.test(key)) return `Field name \"${key}\" must not contain \".\", \"$\" or \"\\\\\".`;\n return null;\n}\n\nfunction inferEnumType(values: unknown[]): RecordSchemaType | null {\n if (values.length === 0) return null;\n if (values.every((value) => typeof value === 'string')) return 'string';\n if (values.every((value) => typeof value === 'boolean')) return 'boolean';\n if (values.every((value) => typeof value === 'number')) {\n return values.every((value) => Number.isInteger(value)) ? 'integer' : 'number';\n }\n return null;\n}\n\nfunction normalizeNode(node: unknown, path: string, depth: number, issues: SchemaIssue[]): RecordSchema | null {\n if (!isPlainObject(node)) {\n issues.push({ path, message: 'Expected a schema object.' });\n return null;\n }\n if (depth > SCHEMA_LIMITS.depth) {\n issues.push({ path, message: `Nesting deeper than ${SCHEMA_LIMITS.depth} levels is not storable. Flatten the structure.` });\n return null;\n }\n\n let valid = true;\n for (const key of Object.keys(node)) {\n if (KEPT_KEYWORDS.has(key) || (depth === 0 && key === '$schema')) continue;\n valid = false;\n issues.push({\n path,\n message: `\\`${key}\\` is not supported. ${KEYWORD_HINTS[key] ?? 'Only type, properties, items, enum, minimum, maximum, declared format, title and description are storable; remove this constraint from the collection schema.'}`,\n });\n }\n\n const rawEnum = Array.isArray(node.enum) ? node.enum : undefined;\n let type = node.type;\n if (type === undefined && rawEnum) type = inferEnumType(rawEnum) ?? undefined;\n if (Array.isArray(type)) {\n issues.push({ path, message: `A field must have one type, got [${type.join(', ')}]. ${NULLABLE_HINT}` });\n return null;\n }\n if (type === 'null') {\n issues.push({ path, message: '`z.null()` is not storable. Make the field optional and leave it out.' });\n return null;\n }\n if (typeof type !== 'string' || !SCHEMA_TYPES.has(type)) {\n if (type === undefined && !('anyOf' in node) && !('oneOf' in node) && !('allOf' in node)) {\n issues.push({\n path,\n message: 'Every field needs a concrete type; `z.any()`, `z.unknown()` and `z.json()` are not storable. Declare the actual shape.',\n });\n }\n return null;\n }\n\n const out: RecordSchema = { type: type as RecordSchemaType };\n const format = node.format === undefined && (type === 'integer' || type === 'number')\n ? DEFAULT_NUMERIC_FORMAT[type]\n : node.format;\n if (format !== undefined) {\n if ((type === 'integer' && format === 'int32') || (type === 'number' && (format === 'float' || format === 'double')) || (type === 'string' && format === 'date-time')) {\n out.format = format;\n } else {\n issues.push({\n path,\n message: type === 'string'\n ? KEYWORD_HINTS.format\n : '`format` must be \"int32\" on integer fields, \"float\" / \"double\" on number fields, or \"date-time\" on string fields. Other types and formats are not storable.',\n });\n valid = false;\n }\n }\n for (const key of ['title', 'description'] as const) {\n const value = node[key];\n if (value === undefined) continue;\n const limit = key === 'title' ? SCHEMA_LIMITS.title : SCHEMA_LIMITS.description;\n // UNS measures these with Go len(): UTF-8 bytes, so CJK text uses 3 per character.\n if (typeof value !== 'string' || utf8Bytes(value) > limit) {\n issues.push({ path, message: `\\`${key}\\` must be a string of at most ${limit} UTF-8 bytes.` });\n valid = false;\n } else if (value) {\n out[key] = value;\n }\n }\n\n if (type === 'object') {\n if (node.additionalProperties !== undefined && node.additionalProperties !== false) {\n issues.push({ path, message: OPEN_OBJECT_HINT });\n valid = false;\n }\n const rawProperties = isPlainObject(node.properties) ? node.properties : {};\n const names = Object.keys(rawProperties);\n if (names.length > SCHEMA_LIMITS.properties) {\n issues.push({ path, message: `More than ${SCHEMA_LIMITS.properties} properties is not storable. Split the object.` });\n valid = false;\n }\n const properties: Record<string, RecordSchema> = {};\n for (const name of names) {\n const fieldPath = joinPath(path, name);\n const nameProblem = validFieldName(name);\n if (nameProblem) {\n issues.push({ path: fieldPath, message: nameProblem });\n valid = false;\n continue;\n }\n const child = normalizeNode(rawProperties[name], fieldPath, depth + 1, issues);\n if (child) properties[name] = child;\n else valid = false;\n }\n out.properties = properties;\n const required = Array.isArray(node.required)\n ? [...new Set(node.required.filter((name): name is string => typeof name === 'string' && name in rawProperties))].sort()\n : [];\n if (required.length > 0) out.required = required;\n out.additionalProperties = false;\n } else if (node.properties !== undefined || node.required !== undefined || node.additionalProperties !== undefined) {\n issues.push({ path, message: 'Only objects may declare properties.' });\n valid = false;\n }\n\n if (type === 'array') {\n const items = node.items;\n if (!isPlainObject(items)) {\n issues.push({ path, message: 'Arrays need one item schema (`z.array(item)`).' });\n valid = false;\n } else {\n const child = normalizeNode(items, `${path}[]`, depth + 1, issues);\n if (child) out.items = child;\n else valid = false;\n }\n }\n\n if (rawEnum) {\n const values: EnumValue[] = [];\n for (const value of rawEnum) {\n const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n const fits =\n scalar &&\n (type === 'string'\n ? typeof value === 'string'\n : type === 'boolean'\n ? typeof value === 'boolean'\n : type === 'integer'\n ? Number.isInteger(value)\n : type === 'number'\n ? typeof value === 'number'\n : false);\n if (!fits) {\n issues.push({ path, message: `Enum value ${JSON.stringify(value)} does not match type ${type}.` });\n valid = false;\n } else if (!values.some((existing) => existing === value)) {\n values.push(value as EnumValue);\n }\n }\n if (values.length > SCHEMA_LIMITS.enumValues) {\n issues.push({ path, message: `More than ${SCHEMA_LIMITS.enumValues} enum values is not storable. Use a reference collection.` });\n valid = false;\n }\n if (values.length > 0) out.enum = values;\n }\n\n for (const key of ['minimum', 'maximum'] as const) {\n const value = node[key];\n if (value === undefined) continue;\n if (type !== 'number' && type !== 'integer') {\n issues.push({ path, message: `\\`${key}\\` is only valid on numbers.` });\n valid = false;\n continue;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n issues.push({ path, message: `\\`${key}\\` must be a finite number.` });\n valid = false;\n continue;\n }\n // z.number().int() always emits the safe-integer range; it is not a business bound.\n if (type === 'integer' && Math.abs(value) === SAFE_INTEGER_BOUND) continue;\n out[key] = value;\n }\n if (out.minimum !== undefined && out.maximum !== undefined && out.minimum > out.maximum) {\n issues.push({ path, message: '`minimum` is greater than `maximum`.' });\n valid = false;\n }\n\n return valid ? out : null;\n}\n\n/** Raw `z.toJSONSchema` output; exported for the snapshot tests. */\nexport function zodJsonSchema(schema: z.ZodType): JsonNode {\n return z.toJSONSchema(schema, { io: 'output', unrepresentable: 'throw', cycles: 'throw' }) as JsonNode;\n}\n\n/** Converts a Zod object schema to the UNS record-schema subset or throws `CollectionSchemaError`. */\nexport function toRecordSchema(alias: string, schema: z.ZodType): RecordSchema {\n let raw: JsonNode;\n try {\n raw = zodJsonSchema(schema);\n } catch (error) {\n throw new CollectionSchemaError(alias, [\n {\n path: '',\n message: `${error instanceof Error ? error.message : String(error)}. \\`z.date()\\`, \\`z.bigint()\\`, \\`.transform()\\`, \\`z.map()\\`, \\`z.set()\\`, \\`z.custom()\\` and recursive schemas are not storable; store instants as ISO-8601 UTC strings from \\`toISOString()\\` and dates as \"YYYY-MM-DD\" strings, and keep transforms in the API input schema.`,\n },\n ]);\n }\n const issues: SchemaIssue[] = [];\n const normalized = normalizeNode(raw, '', 0, issues);\n if (normalized && normalized.type !== 'object') {\n issues.push({ path: '', message: 'A collection schema must be `z.object({...})`.' });\n }\n if (issues.length > 0 || !normalized) throw new CollectionSchemaError(alias, issues);\n return normalized;\n}\n\n/** Resolves a dotted business path in a record schema; array levels accept index segments. */\nexport function recordSchemaAt(schema: RecordSchema, path: string): RecordSchema | undefined {\n let current: RecordSchema | undefined = schema;\n for (const segment of path.split('.')) {\n if (!current) return undefined;\n if (current.type === 'array' && isArraySegment(segment)) {\n current = current.items;\n } else if (current.type === 'object') {\n current = current.properties?.[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\nfunction isArraySegment(segment: string): boolean {\n return /^(?:\\d+|\\$|\\$\\[[A-Za-z0-9_]*\\])$/.test(segment);\n}\n\n/**\n * Index paths follow object properties only: a path that continues past an\n * array (`items.sku`) would index values inside array items, which UNS\n * expression indexes cannot do.\n */\nfunction indexPathProblem(alias: string, schema: RecordSchema, path: string, kind: 'btree' | 'gin'): string | null {\n const segments = path.split('.');\n let current: RecordSchema | undefined = schema;\n for (const [position, segment] of segments.entries()) {\n if (current?.type === 'array') {\n const arrayPath = segments.slice(0, position).join('.');\n return `\"${path}\" reaches into the items of array \"${arrayPath}\"; index the array itself with kind: \"gin\", or copy the value to a top-level field.`;\n }\n current = current?.type === 'object' ? current.properties?.[segment] : undefined;\n if (!current) return `\"${path}\" is not a declared field of \"${alias}\".`;\n }\n const target = current as RecordSchema;\n if (kind === 'btree' && (target.type === 'object' || target.type === 'array')) {\n return `\"${path}\" is an ${target.type}; index a scalar field or use kind: \"gin\".`;\n }\n if (kind === 'gin' && target.type !== 'object' && target.type !== 'array') {\n return `\"${path}\" is a ${target.type}; a GIN index covers an object or array field.`;\n }\n return null;\n}\n\n/** A TTL index expires records by one integer field of Unix milliseconds. */\nfunction ttlProblem(alias: string, schema: RecordSchema, index: IndexSpec, kind: 'btree' | 'gin'): string | null {\n const seconds = index.expireAfterSeconds as number;\n if (!Number.isInteger(seconds) || seconds < SCHEMA_LIMITS.minExpireAfterSeconds || seconds > SCHEMA_LIMITS.maxExpireAfterSeconds) {\n return `\\`expireAfterSeconds\\` is an integer from ${SCHEMA_LIMITS.minExpireAfterSeconds} to ${SCHEMA_LIMITS.maxExpireAfterSeconds} (one year).`;\n }\n if (index.path === undefined || kind !== 'btree' || index.unique) return 'A TTL index covers a single `path` and is neither unique nor GIN.';\n const target = recordSchemaAt(schema, index.path);\n if (target?.type !== 'integer') {\n return `TTL field \"${index.path}\" of \"${alias}\" must be declared \\`z.number().int()\\` holding Unix milliseconds (e.g. \\`Date.now()\\`).`;\n }\n return null;\n}\n\nfunction normalizeIndexes(alias: string, indexes: readonly IndexSpec[], schema: RecordSchema, issues: SchemaIssue[]): NormalizedIndex[] {\n const out: NormalizedIndex[] = [];\n const seen = new Set<string>();\n let ttl = 0;\n if (indexes.length > SCHEMA_LIMITS.indexes) {\n issues.push({ path: 'indexes', message: `At most ${SCHEMA_LIMITS.indexes} indexes per collection.` });\n }\n indexes.forEach((index, position) => {\n const at = `indexes[${position}]`;\n const paths = index.paths ?? (index.path !== undefined ? [index.path] : []);\n if ((index.path !== undefined) === (index.paths !== undefined)) {\n issues.push({ path: at, message: 'Set exactly one of `path` or `paths`.' });\n return;\n }\n if (paths.length === 0 || paths.length > SCHEMA_LIMITS.indexPaths) {\n issues.push({ path: at, message: `A compound index has 1–${SCHEMA_LIMITS.indexPaths} paths.` });\n return;\n }\n const kind = index.kind ?? 'btree';\n if (kind !== 'btree' && kind !== 'gin') {\n issues.push({ path: at, message: '`kind` is \"btree\" or \"gin\".' });\n return;\n }\n if (kind === 'gin' && (paths.length !== 1 || index.unique)) {\n issues.push({ path: at, message: 'A GIN index covers one object/array path and cannot be unique.' });\n return;\n }\n if (new Set(paths).size !== paths.length) {\n issues.push({ path: at, message: 'A compound index lists each path once.' });\n return;\n }\n for (const fieldPath of paths) {\n const problem = indexPathProblem(alias, schema, fieldPath, kind);\n if (problem) {\n issues.push({ path: at, message: problem });\n return;\n }\n }\n if (index.expireAfterSeconds !== undefined) {\n const problem = ttlProblem(alias, schema, index, kind);\n if (problem) {\n issues.push({ path: at, message: problem });\n return;\n }\n ttl += 1;\n if (ttl > SCHEMA_LIMITS.ttlIndexes) {\n issues.push({ path: at, message: 'A collection has at most one TTL index (`expireAfterSeconds`).' });\n return;\n }\n }\n const normalized: NormalizedIndex = index.paths ? { paths: [...paths] } : { path: paths[0] };\n if (index.unique) normalized.unique = true;\n if (kind === 'gin') normalized.kind = 'gin';\n if (index.expireAfterSeconds !== undefined) normalized.expireAfterSeconds = index.expireAfterSeconds;\n const key = JSON.stringify(normalized);\n if (!seen.has(key)) {\n seen.add(key);\n out.push(normalized);\n }\n });\n // A TTL index is an ordinary B-tree on its path as well: a plain index on the same path would duplicate it.\n const ttlPaths = new Set(out.filter((index) => index.expireAfterSeconds !== undefined).map((index) => index.path));\n return out.filter((index) => index.expireAfterSeconds !== undefined || index.unique || index.kind || !ttlPaths.has(index.path));\n}\n\nconst compiled = new WeakMap<CollectionDefinition, CompiledCollection>();\n\n/** Ensure payload for one declaration; memoized per definition object. */\nexport function compileCollection(definition: CollectionDefinition): CompiledCollection {\n const cached = compiled.get(definition);\n if (cached) return cached;\n if (!ALIAS_PATTERN.test(definition.alias)) {\n throw new CollectionSchemaError(definition.alias, [{ path: 'alias', message: `Alias must match ${ALIAS_PATTERN}.` }]);\n }\n try {\n assertCollectionName(definition.name);\n } catch (error) {\n throw new CollectionSchemaError(definition.alias, [{ path: 'name', message: error instanceof Error ? error.message : String(error) }]);\n }\n const recordSchema = toRecordSchema(definition.alias, definition.schema);\n const issues: SchemaIssue[] = [];\n const indexes = normalizeIndexes(definition.alias, definition.indexes, recordSchema, issues);\n if (issues.length > 0) throw new CollectionSchemaError(definition.alias, issues);\n const result: CompiledCollection = {\n alias: definition.alias,\n name: definition.name,\n recordSchema,\n indexes,\n ...(definition.description ? { description: definition.description } : {}),\n };\n compiled.set(definition, result);\n return result;\n}\n\n/* ------------------------------------------------------------------ */\n/* Write validation */\n/* ------------------------------------------------------------------ */\n\ntype IssuePath = (string | number)[];\n\nfunction unknownKeyIssues(schema: RecordSchema | undefined, value: unknown, path: IssuePath, out: z.core.$ZodIssue[]) {\n if (!schema) return;\n if (schema.type === 'object' && isPlainObject(value)) {\n const properties = schema.properties ?? {};\n const unknown = Object.keys(value).filter((key) => !(key in properties));\n if (unknown.length > 0) {\n out.push({\n code: 'unrecognized_keys',\n keys: unknown,\n path,\n message: `Unknown field${unknown.length > 1 ? 's' : ''} ${unknown.map((key) => `\"${key}\"`).join(', ')}: declare ${unknown.length > 1 ? 'them' : 'it'} in the collection schema first.`,\n input: value,\n } as z.core.$ZodIssue);\n }\n for (const [key, child] of Object.entries(value)) {\n if (key in properties) unknownKeyIssues(properties[key], child, [...path, key], out);\n }\n } else if (schema.type === 'array' && Array.isArray(value)) {\n value.forEach((item, index) => unknownKeyIssues(schema.items, item, [...path, index], out));\n }\n}\n\nfunction strictParse<T>(zodSchema: z.ZodType<T>, recordSchema: RecordSchema | undefined, value: unknown, path: IssuePath): T {\n const issues: z.core.$ZodIssue[] = [];\n unknownKeyIssues(recordSchema, value, path, issues);\n const result = zodSchema.safeParse(value);\n if (!result.success) {\n for (const issue of result.error.issues) issues.push({ ...issue, path: [...path, ...issue.path] } as z.core.$ZodIssue);\n }\n if (issues.length > 0) throw new z.ZodError(issues);\n return result.data as T;\n}\n\nfunction zodAt(schema: z.ZodType, path: string): z.ZodType | undefined {\n let current: z.ZodType | undefined = schema;\n for (const segment of path.split('.')) {\n while (current instanceof z.ZodOptional) current = current.unwrap() as z.ZodType;\n if (current instanceof z.ZodObject) {\n current = (current.shape as Record<string, z.ZodType>)[segment];\n } else if (current instanceof z.ZodArray && isArraySegment(segment)) {\n current = current.element as z.ZodType;\n } else {\n return undefined;\n }\n if (!current) return undefined;\n }\n return current;\n}\n\nfunction validationError(path: IssuePath, message: string, input: unknown): z.ZodError {\n return new z.ZodError([{ code: 'custom', path, message, input } as z.core.$ZodIssue]);\n}\n\n/** Splits `_id` / `_meta` off a document and strictly validates the body. */\nexport function validateDocument(\n definition: CollectionDefinition,\n document: Record<string, unknown>,\n): { id?: string; data: Record<string, unknown> } {\n if (!isPlainObject(document)) throw validationError([], 'Expected a document object.', document);\n const { _id, _meta, ...body } = document;\n void _meta;\n if (_id !== undefined && (typeof _id !== 'string' || _id.length === 0 || _id.length > 128)) {\n throw validationError(['_id'], '`_id` must be a string of 1–128 characters.', _id);\n }\n const { recordSchema } = compileCollection(definition);\n const data = strictParse(definition.schema, recordSchema, body, []) as Record<string, unknown>;\n return { ...(typeof _id === 'string' ? { id: _id } : {}), data };\n}\n\n/**\n * Validates `data` of a transaction step. Fields filled by `bindings`\n * (`data.<field>...`) are checked only for being declared; every literal\n * field is strictly validated, and other required fields must be present.\n */\nexport function validateStepData(\n definition: CollectionDefinition,\n data: Record<string, unknown>,\n boundFields: readonly string[],\n): Record<string, unknown> {\n if (!isPlainObject(data)) throw validationError(['data'], 'Expected a document object.', data);\n if ('_id' in data || '_meta' in data) {\n 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);\n }\n const { recordSchema } = compileCollection(definition);\n const properties = recordSchema.properties ?? {};\n const bound = new Set(boundFields.filter((field) => field in properties));\n const unknownBound = boundFields.filter((field) => !(field in properties));\n if (unknownBound.length > 0) {\n throw validationError(['bindings'], `Bound field${unknownBound.length > 1 ? 's' : ''} ${unknownBound.join(', ')} not declared in \"${definition.alias}\".`, boundFields);\n }\n if (bound.size === 0) return strictParse(definition.schema, recordSchema, data, ['data']) as Record<string, unknown>;\n\n const literal = Object.fromEntries(Object.entries(data).filter(([key]) => !bound.has(key)));\n const omit = Object.fromEntries([...bound].map((field) => [field, true as const]));\n const literalSchema: RecordSchema = {\n ...recordSchema,\n properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !bound.has(key))),\n required: recordSchema.required?.filter((key) => !bound.has(key)),\n };\n const parsed = strictParse(definition.schema.omit(omit as never), literalSchema, literal, ['data']) as Record<string, unknown>;\n const boundValues = Object.fromEntries(Object.entries(data).filter(([key]) => bound.has(key)));\n return { ...parsed, ...boundValues };\n}\n\nconst VALUE_OPERATORS = new Set(['$set', '$setOnInsert']);\nconst ELEMENT_OPERATORS = new Set(['$push', '$addToSet']);\nconst NUMERIC_OPERATORS = new Set(['$inc', '$mul']);\n\n/** Validates update-operator documents against the declaration (paths and values). */\nexport function validateUpdate(definition: CollectionDefinition, update: Record<string, unknown>): Record<string, unknown> {\n if (!isPlainObject(update) || Object.keys(update).length === 0) {\n throw validationError([], 'An update needs at least one operator such as `$set`.', update);\n }\n const { recordSchema } = compileCollection(definition);\n const out: Record<string, unknown> = {};\n\n for (const [operator, fields] of Object.entries(update)) {\n if (!operator.startsWith('$')) {\n throw validationError([operator], \"Updates use operators (`{ $set: { status: \\\"DONE\\\" } }`); use replaceOne() to replace a whole document.\", update);\n }\n if (!isPlainObject(fields)) throw validationError([operator], `\\`${operator}\\` takes an object of field paths.`, fields);\n const next: Record<string, unknown> = {};\n\n for (const [path, value] of Object.entries(fields)) {\n const issuePath = [operator, path];\n if (path === '_id' || path === '_meta' || path.startsWith('_meta.')) {\n throw validationError(issuePath, '`_id` and `_meta` are read-only.', value);\n }\n const target = recordSchemaAt(recordSchema, path);\n const zodTarget = zodAt(definition.schema, path);\n if (!target || !zodTarget) {\n throw validationError(issuePath, `\"${path}\" is not a declared field of \"${definition.alias}\".`, value);\n }\n\n if (VALUE_OPERATORS.has(operator)) {\n if (value === undefined) continue;\n next[path] = strictParse(zodTarget, target, value, issuePath);\n } else if (ELEMENT_OPERATORS.has(operator)) {\n const element = zodTarget instanceof z.ZodOptional ? zodTarget.unwrap() : zodTarget;\n if (target.type !== 'array' || !(element instanceof z.ZodArray)) {\n throw validationError(issuePath, `\\`${operator}\\` needs an array field; \"${path}\" is ${target.type}.`, value);\n }\n const each = isPlainObject(value) && Array.isArray(value.$each);\n const items = each ? ((value as { $each: unknown[] }).$each) : [value];\n const parsed = items.map((item, index) =>\n strictParse(element.element as z.ZodType, target.items, item, each ? [...issuePath, '$each', index] : issuePath),\n );\n next[path] = each ? { ...(value as Record<string, unknown>), $each: parsed } : parsed[0];\n } else if (NUMERIC_OPERATORS.has(operator)) {\n if (target.type !== 'number' && target.type !== 'integer') {\n throw validationError(issuePath, `\\`${operator}\\` needs a numeric field; \"${path}\" is ${target.type}.`, value);\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw validationError(issuePath, `\\`${operator}\\` needs a finite number.`, value);\n }\n next[path] = value;\n } else if (operator === '$rename') {\n if (typeof value !== 'string' || !recordSchemaAt(recordSchema, value)) {\n throw validationError(issuePath, `\\`$rename\\` target \"${String(value)}\" is not a declared field.`, value);\n }\n next[path] = value;\n } else {\n // $unset, $min, $max, $currentDate, $pop, $pull, $pullAll: the path is\n // declared; UNS validates the resulting document.\n next[path] = value;\n }\n }\n if (Object.keys(next).length > 0) out[operator] = next;\n }\n if (Object.keys(out).length === 0) {\n throw validationError([], 'Nothing to update: undefined values are dropped; clear a field with `$unset`.', update);\n }\n return out;\n}\n"]}
|