@confect/core 10.0.0-next.9 → 10.0.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +958 -47
  2. package/README.md +3 -1
  3. package/dist/FunctionProvenance.d.ts +166 -68
  4. package/dist/FunctionProvenance.d.ts.map +1 -1
  5. package/dist/FunctionProvenance.js +55 -13
  6. package/dist/FunctionProvenance.js.map +1 -1
  7. package/dist/FunctionSpec.d.ts +320 -138
  8. package/dist/FunctionSpec.d.ts.map +1 -1
  9. package/dist/FunctionSpec.js +56 -13
  10. package/dist/FunctionSpec.js.map +1 -1
  11. package/dist/GenericId.d.ts.map +1 -1
  12. package/dist/GenericId.js +1 -1
  13. package/dist/GroupPath.d.ts +6 -10
  14. package/dist/GroupPath.d.ts.map +1 -1
  15. package/dist/GroupPath.js.map +1 -1
  16. package/dist/GroupSpec.d.ts +25 -12
  17. package/dist/GroupSpec.d.ts.map +1 -1
  18. package/dist/GroupSpec.js +51 -14
  19. package/dist/GroupSpec.js.map +1 -1
  20. package/dist/Identifier.d.ts +6 -5
  21. package/dist/Identifier.d.ts.map +1 -1
  22. package/dist/Identifier.js +6 -5
  23. package/dist/Identifier.js.map +1 -1
  24. package/dist/Lazy.d.ts +11 -14
  25. package/dist/Lazy.d.ts.map +1 -1
  26. package/dist/Lazy.js +11 -14
  27. package/dist/Lazy.js.map +1 -1
  28. package/dist/MiddlewareAttachment.d.ts +171 -0
  29. package/dist/MiddlewareAttachment.d.ts.map +1 -0
  30. package/dist/MiddlewareAttachment.js +48 -0
  31. package/dist/MiddlewareAttachment.js.map +1 -0
  32. package/dist/MiddlewareSpec.d.ts +198 -0
  33. package/dist/MiddlewareSpec.d.ts.map +1 -0
  34. package/dist/MiddlewareSpec.js +60 -0
  35. package/dist/MiddlewareSpec.js.map +1 -0
  36. package/dist/PaginationError.d.ts +20 -0
  37. package/dist/PaginationError.d.ts.map +1 -0
  38. package/dist/PaginationError.js +31 -0
  39. package/dist/PaginationError.js.map +1 -0
  40. package/dist/PaginationOptions.d.ts +23 -0
  41. package/dist/PaginationOptions.d.ts.map +1 -0
  42. package/dist/PaginationOptions.js +29 -0
  43. package/dist/PaginationOptions.js.map +1 -0
  44. package/dist/PaginationResult.d.ts +1 -0
  45. package/dist/PaginationResult.d.ts.map +1 -1
  46. package/dist/PaginationResult.js.map +1 -1
  47. package/dist/Ref.d.ts +135 -47
  48. package/dist/Ref.d.ts.map +1 -1
  49. package/dist/Ref.js +104 -46
  50. package/dist/Ref.js.map +1 -1
  51. package/dist/Refs.d.ts +10 -5
  52. package/dist/Refs.d.ts.map +1 -1
  53. package/dist/Refs.js +5 -4
  54. package/dist/Refs.js.map +1 -1
  55. package/dist/SchemaToValidator.d.ts +99 -0
  56. package/dist/SchemaToValidator.d.ts.map +1 -0
  57. package/dist/SchemaToValidator.js +158 -0
  58. package/dist/SchemaToValidator.js.map +1 -0
  59. package/dist/Spec.d.ts +16 -12
  60. package/dist/Spec.d.ts.map +1 -1
  61. package/dist/Spec.js +14 -9
  62. package/dist/Spec.js.map +1 -1
  63. package/dist/SystemFields.d.ts +16 -15
  64. package/dist/SystemFields.d.ts.map +1 -1
  65. package/dist/SystemFields.js +16 -15
  66. package/dist/SystemFields.js.map +1 -1
  67. package/dist/Table.d.ts +75 -0
  68. package/dist/Table.d.ts.map +1 -0
  69. package/dist/Table.js +77 -0
  70. package/dist/Table.js.map +1 -0
  71. package/dist/Types.d.ts +8 -2
  72. package/dist/Types.d.ts.map +1 -1
  73. package/dist/Types.js.map +1 -1
  74. package/dist/UserIdentity.d.ts.map +1 -1
  75. package/dist/index.d.ts +6 -1
  76. package/dist/index.d.ts.map +1 -1
  77. package/dist/index.js +9 -4
  78. package/package.json +17 -15
  79. package/src/FunctionProvenance.ts +197 -34
  80. package/src/FunctionSpec.ts +332 -86
  81. package/src/GroupPath.ts +6 -12
  82. package/src/GroupSpec.ts +184 -25
  83. package/src/Identifier.ts +6 -5
  84. package/src/Lazy.ts +11 -14
  85. package/src/MiddlewareAttachment.ts +106 -0
  86. package/src/MiddlewareSpec.ts +392 -0
  87. package/src/PaginationError.ts +78 -0
  88. package/src/PaginationOptions.ts +23 -0
  89. package/src/PaginationResult.ts +4 -0
  90. package/src/Ref.ts +468 -236
  91. package/src/Refs.ts +43 -18
  92. package/src/SchemaToValidator.ts +612 -0
  93. package/src/Spec.ts +50 -39
  94. package/src/SystemFields.ts +30 -31
  95. package/src/Table.ts +427 -0
  96. package/src/Types.ts +9 -3
  97. package/src/index.ts +6 -1
  98. package/dist/Registry.d.ts +0 -24
  99. package/dist/Registry.d.ts.map +0 -1
  100. package/dist/Registry.js +0 -19
  101. package/dist/Registry.js.map +0 -1
  102. package/dist/tsconfig.src.tsbuildinfo +0 -1
  103. package/src/Registry.ts +0 -30
@@ -0,0 +1,158 @@
1
+ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
+ import { tableName } from "./GenericId.js";
3
+ import * as Data from "effect/Data";
4
+ import * as Schema from "effect/Schema";
5
+ import * as Predicate from "effect/Predicate";
6
+ import * as Option from "effect/Option";
7
+ import * as SchemaAST from "effect/SchemaAST";
8
+ import { v } from "convex/values";
9
+ import * as Match from "effect/Match";
10
+ import * as Effect from "effect/Effect";
11
+ import { pipe } from "effect/Function";
12
+ import * as Array from "effect/Array";
13
+ import * as Number from "effect/Number";
14
+ import * as String from "effect/String";
15
+ //#region src/SchemaToValidator.ts
16
+ var SchemaToValidator_exports = /* @__PURE__ */ __exportAll({
17
+ EmptyTupleIsNotSupportedError: () => EmptyTupleIsNotSupportedError,
18
+ EmptyUnionIsNotSupportedError: () => EmptyUnionIsNotSupportedError,
19
+ IndexSignaturesAreNotSupportedError: () => IndexSignaturesAreNotSupportedError,
20
+ MixedIndexAndPropertySignaturesAreNotSupportedError: () => MixedIndexAndPropertySignaturesAreNotSupportedError,
21
+ OptionalTupleElementsAreNotSupportedError: () => OptionalTupleElementsAreNotSupportedError,
22
+ TopLevelMustBeObjectError: () => TopLevelMustBeObjectError,
23
+ TopLevelMustBeObjectOrUnionError: () => TopLevelMustBeObjectOrUnionError,
24
+ UnsupportedPropertySignatureKeyTypeError: () => UnsupportedPropertySignatureKeyTypeError,
25
+ UnsupportedSchemaTypeError: () => UnsupportedSchemaTypeError,
26
+ compileArgsSchema: () => compileArgsSchema,
27
+ compileAst: () => compileAst,
28
+ compileReturnsSchema: () => compileReturnsSchema,
29
+ compileSchema: () => compileSchema,
30
+ compileTableSchema: () => compileTableSchema,
31
+ isRecursive: () => isRecursive
32
+ });
33
+ const compileArgsSchema = (argsSchema) => {
34
+ const ast = Schema.toEncoded(argsSchema).ast;
35
+ return pipe(ast, Match.value, Match.tag("Objects", (objectsAst) => Array.isReadonlyArrayEmpty(objectsAst.indexSignatures) ? handlePropertySignatures(objectsAst) : Effect.fail(new IndexSignaturesAreNotSupportedError())), Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())), Effect.runSync);
36
+ };
37
+ const compileReturnsSchema = (schema) => Effect.runSync(compileAst(Schema.toEncoded(schema).ast));
38
+ const compileTableSchema = (schema) => {
39
+ const ast = Schema.toEncoded(schema).ast;
40
+ return pipe(ast, Match.value, Match.tag("Objects", ({ indexSignatures }) => Array.isReadonlyArrayEmpty(indexSignatures) ? compileAst(ast) : Effect.fail(new IndexSignaturesAreNotSupportedError())), Match.tag("Union", (unionAst) => compileAst(unionAst)), Match.orElse(() => Effect.fail(new TopLevelMustBeObjectOrUnionError())), Effect.runSync);
41
+ };
42
+ const compileSchema = (schema) => Effect.runSync(compileAst(schema.ast));
43
+ const isRecursive = (ast) => pipe(ast, Match.value, Match.tag("Literal", "Null", "Boolean", "String", "Number", "BigInt", "Unknown", "Any", "Declaration", "UniqueSymbol", "Symbol", "Undefined", "Void", "Never", "Enum", "TemplateLiteral", "ObjectKeyword", () => false), Match.tag("Union", ({ types }) => Array.some(types, (type) => isRecursive(type))), Match.tag("Objects", ({ propertySignatures }) => Array.some(propertySignatures, ({ type }) => isRecursive(type))), Match.tag("Arrays", ({ elements, rest }) => Array.some(elements, (element) => isRecursive(element)) || Array.some(rest, (element) => isRecursive(element))), Match.tag("Suspend", () => true), Match.exhaustive);
44
+ const compileAst = (ast, isOptionalPropertyOfTypeLiteral = false) => isRecursive(ast) ? Effect.succeed(v.any()) : pipe(ast, Match.value, Match.tag("Literal", ({ literal }) => pipe(literal, Match.value, Match.whenOr(Match.string, Match.number, Match.bigint, Match.boolean, (l) => v.literal(l)), Match.exhaustive, Effect.succeed)), Match.tag("Null", () => Effect.succeed(v.null())), Match.tag("Boolean", () => Effect.succeed(v.boolean())), Match.tag("String", (stringAst) => tableName(stringAst).pipe(Option.match({
45
+ onNone: () => Effect.succeed(v.string()),
46
+ onSome: (tableName) => Effect.succeed(v.id(tableName))
47
+ }))), Match.tag("Number", () => Effect.succeed(v.float64())), Match.tag("BigInt", () => Effect.succeed(v.int64())), Match.tag("Union", (unionAst) => handleUnion(unionAst, isOptionalPropertyOfTypeLiteral)), Match.tag("Objects", (objectsAst) => handleObjects(objectsAst)), Match.tag("Arrays", (arraysAst) => handleArrays(arraysAst)), Match.tag("Unknown", "Any", () => Effect.succeed(v.any())), Match.tag("Declaration", (declaration) => Effect.mapBoth(declaration.run(declaration.typeParameters)(/* @__PURE__ */ new ArrayBuffer(0), declaration, {}), {
48
+ onSuccess: () => v.bytes(),
49
+ onFailure: () => new UnsupportedSchemaTypeError({ schemaType: declaration._tag })
50
+ })), Match.tag("Suspend", () => Effect.succeed(v.any())), Match.tag("UniqueSymbol", "Symbol", "Undefined", "Void", "Never", "Enum", "TemplateLiteral", "ObjectKeyword", () => Effect.fail(new UnsupportedSchemaTypeError({ schemaType: ast._tag }))), Match.exhaustive);
51
+ const handleUnion = ({ types }, isOptionalPropertyOfTypeLiteral) => handleUnionTypes(types, isOptionalPropertyOfTypeLiteral);
52
+ const handleUnionTypes = Effect.fnUntraced(function* (types, isOptionalPropertyOfTypeLiteral) {
53
+ const members = isOptionalPropertyOfTypeLiteral ? Array.filter(types, Predicate.not(SchemaAST.isUndefined)) : types;
54
+ const [firstValidator, secondValidator, ...restValidators] = yield* Effect.all(Array.map(members, (type) => compileAst(type)));
55
+ if (firstValidator === void 0) return yield* new EmptyUnionIsNotSupportedError();
56
+ else if (secondValidator === void 0) return firstValidator;
57
+ else return v.union(firstValidator, secondValidator, ...restValidators);
58
+ });
59
+ const handleObjects = (objectsAst) => pipe(objectsAst.indexSignatures, Array.head, Option.match({
60
+ onNone: () => Effect.map(handlePropertySignatures(objectsAst), v.object),
61
+ onSome: ({ parameter, type }) => pipe(objectsAst.propertySignatures, Array.head, Option.match({
62
+ onNone: () => Effect.map(Effect.all({
63
+ parameter_: compileAst(parameter),
64
+ type_: compileAst(type)
65
+ }), ({ parameter_, type_ }) => v.record(parameter_, type_)),
66
+ onSome: () => Effect.fail(new MixedIndexAndPropertySignaturesAreNotSupportedError())
67
+ }))
68
+ }));
69
+ const handleArrays = ({ elements, rest }) => handleArrayElements(elements, rest);
70
+ const handleArrayElements = Effect.fnUntraced(function* (elements, rest) {
71
+ const [f, s, ...r] = elements;
72
+ const elementToValidator = (element) => SchemaAST.isOptional(element) ? Effect.fail(new OptionalTupleElementsAreNotSupportedError()) : compileAst(element);
73
+ const arrayItemsValidator = yield* f === void 0 ? pipe(rest, Array.head, Option.match({
74
+ onNone: () => Effect.fail(new EmptyTupleIsNotSupportedError()),
75
+ onSome: (type) => compileAst(type)
76
+ })) : s === void 0 ? elementToValidator(f) : Effect.gen(function* () {
77
+ const firstValidator = yield* elementToValidator(f);
78
+ const secondValidator = yield* elementToValidator(s);
79
+ const restValidators = yield* Effect.forEach(r, elementToValidator);
80
+ return v.union(firstValidator, secondValidator, ...restValidators);
81
+ });
82
+ return v.array(arrayItemsValidator);
83
+ });
84
+ const handlePropertySignatures = (objectsAst) => pipe(objectsAst.propertySignatures, Effect.forEach(({ type, name }) => {
85
+ const isOptional = SchemaAST.isOptional(type);
86
+ if (String.isString(name)) return Option.match(Number.parse(name), {
87
+ onNone: () => Effect.gen(function* () {
88
+ const validator = yield* compileAst(type, isOptional);
89
+ return {
90
+ propertyName: name,
91
+ validator: isOptional ? v.optional(validator) : validator
92
+ };
93
+ }),
94
+ onSome: (number) => Effect.fail(new UnsupportedPropertySignatureKeyTypeError({ propertyKey: number }))
95
+ });
96
+ else return Effect.fail(new UnsupportedPropertySignatureKeyTypeError({ propertyKey: name }));
97
+ }), Effect.andThen((propertyNamesWithValidators) => pipe(propertyNamesWithValidators, Array.reduce({}, (acc, { propertyName, validator }) => ({
98
+ [propertyName]: validator,
99
+ ...acc
100
+ })), Effect.succeed)));
101
+ var TopLevelMustBeObjectError = class extends Data.TaggedError("TopLevelMustBeObjectError") {
102
+ /* v8 ignore start */
103
+ get message() {
104
+ return "Top level schema must be an object";
105
+ }
106
+ };
107
+ var TopLevelMustBeObjectOrUnionError = class extends Data.TaggedError("TopLevelMustBeObjectOrUnionError") {
108
+ /* v8 ignore start */
109
+ get message() {
110
+ return "Top level schema must be an object or a union";
111
+ }
112
+ };
113
+ var UnsupportedPropertySignatureKeyTypeError = class extends Data.TaggedError("UnsupportedPropertySignatureKeyTypeError") {
114
+ /* v8 ignore start */
115
+ get message() {
116
+ return `Unsupported property signature '${this.propertyKey.toString()}'. Property is of type '${typeof this.propertyKey}' but only 'string' properties are supported.`;
117
+ }
118
+ };
119
+ var EmptyTupleIsNotSupportedError = class extends Data.TaggedError("EmptyTupleIsNotSupportedError") {
120
+ /* v8 ignore start */
121
+ get message() {
122
+ return "Tuple must have at least one element";
123
+ }
124
+ };
125
+ var EmptyUnionIsNotSupportedError = class extends Data.TaggedError("EmptyUnionIsNotSupportedError") {
126
+ /* v8 ignore start */
127
+ get message() {
128
+ return "Union must have at least one member that compiles to a validator";
129
+ }
130
+ };
131
+ var UnsupportedSchemaTypeError = class extends Data.TaggedError("UnsupportedSchemaTypeError") {
132
+ /* v8 ignore start */
133
+ get message() {
134
+ return `Unsupported schema type '${this.schemaType}'`;
135
+ }
136
+ };
137
+ var IndexSignaturesAreNotSupportedError = class extends Data.TaggedError("IndexSignaturesAreNotSupportedError") {
138
+ /* v8 ignore start */
139
+ get message() {
140
+ return "Index signatures are not supported";
141
+ }
142
+ };
143
+ var MixedIndexAndPropertySignaturesAreNotSupportedError = class extends Data.TaggedError("MixedIndexAndPropertySignaturesAreNotSupportedError") {
144
+ /* v8 ignore start */
145
+ get message() {
146
+ return "Mixed index and property signatures are not supported";
147
+ }
148
+ };
149
+ var OptionalTupleElementsAreNotSupportedError = class extends Data.TaggedError("OptionalTupleElementsAreNotSupportedError") {
150
+ /* v8 ignore start */
151
+ get message() {
152
+ return "Optional tuple elements are not supported";
153
+ }
154
+ };
155
+ //#endregion
156
+ export { EmptyTupleIsNotSupportedError, EmptyUnionIsNotSupportedError, IndexSignaturesAreNotSupportedError, MixedIndexAndPropertySignaturesAreNotSupportedError, OptionalTupleElementsAreNotSupportedError, SchemaToValidator_exports, TopLevelMustBeObjectError, TopLevelMustBeObjectOrUnionError, UnsupportedPropertySignatureKeyTypeError, UnsupportedSchemaTypeError, compileArgsSchema, compileAst, compileReturnsSchema, compileSchema, compileTableSchema, isRecursive };
157
+
158
+ //# sourceMappingURL=SchemaToValidator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaToValidator.js","names":["GenericId.tableName"],"sources":["../src/SchemaToValidator.ts"],"sourcesContent":["import type {\n PropertyValidators,\n Validator,\n VAny,\n VArray,\n VBoolean,\n VBytes,\n VFloat64,\n VId,\n VInt64,\n VLiteral,\n VNull,\n VObject,\n VOptional,\n VRecord,\n VString,\n VUnion,\n} from \"convex/values\";\nimport { v } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Number from \"effect/Number\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as String from \"effect/String\";\n\nimport * as GenericId from \"./GenericId\";\nimport type {\n IsAny,\n IsOptional,\n IsRecord,\n IsRecursive,\n IsUnion,\n TypeError,\n UnionToTuple,\n} from \"./Types\";\n\n// Args\n\nexport const compileArgsSchema = <ConfectValue, ConvexValue>(\n argsSchema: Schema.Codec<ConfectValue, ConvexValue>,\n): PropertyValidators => {\n const ast = Schema.toEncoded(argsSchema).ast;\n\n return pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", (objectsAst) =>\n Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)\n ? handlePropertySignatures(objectsAst)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),\n Effect.runSync,\n );\n};\n\n// Returns\n\nexport const compileReturnsSchema = <ConfectValue, ConvexValue>(\n schema: Schema.Codec<ConfectValue, ConvexValue>,\n): Validator<any, any, any> =>\n Effect.runSync(compileAst(Schema.toEncoded(schema).ast));\n\n// Table\n\n/**\n * Convert a table `Schema` to a table `Validator`.\n */\nexport type TableSchemaToTableValidator<\n TableSchema extends Schema.Codec<any, any>,\n> =\n ValueToValidator<TableSchema[\"Encoded\"]> extends infer Vd extends\n | VObject<any, any, any, any>\n | VUnion<any, any, any, any>\n ? Vd\n : never;\n\nexport const compileTableSchema = <TableSchema extends Schema.Codec<any, any>>(\n schema: TableSchema,\n): TableSchemaToTableValidator<TableSchema> => {\n const ast = Schema.toEncoded(schema).ast;\n\n return pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", ({ indexSignatures }) =>\n Array.isReadonlyArrayEmpty(indexSignatures)\n ? // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- The return type is derived from the input schema and cannot be recovered from the runtime AST.\n (compileAst(ast) as Effect.Effect<any>)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.tag(\"Union\", (unionAst) => compileAst(unionAst)),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectOrUnionError())),\n Effect.runSync,\n );\n};\n\n// Compiler\n\nexport type ReadonlyValue =\n | string\n | number\n | bigint\n | boolean\n | ArrayBuffer\n | ReadonlyArrayValue\n | ReadonlyRecordValue\n | null;\n\ntype ReadonlyArrayValue = readonly ReadonlyValue[];\n\nexport type ReadonlyRecordValue = {\n readonly [key: string]: ReadonlyValue | undefined;\n};\n\ntype MutableValue<T> =\n T extends ReadonlyArray<infer El>\n ? MutableValue<El>[]\n : T extends ReadonlyRecordValue\n ? { -readonly [K in keyof T]: MutableValue<Exclude<T[K], undefined>> }\n : T;\n\nexport type ValueToValidator<Vl> = [Vl] extends [never]\n ? never\n : IsAny<Vl> extends true\n ? VAny\n : [Vl] extends [null]\n ? VNull\n : [Vl] extends [boolean]\n ? [boolean] extends [Vl]\n ? VBoolean\n : VLiteral<Vl>\n : IsUnion<Vl> extends true\n ? IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? UnionValueToValidator<Vl>\n : TypeError<\"Provided value is not a valid Convex value\", Vl>\n : [Vl] extends [number]\n ? [number] extends [Vl]\n ? VFloat64\n : VLiteral<Vl>\n : [Vl] extends [bigint]\n ? [bigint] extends [Vl]\n ? VInt64\n : VLiteral<Vl>\n : [Vl] extends [string]\n ? Vl extends {\n __tableName: infer TableName extends string;\n }\n ? VId<GenericId.GenericId<TableName>>\n : [string] extends [Vl]\n ? VString\n : VLiteral<Vl>\n : [Vl] extends [ArrayBuffer]\n ? VBytes\n : IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? Vl extends ReadonlyArray<ReadonlyValue>\n ? ArrayValueToValidator<Vl>\n : Vl extends ReadonlyRecordValue\n ? RecordValueToValidator<Vl>\n : TypeError<\"Unexpected value\", Vl>\n : TypeError<\n \"Provided value is not a valid Convex value\",\n Vl\n >;\n\ntype ArrayValueToValidator<Vl extends ReadonlyArray<ReadonlyValue>> =\n Vl extends ReadonlyArray<infer El extends ReadonlyValue>\n ? ValueToValidator<El> extends infer Vd extends Validator<any, any, any>\n ? VArray<MutableValue<El[]>, Vd>\n : never\n : never;\n\ntype RecordValueToValidator<Vl> = Vl extends ReadonlyRecordValue\n ? {\n -readonly [K in keyof Vl]-?: IsAny<Vl[K]> extends true\n ? IsOptional<Vl, K> extends true\n ? VOptional<VAny>\n : VAny\n : UndefinedOrValueToValidator<Vl[K]>;\n } extends infer VdRecord extends Record<string, any>\n ? MutableValue<Vl> extends infer VlRecord extends Record<string, any>\n ? IsRecord<VlRecord> extends true\n ? VRecord<VlRecord, VString, VdRecord[keyof VdRecord]>\n : VObject<VlRecord, VdRecord>\n : never\n : never\n : never;\n\nexport type UndefinedOrValueToValidator<Vl extends ReadonlyValue | undefined> =\n undefined extends Vl\n ? [Vl] extends [(infer Val extends ReadonlyValue) | undefined]\n ? ValueToValidator<Val> extends infer Vd extends Validator<\n any,\n \"required\",\n any\n >\n ? VOptional<Vd>\n : never\n : never\n : [Vl] extends [ReadonlyValue]\n ? ValueToValidator<Vl>\n : never;\n\ntype UnionValueToValidator<Vl extends ReadonlyValue> = [Vl] extends [\n ReadonlyValue,\n]\n ? IsUnion<Vl> extends true\n ? UnionToTuple<Vl> extends infer VlTuple extends\n ReadonlyArray<ReadonlyValue>\n ? ValueTupleToValidatorTuple<VlTuple> extends infer VdTuple extends\n Validator<any, \"required\", any>[]\n ? VUnion<MutableValue<Vl>, VdTuple>\n : TypeError<\"Failed to convert value tuple to validator tuple\">\n : TypeError<\"Failed to convert union to tuple\">\n : TypeError<\"Expected a union of values, but got a single value instead\">\n : TypeError<\"Provided value is not a valid Convex value\">;\n\ntype ValueTupleToValidatorTuple<VlTuple extends ReadonlyArray<ReadonlyValue>> =\n VlTuple extends\n | [true, false, ...infer VlRest extends ReadonlyArray<ReadonlyValue>]\n | [false, true, ...infer VlRest extends ReadonlyArray<ReadonlyValue>]\n ? ValueTupleToValidatorTuple<VlRest> extends infer VdRest extends Validator<\n any,\n any,\n any\n >[]\n ? [VBoolean<boolean>, ...VdRest]\n : never\n : VlTuple extends [\n infer Vl extends ReadonlyValue,\n ...infer VlRest extends ReadonlyArray<ReadonlyValue>,\n ]\n ? ValueToValidator<Vl> extends infer Vd extends Validator<any, any, any>\n ? ValueTupleToValidatorTuple<VlRest> extends infer VdRest extends\n Validator<any, \"required\", any>[]\n ? [Vd, ...VdRest]\n : never\n : never\n : [];\n\nexport const compileSchema = <T, E>(\n schema: Schema.Codec<T, E>,\n): ValueToValidator<(typeof schema)[\"Encoded\"]> =>\n Effect.runSync(compileAst(schema.ast)) as any;\n\nexport const isRecursive = (ast: SchemaAST.AST): boolean =>\n pipe(\n ast,\n Match.value,\n Match.tag(\n \"Literal\",\n \"Null\",\n \"Boolean\",\n \"String\",\n \"Number\",\n \"BigInt\",\n \"Unknown\",\n \"Any\",\n \"Declaration\",\n \"UniqueSymbol\",\n \"Symbol\",\n \"Undefined\",\n \"Void\",\n \"Never\",\n \"Enum\",\n \"TemplateLiteral\",\n \"ObjectKeyword\",\n () => false,\n ),\n Match.tag(\"Union\", ({ types }) =>\n Array.some(types, (type) => isRecursive(type)),\n ),\n Match.tag(\"Objects\", ({ propertySignatures }) =>\n Array.some(propertySignatures, ({ type }) => isRecursive(type)),\n ),\n Match.tag(\n \"Arrays\",\n ({ elements, rest }) =>\n Array.some(elements, (element) => isRecursive(element)) ||\n Array.some(rest, (element) => isRecursive(element)),\n ),\n Match.tag(\"Suspend\", () => true),\n Match.exhaustive,\n );\n\nexport const compileAst = (\n ast: SchemaAST.AST,\n isOptionalPropertyOfTypeLiteral = false,\n): Effect.Effect<\n Validator<any, any, any>,\n | UnsupportedSchemaTypeError\n | UnsupportedPropertySignatureKeyTypeError\n | IndexSignaturesAreNotSupportedError\n | MixedIndexAndPropertySignaturesAreNotSupportedError\n | OptionalTupleElementsAreNotSupportedError\n | EmptyTupleIsNotSupportedError\n | EmptyUnionIsNotSupportedError\n> =>\n isRecursive(ast)\n ? Effect.succeed(v.any())\n : pipe(\n ast,\n Match.value,\n Match.tag(\"Literal\", ({ literal }) =>\n pipe(\n literal,\n Match.value,\n Match.whenOr(\n Match.string,\n Match.number,\n Match.bigint,\n Match.boolean,\n (l) => v.literal(l),\n ),\n Match.exhaustive,\n Effect.succeed,\n ),\n ),\n Match.tag(\"Null\", () => Effect.succeed(v.null())),\n Match.tag(\"Boolean\", () => Effect.succeed(v.boolean())),\n Match.tag(\"String\", (stringAst) =>\n GenericId.tableName(stringAst).pipe(\n Option.match({\n onNone: () => Effect.succeed(v.string()),\n onSome: (tableName) => Effect.succeed(v.id(tableName)),\n }),\n ),\n ),\n Match.tag(\"Number\", () => Effect.succeed(v.float64())),\n Match.tag(\"BigInt\", () => Effect.succeed(v.int64())),\n Match.tag(\"Union\", (unionAst) =>\n handleUnion(unionAst, isOptionalPropertyOfTypeLiteral),\n ),\n Match.tag(\"Objects\", (objectsAst) => handleObjects(objectsAst)),\n Match.tag(\"Arrays\", (arraysAst) => handleArrays(arraysAst)),\n Match.tag(\"Unknown\", \"Any\", () => Effect.succeed(v.any())),\n Match.tag(\"Declaration\", (declaration) =>\n Effect.mapBoth(\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- Codec inputs are context-free, but Effect's SchemaAST.DeclarationRun erases their requirements to `any`.\n declaration.run(declaration.typeParameters)(\n new ArrayBuffer(0),\n declaration,\n {},\n ) as Effect.Effect<ArrayBuffer, unknown, never>,\n {\n onSuccess: () => v.bytes(),\n onFailure: () =>\n new UnsupportedSchemaTypeError({\n schemaType: declaration._tag,\n }),\n },\n ),\n ),\n Match.tag(\"Suspend\", () => Effect.succeed(v.any())),\n Match.tag(\n \"UniqueSymbol\",\n \"Symbol\",\n \"Undefined\",\n \"Void\",\n \"Never\",\n \"Enum\",\n \"TemplateLiteral\",\n \"ObjectKeyword\",\n () =>\n Effect.fail(\n new UnsupportedSchemaTypeError({\n schemaType: ast._tag,\n }),\n ),\n ),\n Match.exhaustive,\n );\n\nconst handleUnion = (\n { types }: SchemaAST.Union,\n isOptionalPropertyOfTypeLiteral: boolean,\n) => handleUnionTypes(types, isOptionalPropertyOfTypeLiteral);\n\nconst handleUnionTypes = Effect.fnUntraced(function* (\n types: SchemaAST.Union[\"types\"],\n isOptionalPropertyOfTypeLiteral: boolean,\n) {\n const members = isOptionalPropertyOfTypeLiteral\n ? Array.filter(types, Predicate.not(SchemaAST.isUndefined))\n : types;\n\n const [firstValidator, secondValidator, ...restValidators] =\n yield* Effect.all(Array.map(members, (type) => compileAst(type)));\n\n if (firstValidator === undefined) {\n return yield* new EmptyUnionIsNotSupportedError();\n } else if (secondValidator === undefined) {\n return firstValidator;\n } else {\n return v.union(firstValidator, secondValidator, ...restValidators);\n }\n});\n\nconst handleObjects = (objectsAst: SchemaAST.Objects) =>\n pipe(\n objectsAst.indexSignatures,\n Array.head,\n Option.match({\n onNone: () => Effect.map(handlePropertySignatures(objectsAst), v.object),\n onSome: ({ parameter, type }) =>\n pipe(\n objectsAst.propertySignatures,\n Array.head,\n Option.match({\n onNone: () =>\n Effect.map(\n Effect.all({\n parameter_: compileAst(parameter),\n type_: compileAst(type),\n }),\n ({ parameter_, type_ }) => v.record(parameter_, type_),\n ),\n onSome: () =>\n Effect.fail(\n new MixedIndexAndPropertySignaturesAreNotSupportedError(),\n ),\n }),\n ),\n }),\n );\n\nconst handleArrays = ({ elements, rest }: SchemaAST.Arrays) =>\n handleArrayElements(elements, rest);\n\nconst handleArrayElements = Effect.fnUntraced(function* (\n elements: SchemaAST.Arrays[\"elements\"],\n rest: SchemaAST.Arrays[\"rest\"],\n) {\n const [f, s, ...r] = elements;\n\n const elementToValidator = (element: SchemaAST.AST) =>\n SchemaAST.isOptional(element)\n ? Effect.fail(new OptionalTupleElementsAreNotSupportedError())\n : compileAst(element);\n\n const arrayItemsValidator = yield* f === undefined\n ? pipe(\n rest,\n Array.head,\n Option.match({\n onNone: () => Effect.fail(new EmptyTupleIsNotSupportedError()),\n onSome: (type) => compileAst(type),\n }),\n )\n : s === undefined\n ? elementToValidator(f)\n : Effect.gen(function* () {\n const firstValidator = yield* elementToValidator(f);\n const secondValidator = yield* elementToValidator(s);\n const restValidators = yield* Effect.forEach(r, elementToValidator);\n\n return v.union(firstValidator, secondValidator, ...restValidators);\n });\n\n return v.array(arrayItemsValidator);\n});\n\nconst handlePropertySignatures = (objectsAst: SchemaAST.Objects) =>\n pipe(\n objectsAst.propertySignatures,\n Effect.forEach(({ type, name }) => {\n const isOptional = SchemaAST.isOptional(type);\n if (String.isString(name)) {\n // Somehow, somewhere, keys of type number are being coerced to strings…\n return Option.match(Number.parse(name), {\n onNone: () =>\n Effect.gen(function* () {\n const validator = yield* compileAst(type, isOptional);\n\n return {\n propertyName: name,\n validator: isOptional ? v.optional(validator) : validator,\n };\n }),\n onSome: (number) =>\n Effect.fail(\n new UnsupportedPropertySignatureKeyTypeError({\n propertyKey: number,\n }),\n ),\n });\n } else {\n return Effect.fail(\n new UnsupportedPropertySignatureKeyTypeError({ propertyKey: name }),\n );\n }\n }),\n Effect.andThen((propertyNamesWithValidators) =>\n pipe(\n propertyNamesWithValidators,\n Array.reduce(\n {} as Record<string, Validator<any, any, any>>,\n (acc, { propertyName, validator }) => ({\n [propertyName]: validator,\n ...acc,\n }),\n ),\n Effect.succeed,\n ),\n ),\n );\n\n// Errors\n\nexport class TopLevelMustBeObjectError extends Data.TaggedError(\n \"TopLevelMustBeObjectError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Top level schema must be an object\";\n }\n /* v8 ignore stop */\n}\n\nexport class TopLevelMustBeObjectOrUnionError extends Data.TaggedError(\n \"TopLevelMustBeObjectOrUnionError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Top level schema must be an object or a union\";\n }\n /* v8 ignore stop */\n}\n\nexport class UnsupportedPropertySignatureKeyTypeError extends Data.TaggedError(\n \"UnsupportedPropertySignatureKeyTypeError\",\n)<{\n readonly propertyKey: number | symbol;\n}> {\n /* v8 ignore start */\n override get message() {\n return `Unsupported property signature '${this.propertyKey.toString()}'. Property is of type '${typeof this.propertyKey}' but only 'string' properties are supported.`;\n }\n /* v8 ignore stop */\n}\n\nexport class EmptyTupleIsNotSupportedError extends Data.TaggedError(\n \"EmptyTupleIsNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Tuple must have at least one element\";\n }\n /* v8 ignore stop */\n}\n\nexport class EmptyUnionIsNotSupportedError extends Data.TaggedError(\n \"EmptyUnionIsNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Union must have at least one member that compiles to a validator\";\n }\n /* v8 ignore stop */\n}\n\nexport class UnsupportedSchemaTypeError extends Data.TaggedError(\n \"UnsupportedSchemaTypeError\",\n)<{\n readonly schemaType: SchemaAST.AST[\"_tag\"];\n}> {\n /* v8 ignore start */\n override get message() {\n return `Unsupported schema type '${this.schemaType}'`;\n }\n /* v8 ignore stop */\n}\n\nexport class IndexSignaturesAreNotSupportedError extends Data.TaggedError(\n \"IndexSignaturesAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Index signatures are not supported\";\n }\n /* v8 ignore stop */\n}\n\nexport class MixedIndexAndPropertySignaturesAreNotSupportedError extends Data.TaggedError(\n \"MixedIndexAndPropertySignaturesAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Mixed index and property signatures are not supported\";\n }\n /* v8 ignore stop */\n}\n\nexport class OptionalTupleElementsAreNotSupportedError extends Data.TaggedError(\n \"OptionalTupleElementsAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Optional tuple elements are not supported\";\n }\n /* v8 ignore stop */\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,qBACX,eACuB;CACvB,MAAM,MAAM,OAAO,UAAU,UAAU,CAAC,CAAC;CAEzC,OAAO,KACL,KACA,MAAM,OACN,MAAM,IAAI,YAAY,eACpB,MAAM,qBAAqB,WAAW,eAAe,IACjD,yBAAyB,U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;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,2CAAb,cAA8D,KAAK,YACjE,0CACF,CAAC,CAEE;;CAED,IAAa,UAAU;EACrB,OAAO,mCAAmC,KAAK,YAAY,SAAS,EAAE,0BAA0B,OAAO,KAAK,YAAY;CAC1H;AAEF;AAEA,IAAa,gCAAb,cAAmD,KAAK,YACtD,+BACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,gCAAb,cAAmD,KAAK,YACtD,+BACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,6BAAb,cAAgD,KAAK,YACnD,4BACF,CAAC,CAEE;;CAED,IAAa,UAAU;EACrB,OAAO,4BAA4B,KAAK,WAAW;CACrD;AAEF;AAEA,IAAa,sCAAb,cAAyD,KAAK,YAC5D,qCACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,sDAAb,cAAyE,KAAK,YAC5E,qDACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,4CAAb,cAA+D,KAAK,YAClE,2CACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF"}
package/dist/Spec.d.ts CHANGED
@@ -1,27 +1,31 @@
1
+ import * as Record from "effect/Record";
2
+ import * as Struct from "effect/Struct";
1
3
  import * as GroupSpec from "./GroupSpec";
2
- export declare const TypeId = "@confect/core/Spec";
4
+ export declare const TypeId = "~@confect/core/Spec";
3
5
  export type TypeId = typeof TypeId;
4
6
  export declare const isSpec: (u: unknown) => u is AnyWithProps;
5
7
  /**
6
8
  * A Confect spec: a flat container of function groups. Groups may be of any
7
- * runtime — a group built with `GroupSpec.makeNode()` (a Node action group) sits
9
+ * runtime—a group built with `GroupSpec.makeNode()` (a Node action group) sits
8
10
  * alongside `GroupSpec.make()` groups in the same namespace. The runtime of a
9
11
  * group lives on the group itself (`GroupSpec.runtime`) and on each function's
10
12
  * `RuntimeAndFunctionType`; the spec does not carry a runtime of its own.
11
13
  */
12
- export interface Spec<Groups_ extends GroupSpec.AnyWithProps = never> {
13
- readonly [TypeId]: TypeId;
14
- readonly groups: {
15
- [GroupName in GroupSpec.Name<Groups_>]: GroupSpec.WithName<Groups_, GroupName>;
16
- };
17
- add<Group extends GroupSpec.AnyWithProps>(group: Group): Spec<Groups_ | Group>;
18
- addAt<const Name extends string, Group extends GroupSpec.AnyWithProps>(name: Name, group: Group): Spec<Groups_ | GroupSpec.NamedAt<Group, Name>>;
14
+ export interface Spec<Groups_ extends Record.ReadonlyRecord<string, GroupSpec.AnyWithProps> = {}> {
15
+ readonly [TypeId]: Readonly<Groups_>;
16
+ add<Group extends GroupSpec.AnyWithProps>(group: Group): Spec<Struct.Assign<Groups_, Record.ReadonlyRecord<GroupSpec.Name<Group>, Group>>>;
17
+ addAt<const Name extends string, Group extends GroupSpec.AnyWithProps>(name: Name, group: Group): Spec<Struct.Assign<Groups_, Record.ReadonlyRecord<Name, GroupSpec.NamedAt<Group, Name>>>>;
19
18
  }
20
19
  export interface Any {
21
- readonly [TypeId]: TypeId;
20
+ readonly [TypeId]: unknown;
22
21
  }
23
- export interface AnyWithProps extends Spec<GroupSpec.AnyWithProps> {
22
+ export interface AnyWithProps extends Any {
23
+ readonly [TypeId]: Record.ReadonlyRecord<string, GroupSpec.AnyWithProps>;
24
24
  }
25
- export type Groups<Spec_ extends AnyWithProps> = Spec_["groups"][keyof Spec_["groups"]];
25
+ export type Groups<Spec_ extends AnyWithProps> = Spec_[TypeId][keyof Spec_[TypeId]];
26
+ /**
27
+ * The group record stored by a spec, with its precise member types.
28
+ */
29
+ export declare const groups: <Spec_ extends AnyWithProps>(self: Spec_) => Spec_[TypeId];
26
30
  export declare const make: () => Spec;
27
31
  //# sourceMappingURL=Spec.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Spec.d.ts","sour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CAAC,cAAc,CAAC,MAAM,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;CAC1E;AAED,MAAM,MAAM,MAAM,CAAC,KAAK,SAAS,YAAY,IAC3C,KAAK,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;AAErC;;GAEG;AACH,eAAO,MAAM,MAAM,GAAI,KAAK,SAAS,YAAY,QACzC,KAAK,KACV,KAAK,CAAC,MAAM,CAAiB,CAAC;AA6BjC,eAAO,MAAM,IAAI,QAAO,IAAsB,CAAC"}
package/dist/Spec.js CHANGED
@@ -2,26 +2,31 @@ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
2
  import { withName } from "./GroupSpec.js";
3
3
  import * as Predicate from "effect/Predicate";
4
4
  import * as Record from "effect/Record";
5
+ import * as Struct from "effect/Struct";
5
6
  //#region src/Spec.ts
6
7
  var Spec_exports = /* @__PURE__ */ __exportAll({
7
8
  TypeId: () => TypeId,
9
+ groups: () => groups,
8
10
  isSpec: () => isSpec,
9
11
  make: () => make
10
12
  });
11
- const TypeId = "@confect/core/Spec";
13
+ const TypeId = "~@confect/core/Spec";
12
14
  const isSpec = (u) => Predicate.hasProperty(u, TypeId);
13
- const Proto = {
14
- [TypeId]: TypeId,
15
+ /**
16
+ * The group record stored by a spec, with its precise member types.
17
+ */
18
+ const groups = (self) => self[TypeId];
19
+ const makeRecord = (record) => ({
20
+ [TypeId]: record,
15
21
  add(group) {
16
- return makeProto({ groups: Record.set(this.groups, group.name, group) });
22
+ return makeRecord(Struct.assign(record, Record.singleton(group.name, group)));
17
23
  },
18
24
  addAt(name, group) {
19
- return makeProto({ groups: Record.set(this.groups, name, withName(name, group)) });
25
+ return makeRecord(Struct.assign(record, Record.singleton(name, withName(name, group))));
20
26
  }
21
- };
22
- const makeProto = ({ groups }) => Object.assign(Object.create(Proto), { groups });
23
- const make = () => makeProto({ groups: {} });
27
+ });
28
+ const make = () => makeRecord({});
24
29
  //#endregion
25
- export { Spec_exports, TypeId, isSpec, make };
30
+ export { Spec_exports, TypeId, groups, isSpec, make };
26
31
 
27
32
  //# sourceMappingURL=Spec.js.map
package/dist/Spec.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Spec.js","names":["GroupSpec.withName"],"sources":["../src/Spec.ts"],"sourcesContent":["import * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as GroupSpec from \"./GroupSpec\";\n\nexport const TypeId = \"@confect/core/Spec\";\nexport type TypeId = typeof TypeId;\n\nexport const isSpec = (u: unknown): u is AnyWithProps =>\n Predicate.hasProperty(u, TypeId);\n\n/**\n * A Confect spec: a flat container of function groups. Groups may be of any\n * runtime — a group built with `GroupSpec.makeNode()` (a Node action group) sits\n * alongside `GroupSpec.make()` groups in the same namespace. The runtime of a\n * group lives on the group itself (`GroupSpec.runtime`) and on each function's\n * `RuntimeAndFunctionType`; the spec does not carry a runtime of its own.\n */\nexport interface Spec<Groups_ extends GroupSpec.AnyWithProps = never> {\n readonly [TypeId]: TypeId;\n readonly groups: {\n [GroupName in GroupSpec.Name<Groups_>]: GroupSpec.WithName<\n Groups_,\n GroupName\n >;\n };\n\n add<Group extends GroupSpec.AnyWithProps>(\n group: Group,\n ): Spec<Groups_ | Group>;\n\n addAt<const Name extends string, Group extends GroupSpec.AnyWithProps>(\n name: Name,\n group: Group,\n ): Spec<Groups_ | GroupSpec.NamedAt<Group, Name>>;\n}\n\nexport interface Any {\n readonly [TypeId]: TypeId;\n}\n\nexport interface AnyWithProps extends Spec<GroupSpec.AnyWithProps> {}\n\nexport type Groups<Spec_ extends AnyWithProps> =\n Spec_[\"groups\"][keyof Spec_[\"groups\"]];\n\nconst Proto = {\n [TypeId]: TypeId,\n\n add<Group extends GroupSpec.AnyWithProps>(this: AnyWithProps, group: Group) {\n return makeProto({\n groups: Record.set(this.groups, group.name, group),\n });\n },\n\n addAt<Group extends GroupSpec.AnyWithProps>(\n this: AnyWithProps,\n name: string,\n group: Group,\n ) {\n return makeProto({\n groups: Record.set(this.groups, name, GroupSpec.withName(name, group)),\n });\n },\n};\n\nconst makeProto = <Groups_ extends GroupSpec.AnyWithProps>({\n groups,\n}: {\n groups: Record.ReadonlyRecord<string, Groups_>;\n}): Spec<Groups_> =>\n Object.assign(Object.create(Proto), {\n groups,\n });\n\nexport const make = (): Spec => makeProto({ groups: {} });\n"],"mappings":";;;;;;;;;;AAIA,MAAa,SAAS;AAGtB,MAAa,UAAU,MACrB,UAAU,YAAY,GAAG,MAAM;AAqCjC,MAAM,QAAQ;EACX,SAAS;CAEV,IAA8D,OAAc;EAC1E,OAAO,UAAU,EACf,QAAQ,OAAO,IAAI,KAAK,QAAQ,MAAM,MAAM,KAAK,EACnD,CAAC;CACH;CAEA,MAEE,MACA,OACA;EACA,OAAO,UAAU,EACf,QAAQ,OAAO,IAAI,KAAK,QAAQ,MAAMA,SAAmB,MAAM,KAAK,CAAC,EACvE,CAAC;CACH;AACF;AAEA,MAAM,aAAqD,EACzD,aAIA,OAAO,OAAO,OAAO,OAAO,KAAK,GAAG,EAClC,OACF,CAAC;AAEH,MAAa,aAAmB,UAAU,EAAE,QAAQ,CAAC,EAAE,CAAC"}
1
+ {"version":3,"file":"Spec.js","names":["GroupSpec.withName"],"sources":["../src/Spec.ts"],"sourcesContent":["import * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Struct from \"effect/Struct\";\nimport * as GroupSpec from \"./GroupSpec\";\n\nexport const TypeId = \"~@confect/core/Spec\";\nexport type TypeId = typeof TypeId;\n\nexport const isSpec = (u: unknown): u is AnyWithProps =>\n Predicate.hasProperty(u, TypeId);\n\n/**\n * A Confect spec: a flat container of function groups. Groups may be of any\n * runtime—a group built with `GroupSpec.makeNode()` (a Node action group) sits\n * alongside `GroupSpec.make()` groups in the same namespace. The runtime of a\n * group lives on the group itself (`GroupSpec.runtime`) and on each function's\n * `RuntimeAndFunctionType`; the spec does not carry a runtime of its own.\n */\nexport interface Spec<\n Groups_ extends Record.ReadonlyRecord<string, GroupSpec.AnyWithProps> = {},\n> {\n readonly [TypeId]: Readonly<Groups_>;\n\n add<Group extends GroupSpec.AnyWithProps>(\n group: Group,\n ): Spec<\n Struct.Assign<Groups_, Record.ReadonlyRecord<GroupSpec.Name<Group>, Group>>\n >;\n\n addAt<const Name extends string, Group extends GroupSpec.AnyWithProps>(\n name: Name,\n group: Group,\n ): Spec<\n Struct.Assign<\n Groups_,\n Record.ReadonlyRecord<Name, GroupSpec.NamedAt<Group, Name>>\n >\n >;\n}\n\nexport interface Any {\n readonly [TypeId]: unknown;\n}\n\nexport interface AnyWithProps extends Any {\n readonly [TypeId]: Record.ReadonlyRecord<string, GroupSpec.AnyWithProps>;\n}\n\nexport type Groups<Spec_ extends AnyWithProps> =\n Spec_[TypeId][keyof Spec_[TypeId]];\n\n/**\n * The group record stored by a spec, with its precise member types.\n */\nexport const groups = <Spec_ extends AnyWithProps>(\n self: Spec_,\n): Spec_[TypeId] => self[TypeId];\n\nconst makeRecord = <\n Groups_ extends Record.ReadonlyRecord<string, GroupSpec.AnyWithProps>,\n>(\n record: Groups_,\n): Spec<Groups_> => ({\n [TypeId]: record,\n add<Group extends GroupSpec.AnyWithProps>(group: Group) {\n return makeRecord(\n Struct.assign(\n record,\n Record.singleton<GroupSpec.Name<Group>, Group>(group.name, group),\n ),\n );\n },\n addAt<const Name extends string, Group extends GroupSpec.AnyWithProps>(\n name: Name,\n group: Group,\n ) {\n return makeRecord(\n Struct.assign(\n record,\n Record.singleton(name, GroupSpec.withName(name, group)),\n ),\n );\n },\n});\n\nexport const make = (): Spec => makeRecord({});\n"],"mappings":";;;;;;;;;;;;AAKA,MAAa,SAAS;AAGtB,MAAa,UAAU,MACrB,UAAU,YAAY,GAAG,MAAM;;;;AA6CjC,MAAa,UACX,SACkB,KAAK;AAEzB,MAAM,cAGJ,YACmB;EAClB,SAAS;CACV,IAA0C,OAAc;EACtD,OAAO,WACL,OAAO,OACL,QACA,OAAO,UAAwC,MAAM,MAAM,KAAK,CAClE,CACF;CACF;CACA,MACE,MACA,OACA;EACA,OAAO,WACL,OAAO,OACL,QACA,OAAO,UAAU,MAAMA,SAAmB,MAAM,KAAK,CAAC,CACxD,CACF;CACF;AACF;AAEA,MAAa,aAAmB,WAAW,CAAC,CAAC"}
@@ -2,11 +2,12 @@ import type { IdField, SystemFields as NonIdSystemFields } from "convex/server";
2
2
  import * as Schema from "effect/Schema";
3
3
  import * as Struct from "effect/Struct";
4
4
  /**
5
- * Produces a schema for Convex system fields. In Confect, system fields include `_id`.
5
+ * Produces a schema for Convex system fields. In Confect, system fields include
6
+ * `_id`.
6
7
  */
7
8
  export declare const SystemFields: <TableName extends string>(tableName: TableName) => Schema.Struct<{
8
9
  readonly _id: Schema.Codec<import("convex/values").GenericId<TableName>, import("convex/values").GenericId<TableName>, never, never>;
9
- readonly _creationTime: Schema.Number;
10
+ readonly _creationTime: Schema.Finite;
10
11
  }>;
11
12
  /**
12
13
  * The field map added to a table schema, derived from {@link SystemFields} so it
@@ -16,11 +17,11 @@ type SystemFieldsFor<TableName extends string> = ReturnType<typeof SystemFields<
16
17
  /**
17
18
  * Extend a table schema with Convex system fields.
18
19
  *
19
- * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`
20
- * has them distributed across its members, preserving the schema's
21
- * `Struct`/`Union` structure. Any other object-shaped schema — one built with
22
- * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema
23
- * — is extended at the AST level: every object node in its encoding chain
20
+ * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union` has
21
+ * them distributed across its members, preserving the schema's `Struct`/`Union`
22
+ * structure. Any other object-shaped schema—one built with
23
+ * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended
24
+ * schema—is extended at the AST level: every object node in its encoding chain
24
25
  * gains the system fields, and each transformation is wrapped so the fields
25
26
  * bypass the user-defined getters. Schemas that do not resolve to an object
26
27
  * shape at every step (such as `Schema.Class`, whose decoded values are class
@@ -32,9 +33,9 @@ type SystemFieldsFor<TableName extends string> = ReturnType<typeof SystemFields<
32
33
  */
33
34
  export declare const extendWithSystemFields: <TableName extends string, TableSchema extends Schema.Codec<any, any>>(tableName: TableName, schema: TableSchema) => ExtendWithSystemFields<TableName, TableSchema>;
34
35
  /**
35
- * Applies the system fields to a single struct, mirroring `Schema.fieldsAssign`.
36
- * Any other (already-extended or opaque) schema falls back to a `Codec` carrying
37
- * the system-field document shape.
36
+ * Applies the system fields to a single struct, mirroring
37
+ * `Schema.fieldsAssign`. Any other (already-extended or opaque) schema falls
38
+ * back to a `Codec` carrying the system-field document shape.
38
39
  */
39
40
  type ApplySystemFields<TableName extends string, S> = S extends Schema.Struct<infer Fields extends Schema.Struct.Fields> ? Schema.Struct<Struct.Simplify<Struct.Assign<Fields, SystemFieldsFor<TableName>>>> : S extends Schema.Codec<infer Type, infer Encoded> ? Schema.Codec<WithSystemFields<TableName, Type>, WithSystemFields<TableName, Encoded>> : never;
40
41
  /**
@@ -43,17 +44,17 @@ type ApplySystemFields<TableName extends string, S> = S extends Schema.Struct<in
43
44
  * This mirrors the runtime {@link extendWithSystemFields}: a `Struct` gains the
44
45
  * system fields directly (matching `Schema.fieldsAssign`), and a `Union` has
45
46
  * them distributed across its members (matching
46
- * `union.mapMembers(Tuple.map(Schema.fieldsAssign(...)))`). The `Struct`/`Union`
47
- * structure is preserved rather than collapsed to a bare `Codec`; any other
48
- * schema falls back to a `Codec` carrying the system-field document shape,
49
- * matching the runtime's AST-level extension.
47
+ * `union.mapMembers(Tuple.map(Schema.fieldsAssign(...)))`). The
48
+ * `Struct`/`Union` structure is preserved rather than collapsed to a bare
49
+ * `Codec`; any other schema falls back to a `Codec` carrying the system-field
50
+ * document shape, matching the runtime's AST-level extension.
50
51
  */
51
52
  export type ExtendWithSystemFields<TableName extends string, TableSchema extends Schema.Top> = TableSchema extends Schema.Union<infer Members extends ReadonlyArray<Schema.Top>> ? Schema.Union<Struct.Simplify<Readonly<{
52
53
  [K in keyof Members]: ExtendWithSystemFields<TableName, Members[K]>;
53
54
  }>>> : ApplySystemFields<TableName, TableSchema>;
54
55
  /**
55
56
  * The decoded/encoded document shape: a table's fields plus Convex's system
56
- * fields. Deliberately a bare intersection (no `Expand`/`Simplify`) — flattening
57
+ * fields. Deliberately a bare intersection (no `Expand`/`Simplify`)—flattening
57
58
  * it with a homomorphic mapped type collapses to `{ [x: string]: any }` when
58
59
  * `Document` is still an unresolved generic, which breaks structural
59
60
  * comparability in the database reader/writer plumbing.
@@ -1 +1 @@
1
- {"version":3,"file":"SystemFields.d.ts","sourceRoot":"","sources":["../src/SystemFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAOhF,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,SAAS,SAAS,MAAM,EAAE,WAAW,SAAS;;;EAIvE,CAAC;AAEL;;;GAGG;AACH,KAAK,eAAe,CAAC,SAAS,SAAS,MAAM,IAAI,UAAU,CACzD,OAAO,YAAY,CAAC,SAAS,CAAC,CAC/B,CAAC,QAAQ,CAAC,CAAC;AA4HZ;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,sBAAsB,GACjC,SAAS,SAAS,MAAM,EACxB,WAAW,SAAS,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,EAE1C,WAAW,SAAS,EACpB,QAAQ,WAAW,KAClB,sBAAsB,CAAC,SAAS,EAAE,WAAW,CA0C/C,CAAC;AAEF;;;;GAIG;AACH,KAAK,iBAAiB,CAAC,SAAS,SAAS,MAAM,EAAE,CAAC,IAChD,CAAC,SAAS,MAAM,CAAC,MAAM,CAAC,MAAM,MAAM,SAAS,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,GAC9D,MAAM,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AAM,OAAO,GAAG,sBAAsB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;CACpE,CAAC,CACH,CACF,GACD,iBAAiB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAEhD;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,CAC1B,SAAS,SAAS,MAAM,EACxB,QAAQ,IACN,QAAQ,SAAS,OAAO,GACxB,OAAO,CAAC,SAAS,CAAC,GAAG,iBAAiB,GAAG,QAAQ,GACjD,KAAK,CAAC"}
@@ -1,27 +1,28 @@
1
1
  import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
2
  import { GenericId } from "./GenericId.js";
3
+ import * as Schema from "effect/Schema";
3
4
  import * as Predicate from "effect/Predicate";
4
5
  import * as Option from "effect/Option";
5
- import * as Schema from "effect/Schema";
6
6
  import * as SchemaAST from "effect/SchemaAST";
7
7
  import * as Record from "effect/Record";
8
8
  import * as Effect from "effect/Effect";
9
9
  import { pipe } from "effect/Function";
10
+ import * as Struct from "effect/Struct";
10
11
  import * as Array from "effect/Array";
11
12
  import * as SchemaGetter from "effect/SchemaGetter";
12
13
  import * as SchemaTransformation from "effect/SchemaTransformation";
13
- import * as Struct from "effect/Struct";
14
14
  //#region src/SystemFields.ts
15
15
  var SystemFields_exports = /* @__PURE__ */ __exportAll({
16
16
  SystemFields: () => SystemFields,
17
17
  extendWithSystemFields: () => extendWithSystemFields
18
18
  });
19
19
  /**
20
- * Produces a schema for Convex system fields. In Confect, system fields include `_id`.
20
+ * Produces a schema for Convex system fields. In Confect, system fields include
21
+ * `_id`.
21
22
  */
22
23
  const SystemFields = (tableName) => Schema.Struct({
23
24
  _id: GenericId(tableName),
24
- _creationTime: Schema.Number
25
+ _creationTime: Schema.Finite
25
26
  });
26
27
  /**
27
28
  * The system field names, derived from {@link SystemFields} so they stay in
@@ -43,10 +44,10 @@ const splitSystemFields = (input) => {
43
44
  * output. Transformations construct fresh objects, so without this the system
44
45
  * fields would be dropped at every transformation step.
45
46
  */
46
- const wrapGetter = (getter) => new SchemaGetter.Getter((input, options) => {
47
- if (Option.isNone(input) || !Predicate.isObject(input.value)) return getter.run(input, options);
47
+ const wrapGetter = (getter) => SchemaGetter.transformOptionalEffect((input, options) => {
48
+ if (Option.isNone(input) || !Predicate.isObject(input.value)) return SchemaGetter.run(getter, input, options);
48
49
  const { system, rest } = splitSystemFields(input.value);
49
- return getter.run(Option.some(rest), options).pipe(Effect.map(Option.map((output) => Predicate.isObject(output) ? Struct.assign(output, system) : output)));
50
+ return SchemaGetter.run(getter, Option.some(rest), options).pipe(Effect.map(Option.map((output) => Predicate.isObject(output) ? Struct.assign(output, system) : output)));
50
51
  });
51
52
  const wrapTransformation = (transformation) => {
52
53
  if (!SchemaTransformation.isTransformation(transformation)) throw new Error("Cannot extend a table schema that uses decoding/encoding middleware with system fields");
@@ -54,13 +55,13 @@ const wrapTransformation = (transformation) => {
54
55
  };
55
56
  /**
56
57
  * Builds an AST walker that adds the given system-field property signatures to
57
- * every object node of a schema's AST — including each step of its encoding
58
- * chain — wrapping transformations so the fields survive them.
58
+ * every object node of a schema's AST—including each step of its encoding
59
+ * chain—wrapping transformations so the fields survive them.
59
60
  */
60
61
  const makeExtendAst = (systemPropertySignatures) => {
61
62
  const extendEncoding = (encoding) => Array.map(encoding, (link) => new SchemaAST.Link(extendAst(link.to), wrapTransformation(link.transformation)));
62
63
  const extendAst = (ast) => {
63
- if (SchemaAST.isUnion(ast)) return new SchemaAST.Union(Array.map(ast.types, extendAst), ast.mode, ast.annotations, ast.checks, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context, ast.encodingChecks);
64
+ if (SchemaAST.isUnion(ast)) return new SchemaAST.Union(Array.map(ast.types, extendAst), ast.options, ast.annotations, ast.checks, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context, ast.encodingChecks);
64
65
  if (SchemaAST.isSuspend(ast)) return new SchemaAST.Suspend(() => extendAst(ast.thunk()), ast.annotations, void 0, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context);
65
66
  if (SchemaAST.isObjects(ast)) return new SchemaAST.Objects(Array.appendAll(ast.propertySignatures, systemPropertySignatures), ast.indexSignatures, ast.annotations, ast.checks, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context, ast.encodingChecks);
66
67
  throw new Error(ast._tag === "Declaration" ? "Cannot extend a `Declaration` schema (such as a `Schema.Class`) with system fields: its decoded values are constructed instances, which cannot gain extra fields. Use a plain `Schema.Struct`, or transform to one with `Schema.decodeTo`." : `Cannot extend a \`${ast._tag}\` schema node with system fields: a table schema must resolve to an object shape at every step of its encoding.`);
@@ -70,11 +71,11 @@ const makeExtendAst = (systemPropertySignatures) => {
70
71
  /**
71
72
  * Extend a table schema with Convex system fields.
72
73
  *
73
- * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`
74
- * has them distributed across its members, preserving the schema's
75
- * `Struct`/`Union` structure. Any other object-shaped schema — one built with
76
- * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema
77
- * — is extended at the AST level: every object node in its encoding chain
74
+ * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union` has
75
+ * them distributed across its members, preserving the schema's `Struct`/`Union`
76
+ * structure. Any other object-shaped schema—one built with
77
+ * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended
78
+ * schema—is extended at the AST level: every object node in its encoding chain
78
79
  * gains the system fields, and each transformation is wrapped so the fields
79
80
  * bypass the user-defined getters. Schemas that do not resolve to an object
80
81
  * shape at every step (such as `Schema.Class`, whose decoded values are class
@@ -1 +1 @@
1
- {"version":3,"file":"SystemFields.js","names":["GenericId.GenericId"],"sources":["../src/SystemFields.ts"],"sourcesContent":["import type { IdField, SystemFields as NonIdSystemFields } from \"convex/server\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Struct from \"effect/Struct\";\nimport * as GenericId from \"./GenericId\";\n\n/**\n * Produces a schema for Convex system fields. In Confect, system fields include `_id`.\n */\nexport const SystemFields = <TableName extends string>(tableName: TableName) =>\n Schema.Struct({\n _id: GenericId.GenericId(tableName),\n _creationTime: Schema.Number,\n });\n\n/**\n * The field map added to a table schema, derived from {@link SystemFields} so it\n * stays in lockstep with the runtime schema.\n */\ntype SystemFieldsFor<TableName extends string> = ReturnType<\n typeof SystemFields<TableName>\n>[\"fields\"];\n\n/**\n * The system field names, derived from {@link SystemFields} so they stay in\n * lockstep with the schema.\n */\nconst systemFieldNames: ReadonlyArray<string> = Record.keys(\n SystemFields(\"\").fields,\n);\n\nconst isSystemFieldKey = (key: string | symbol): key is string =>\n Predicate.isString(key) && Array.contains(systemFieldNames, key);\n\nconst splitSystemFields = (input: { [key: PropertyKey]: unknown }) => {\n const keys = Reflect.ownKeys(input);\n const pick = (pickedKeys: ReadonlyArray<string | symbol>) =>\n Record.fromEntries(\n Array.map(pickedKeys, (key) => [key, input[key]] as const),\n );\n return {\n system: pick(Array.filter(keys, isSystemFieldKey)),\n rest: pick(Array.filter(keys, Predicate.not(isSystemFieldKey))),\n };\n};\n\n/**\n * Wraps a transformation getter so the system fields bypass it: they are split\n * off the input before the user-defined getter runs and merged back into its\n * output. Transformations construct fresh objects, so without this the system\n * fields would be dropped at every transformation step.\n */\nconst wrapGetter = (\n getter: SchemaGetter.Getter<any, any, any>,\n): SchemaGetter.Getter<any, any, any> =>\n new SchemaGetter.Getter((input, options) => {\n if (Option.isNone(input) || !Predicate.isObject(input.value)) {\n return getter.run(input, options);\n }\n const { system, rest } = splitSystemFields(input.value);\n return getter\n .run(Option.some(rest), options)\n .pipe(\n Effect.map(\n Option.map((output) =>\n Predicate.isObject(output) ? Struct.assign(output, system) : output,\n ),\n ),\n );\n });\n\nconst wrapTransformation = (\n transformation: SchemaAST.Link[\"transformation\"],\n): SchemaTransformation.Transformation<any, any, any, any> => {\n if (!SchemaTransformation.isTransformation(transformation)) {\n throw new Error(\n \"Cannot extend a table schema that uses decoding/encoding middleware with system fields\",\n );\n }\n return new SchemaTransformation.Transformation(\n wrapGetter(transformation.decode),\n wrapGetter(transformation.encode),\n );\n};\n\n/**\n * Builds an AST walker that adds the given system-field property signatures to\n * every object node of a schema's AST — including each step of its encoding\n * chain — wrapping transformations so the fields survive them.\n */\nconst makeExtendAst = (\n systemPropertySignatures: ReadonlyArray<SchemaAST.PropertySignature>,\n) => {\n const extendEncoding = (encoding: SchemaAST.Encoding): SchemaAST.Encoding =>\n Array.map(\n encoding,\n (link) =>\n new SchemaAST.Link(\n extendAst(link.to),\n wrapTransformation(link.transformation),\n ),\n );\n\n const extendAst = (ast: SchemaAST.AST): SchemaAST.AST => {\n if (SchemaAST.isUnion(ast)) {\n return new SchemaAST.Union(\n Array.map(ast.types, extendAst),\n ast.mode,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n if (SchemaAST.isSuspend(ast)) {\n return new SchemaAST.Suspend(\n () => extendAst(ast.thunk()),\n ast.annotations,\n undefined,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n );\n }\n if (SchemaAST.isObjects(ast)) {\n return new SchemaAST.Objects(\n Array.appendAll(ast.propertySignatures, systemPropertySignatures),\n ast.indexSignatures,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n throw new Error(\n ast._tag === \"Declaration\"\n ? \"Cannot extend a `Declaration` schema (such as a `Schema.Class`) with system fields: its decoded values are constructed instances, which cannot gain extra fields. Use a plain `Schema.Struct`, or transform to one with `Schema.decodeTo`.\"\n : `Cannot extend a \\`${ast._tag}\\` schema node with system fields: a table schema must resolve to an object shape at every step of its encoding.`,\n );\n };\n\n return extendAst;\n};\n\n/**\n * Extend a table schema with Convex system fields.\n *\n * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`\n * has them distributed across its members, preserving the schema's\n * `Struct`/`Union` structure. Any other object-shaped schema — one built with\n * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema\n * — is extended at the AST level: every object node in its encoding chain\n * gains the system fields, and each transformation is wrapped so the fields\n * bypass the user-defined getters. Schemas that do not resolve to an object\n * shape at every step (such as `Schema.Class`, whose decoded values are class\n * instances) are rejected with a descriptive error.\n *\n * Note that struct-level checks on an extended schema observe the value with\n * the system fields attached, and encoding an extended schema emits the system\n * fields alongside the table fields.\n */\nexport const extendWithSystemFields = <\n TableName extends string,\n TableSchema extends Schema.Codec<any, any>,\n>(\n tableName: TableName,\n schema: TableSchema,\n): ExtendWithSystemFields<TableName, TableSchema> => {\n const system = SystemFields(tableName).fields;\n\n const extendAst = makeExtendAst(\n pipe(\n system,\n Record.toEntries,\n Array.map(\n ([name, field]) => new SchemaAST.PropertySignature(name, field.ast),\n ),\n ),\n );\n\n const extend = (s: Schema.Top): Schema.Top => {\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isUnion(s.ast) &&\n Array.isArray((s as { readonly members?: unknown }).members)\n ) {\n return Schema.Union(\n Array.map(\n (s as Schema.Union<ReadonlyArray<Schema.Top>>).members,\n extend,\n ),\n );\n }\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isObjects(s.ast) &&\n typeof (s as { readonly mapFields?: unknown }).mapFields === \"function\"\n ) {\n return Schema.fieldsAssign(system)(\n s as Schema.Struct<Schema.Struct.Fields>,\n );\n }\n return Schema.make(extendAst(s.ast));\n };\n\n return extend(schema) as unknown as ExtendWithSystemFields<\n TableName,\n TableSchema\n >;\n};\n\n/**\n * Applies the system fields to a single struct, mirroring `Schema.fieldsAssign`.\n * Any other (already-extended or opaque) schema falls back to a `Codec` carrying\n * the system-field document shape.\n */\ntype ApplySystemFields<TableName extends string, S> =\n S extends Schema.Struct<infer Fields extends Schema.Struct.Fields>\n ? Schema.Struct<\n Struct.Simplify<Struct.Assign<Fields, SystemFieldsFor<TableName>>>\n >\n : S extends Schema.Codec<infer Type, infer Encoded>\n ? Schema.Codec<\n WithSystemFields<TableName, Type>,\n WithSystemFields<TableName, Encoded>\n >\n : never;\n\n/**\n * Extend a table schema with Convex system fields at the type level.\n *\n * This mirrors the runtime {@link extendWithSystemFields}: a `Struct` gains the\n * system fields directly (matching `Schema.fieldsAssign`), and a `Union` has\n * them distributed across its members (matching\n * `union.mapMembers(Tuple.map(Schema.fieldsAssign(...)))`). The `Struct`/`Union`\n * structure is preserved rather than collapsed to a bare `Codec`; any other\n * schema falls back to a `Codec` carrying the system-field document shape,\n * matching the runtime's AST-level extension.\n */\nexport type ExtendWithSystemFields<\n TableName extends string,\n TableSchema extends Schema.Top,\n> =\n TableSchema extends Schema.Union<\n infer Members extends ReadonlyArray<Schema.Top>\n >\n ? Schema.Union<\n Struct.Simplify<\n Readonly<{\n [K in keyof Members]: ExtendWithSystemFields<TableName, Members[K]>;\n }>\n >\n >\n : ApplySystemFields<TableName, TableSchema>;\n\n/**\n * The decoded/encoded document shape: a table's fields plus Convex's system\n * fields. Deliberately a bare intersection (no `Expand`/`Simplify`) — flattening\n * it with a homomorphic mapped type collapses to `{ [x: string]: any }` when\n * `Document` is still an unresolved generic, which breaks structural\n * comparability in the database reader/writer plumbing.\n */\nexport type WithSystemFields<\n TableName extends string,\n Document,\n> = Document extends unknown\n ? IdField<TableName> & NonIdSystemFields & Document\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,gBAA0C,cACrD,OAAO,OAAO;CACZ,KAAKA,UAAoB,SAAS;CAClC,eAAe,OAAO;AACxB,CAAC;;;;;AAcH,MAAM,mBAA0C,OAAO,K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,OAAO,KAAK,UAAU,EAAE,GAAG,CAAC;CACrC;CAEA,OAAO,OAAO,MAAM;AAItB"}
1
+ {"version":3,"file":"SystemFields.js","names":["GenericId.GenericId"],"sources":["../src/SystemFields.ts"],"sourcesContent":["import type { IdField, SystemFields as NonIdSystemFields } from \"convex/server\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Struct from \"effect/Struct\";\nimport * as GenericId from \"./GenericId\";\n\n/**\n * Produces a schema for Convex system fields. In Confect, system fields include\n * `_id`.\n */\nexport const SystemFields = <TableName extends string>(tableName: TableName) =>\n Schema.Struct({\n _id: GenericId.GenericId(tableName),\n _creationTime: Schema.Finite,\n });\n\n/**\n * The field map added to a table schema, derived from {@link SystemFields} so it\n * stays in lockstep with the runtime schema.\n */\ntype SystemFieldsFor<TableName extends string> = ReturnType<\n typeof SystemFields<TableName>\n>[\"fields\"];\n\n/**\n * The system field names, derived from {@link SystemFields} so they stay in\n * lockstep with the schema.\n */\nconst systemFieldNames: ReadonlyArray<string> = Record.keys(\n SystemFields(\"\").fields,\n);\n\nconst isSystemFieldKey = (key: string | symbol): key is string =>\n Predicate.isString(key) && Array.contains(systemFieldNames, key);\n\nconst splitSystemFields = (input: { [key: PropertyKey]: unknown }) => {\n const keys = Reflect.ownKeys(input);\n const pick = (pickedKeys: ReadonlyArray<string | symbol>) =>\n Record.fromEntries(\n Array.map(pickedKeys, (key) => [key, input[key]] as const),\n );\n return {\n system: pick(Array.filter(keys, isSystemFieldKey)),\n rest: pick(Array.filter(keys, Predicate.not(isSystemFieldKey))),\n };\n};\n\n/**\n * Wraps a transformation getter so the system fields bypass it: they are split\n * off the input before the user-defined getter runs and merged back into its\n * output. Transformations construct fresh objects, so without this the system\n * fields would be dropped at every transformation step.\n */\nconst wrapGetter = <R>(\n getter: SchemaGetter.Getter<any, any, R>,\n): SchemaGetter.Getter<any, any, R> =>\n SchemaGetter.transformOptionalEffect((input, options) => {\n if (Option.isNone(input) || !Predicate.isObject(input.value)) {\n return SchemaGetter.run(getter, input, options);\n }\n const { system, rest } = splitSystemFields(input.value);\n return SchemaGetter.run(getter, Option.some(rest), options).pipe(\n Effect.map(\n Option.map((output) =>\n Predicate.isObject(output) ? Struct.assign(output, system) : output,\n ),\n ),\n );\n });\n\nconst wrapTransformation = (\n transformation: SchemaAST.Link[\"transformation\"],\n): SchemaTransformation.Transformation<any, any, any, any> => {\n if (!SchemaTransformation.isTransformation(transformation)) {\n throw new Error(\n \"Cannot extend a table schema that uses decoding/encoding middleware with system fields\",\n );\n }\n return new SchemaTransformation.Transformation(\n wrapGetter(transformation.decode),\n wrapGetter(transformation.encode),\n );\n};\n\n/**\n * Builds an AST walker that adds the given system-field property signatures to\n * every object node of a schema's AST—including each step of its encoding\n * chain—wrapping transformations so the fields survive them.\n */\nconst makeExtendAst = (\n systemPropertySignatures: ReadonlyArray<SchemaAST.PropertySignature>,\n) => {\n const extendEncoding = (encoding: SchemaAST.Encoding): SchemaAST.Encoding =>\n Array.map(\n encoding,\n (link) =>\n new SchemaAST.Link(\n extendAst(link.to),\n wrapTransformation(link.transformation),\n ),\n );\n\n const extendAst = (ast: SchemaAST.AST): SchemaAST.AST => {\n if (SchemaAST.isUnion(ast)) {\n return new SchemaAST.Union(\n Array.map(ast.types, extendAst),\n ast.options,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n if (SchemaAST.isSuspend(ast)) {\n return new SchemaAST.Suspend(\n () => extendAst(ast.thunk()),\n ast.annotations,\n undefined,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n );\n }\n if (SchemaAST.isObjects(ast)) {\n return new SchemaAST.Objects(\n Array.appendAll(ast.propertySignatures, systemPropertySignatures),\n ast.indexSignatures,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n throw new Error(\n ast._tag === \"Declaration\"\n ? \"Cannot extend a `Declaration` schema (such as a `Schema.Class`) with system fields: its decoded values are constructed instances, which cannot gain extra fields. Use a plain `Schema.Struct`, or transform to one with `Schema.decodeTo`.\"\n : `Cannot extend a \\`${ast._tag}\\` schema node with system fields: a table schema must resolve to an object shape at every step of its encoding.`,\n );\n };\n\n return extendAst;\n};\n\n/**\n * Extend a table schema with Convex system fields.\n *\n * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union` has\n * them distributed across its members, preserving the schema's `Struct`/`Union`\n * structure. Any other object-shaped schema—one built with\n * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended\n * schema—is extended at the AST level: every object node in its encoding chain\n * gains the system fields, and each transformation is wrapped so the fields\n * bypass the user-defined getters. Schemas that do not resolve to an object\n * shape at every step (such as `Schema.Class`, whose decoded values are class\n * instances) are rejected with a descriptive error.\n *\n * Note that struct-level checks on an extended schema observe the value with\n * the system fields attached, and encoding an extended schema emits the system\n * fields alongside the table fields.\n */\nexport const extendWithSystemFields = <\n TableName extends string,\n TableSchema extends Schema.Codec<any, any>,\n>(\n tableName: TableName,\n schema: TableSchema,\n): ExtendWithSystemFields<TableName, TableSchema> => {\n const system = SystemFields(tableName).fields;\n\n const extendAst = makeExtendAst(\n pipe(\n system,\n Record.toEntries,\n Array.map(\n ([name, field]) => new SchemaAST.PropertySignature(name, field.ast),\n ),\n ),\n );\n\n const extend = (s: Schema.Top): Schema.Top => {\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isUnion(s.ast) &&\n Array.isArray((s as { readonly members?: unknown }).members)\n ) {\n return Schema.Union(\n Array.map(\n (s as Schema.Union<ReadonlyArray<Schema.Top>>).members,\n extend,\n ),\n );\n }\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isObjects(s.ast) &&\n typeof (s as { readonly mapFields?: unknown }).mapFields === \"function\"\n ) {\n return Schema.fieldsAssign(system)(\n s as Schema.Struct<Schema.Struct.Fields>,\n );\n }\n return Schema.make(extendAst(s.ast));\n };\n\n return extend(schema) as unknown as ExtendWithSystemFields<\n TableName,\n TableSchema\n >;\n};\n\n/**\n * Applies the system fields to a single struct, mirroring\n * `Schema.fieldsAssign`. Any other (already-extended or opaque) schema falls\n * back to a `Codec` carrying the system-field document shape.\n */\ntype ApplySystemFields<TableName extends string, S> =\n S extends Schema.Struct<infer Fields extends Schema.Struct.Fields>\n ? Schema.Struct<\n Struct.Simplify<Struct.Assign<Fields, SystemFieldsFor<TableName>>>\n >\n : S extends Schema.Codec<infer Type, infer Encoded>\n ? Schema.Codec<\n WithSystemFields<TableName, Type>,\n WithSystemFields<TableName, Encoded>\n >\n : never;\n\n/**\n * Extend a table schema with Convex system fields at the type level.\n *\n * This mirrors the runtime {@link extendWithSystemFields}: a `Struct` gains the\n * system fields directly (matching `Schema.fieldsAssign`), and a `Union` has\n * them distributed across its members (matching\n * `union.mapMembers(Tuple.map(Schema.fieldsAssign(...)))`). The\n * `Struct`/`Union` structure is preserved rather than collapsed to a bare\n * `Codec`; any other schema falls back to a `Codec` carrying the system-field\n * document shape, matching the runtime's AST-level extension.\n */\nexport type ExtendWithSystemFields<\n TableName extends string,\n TableSchema extends Schema.Top,\n> =\n TableSchema extends Schema.Union<\n infer Members extends ReadonlyArray<Schema.Top>\n >\n ? Schema.Union<\n Struct.Simplify<\n Readonly<{\n [K in keyof Members]: ExtendWithSystemFields<TableName, Members[K]>;\n }>\n >\n >\n : ApplySystemFields<TableName, TableSchema>;\n\n/**\n * The decoded/encoded document shape: a table's fields plus Convex's system\n * fields. Deliberately a bare intersection (no `Expand`/`Simplify`)—flattening\n * it with a homomorphic mapped type collapses to `{ [x: string]: any }` when\n * `Document` is still an unresolved generic, which breaks structural\n * comparability in the database reader/writer plumbing.\n */\nexport type WithSystemFields<\n TableName extends string,\n Document,\n> = Document extends unknown\n ? IdField<TableName> & NonIdSystemFields & Document\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,gBAA0C,cACrD,OAAO,OAAO;CACZ,KAAKA,UAAoB,SAAS;CAClC,eAAe,OAAO;AACxB,CAAC;;;;;AAcH,MAAM,mBAA0C,OAAO,KACrD,aAAa,EAAE,CAAC,CAAC,MACnB;AAEA,MAAM,oBAAoB,QACxB,UAAU,SAAS,GAAG,KAAK,MAAM,SAAS,kBAAkB,GAAG;AAEjE,MAAM,qBAAqB,UAA2C;CACpE,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,MAAM,QAAQ,eACZ,OAAO,YACL,MAAM,IAAI,aAAa,QAAQ,CAAC,KAAK,MAAM,IAAI,CAAU,CAC3D;CACF,OAAO;EACL,QAAQ,KAAK,MAAM,OAAO,MAAM,gBAAgB,CAAC;EACjD,MAAM,KAAK,MAAM,OAAO,MAAM,UAAU,IAAI,gBAAgB,CAAC,CAAC;CAChE;AACF;;;;;;;AAQA,MAAM,cACJ,WAEA,aAAa,yBAAyB,OAAO,YAAY;CACvD,IAAI,OAAO,OAAO,KAAK,KAAK,CAAC,UAAU,SAAS,MAAM,KAAK,GACzD,OAAO,aAAa,IAAI,QAAQ,OAAO,OAAO;CAEhD,MAAM,EAAE,QAAQ,SAAS,kBAAkB,MAAM,KAAK;CACtD,OAAO,aAAa,IAAI,QAAQ,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,CAAC,KAC1D,OAAO,IACL,OAAO,KAAK,WACV,UAAU,SAAS,MAAM,IAAI,OAAO,OAAO,QAAQ,MAAM,IAAI,MAC/D,CACF,CACF;AACF,CAAC;AAEH,MAAM,sBACJ,mBAC4D;CAC5D,IAAI,CAAC,qBAAqB,iBAAiB,cAAc,GACvD,MAA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