@gaganref/confect-core 10.3.1-fork.63 → 10.3.1-fork.65
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/dist/Callback.d.ts +7 -2
- package/dist/Callback.d.ts.map +1 -1
- package/dist/Callback.js +8 -4
- package/dist/Callback.js.map +1 -1
- package/dist/SchemaToValidator.d.ts +1 -1
- package/dist/SchemaToValidator.d.ts.map +1 -1
- package/dist/SchemaToValidator.js +22 -8
- package/dist/SchemaToValidator.js.map +1 -1
- package/dist/internal/annotations.d.ts +2 -0
- package/dist/internal/annotations.d.ts.map +1 -0
- package/dist/internal/annotations.js +6 -0
- package/dist/internal/annotations.js.map +1 -0
- package/package.json +1 -1
- package/src/Callback.ts +14 -3
- package/src/SchemaToValidator.ts +34 -13
- package/src/internal/annotations.ts +1 -0
package/dist/Callback.d.ts
CHANGED
|
@@ -66,9 +66,14 @@ export declare const action: <const Id_ extends Id, const ArgsFields_ extends Fu
|
|
|
66
66
|
}) => Contract<Id_, "action", ArgsFields_, Returns_, Error_>;
|
|
67
67
|
/**
|
|
68
68
|
* The schema of a handle for `contract`: a string on the wire, a runnable ref
|
|
69
|
-
* once decoded. Use it in a component's function args or tables.
|
|
69
|
+
* once decoded. Use it in a component's function args or tables. It lowers to
|
|
70
|
+
* Convex's `v.function` with the contract's encoded args and returns.
|
|
71
|
+
* `reservedArgument` opts mutation and action handles into context forwarding.
|
|
72
|
+
* The host target must reserve the same argument name.
|
|
70
73
|
*/
|
|
71
|
-
export declare const handle: <Contract_ extends Any>(contract: Contract_
|
|
74
|
+
export declare const handle: <Contract_ extends Any>(contract: Contract_, options?: {
|
|
75
|
+
readonly reservedArgument?: Contract_["functionType"] extends "query" ? never : string;
|
|
76
|
+
}) => Schema.Codec<Handle<Contract_>, string>;
|
|
72
77
|
type EncodedArgs<Ref_> = Ref_ extends {
|
|
73
78
|
readonly _tag: "Confect";
|
|
74
79
|
readonly args: {
|
package/dist/Callback.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Callback.d.ts","sourceRoot":"","sources":["../src/Callback.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,wBAAwB,EACxB,YAAY,EACb,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,KAAK,kBAAkB,MAAM,yBAAyB,CAAC;AAC9D,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"Callback.d.ts","sourceRoot":"","sources":["../src/Callback.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,wBAAwB,EACxB,YAAY,EACb,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,KAAK,kBAAkB,MAAM,yBAAyB,CAAC;AAC9D,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAGhC,OAAO,KAAK,KAAK,sBAAsB,MAAM,6BAA6B,CAAC;AAE3E,eAAO,MAAM,MAAM,4BAA4B,CAAC;AAChD,MAAM,MAAM,MAAM,GAAG,OAAO,MAAM,CAAC;AAEnC,QAAA,MAAM,YAAY,mCAAmC,CAAC;AAEtD;;GAEG;AACH,MAAM,MAAM,EAAE,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAC;AAEvC;;;;GAIG;AACH,MAAM,WAAW,QAAQ,CACvB,GAAG,SAAS,EAAE,EACd,aAAa,SAAS,YAAY,EAClC,WAAW,SAAS,kBAAkB,CAAC,UAAU,EACjD,QAAQ,SAAS,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,EACvC,MAAM,SAAS,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,KAAK;IAE7C,QAAQ,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC;IACjB,QA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AAE,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;CAAE,CAAC;AAEhE;;;GAGG;AACH,eAAO,MAAM,QAAQ,GAAI,IAAI,SAAS,GAAG,CAAC,GAAG,OACtC,IAAI,KACR,wBAAwB,CACzB,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,EACzB,GAAG,CAAC,qBAAqB,CAAC,IAAI,CAAC,EAC/B,WAAW,CAAC,IAAI,CAAC,EACjB,cAAc,CAAC,IAAI,CAAC,CACiB,CAAC"}
|
package/dist/Callback.js
CHANGED
|
@@ -2,6 +2,7 @@ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
|
2
2
|
import { Confect } from "./FunctionProvenance.js";
|
|
3
3
|
import { getFunctionReference } from "./RefInternal.js";
|
|
4
4
|
import { fromProvenance, isRef } from "./Ref.js";
|
|
5
|
+
import { CallbackContract } from "./internal/annotations.js";
|
|
5
6
|
import * as Schema from "effect/Schema";
|
|
6
7
|
import * as Predicate from "effect/Predicate";
|
|
7
8
|
import * as SchemaGetter from "effect/SchemaGetter";
|
|
@@ -28,13 +29,16 @@ const query = make("query");
|
|
|
28
29
|
const mutation = make("mutation");
|
|
29
30
|
const action = make("action");
|
|
30
31
|
const isHandleOf = (contract) => (value) => isRef(value) && Predicate.hasProperty(value, HandleTypeId) && value[HandleTypeId] === contract.id;
|
|
31
|
-
const fromText = (contract, text) => Object.assign(fromProvenance(text, contract.functionProvenance, [], text, contract.functionType), { [HandleTypeId]: contract.id });
|
|
32
|
+
const fromText = (contract, text, reservedArgument) => Object.assign(fromProvenance(text, contract.functionProvenance, [], text, contract.functionType, contract.functionType === "query" ? void 0 : reservedArgument), { [HandleTypeId]: contract.id });
|
|
32
33
|
/**
|
|
33
34
|
* The schema of a handle for `contract`: a string on the wire, a runnable ref
|
|
34
|
-
* once decoded. Use it in a component's function args or tables.
|
|
35
|
+
* once decoded. Use it in a component's function args or tables. It lowers to
|
|
36
|
+
* Convex's `v.function` with the contract's encoded args and returns.
|
|
37
|
+
* `reservedArgument` opts mutation and action handles into context forwarding.
|
|
38
|
+
* The host target must reserve the same argument name.
|
|
35
39
|
*/
|
|
36
|
-
const handle = (contract) => Schema.String.pipe(Schema.decodeTo(Schema.declare(isHandleOf(contract), { identifier: `Callback.Handle<${contract.id}>` }), {
|
|
37
|
-
decode: SchemaGetter.transform((text) => fromText(contract, text)),
|
|
40
|
+
const handle = (contract, options) => Schema.String.annotate({ [CallbackContract]: contract }).pipe(Schema.decodeTo(Schema.declare(isHandleOf(contract), { identifier: `Callback.Handle<${contract.id}>` }), {
|
|
41
|
+
decode: SchemaGetter.transform((text) => fromText(contract, text, options?.reservedArgument)),
|
|
38
42
|
encode: SchemaGetter.transform((ref) => ref.convexFunctionName)
|
|
39
43
|
}));
|
|
40
44
|
/**
|
package/dist/Callback.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Callback.js","names":["FunctionProvenance.Confect","Ref.isRef","Ref.fromProvenance"],"sources":["../src/Callback.ts"],"sourcesContent":["import type {\n FunctionReference,\n FunctionReference_future,\n FunctionType,\n} from \"convex/server\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as FunctionProvenance from \"./FunctionProvenance.js\";\nimport * as Ref from \"./Ref.js\";\nimport { getFunctionReference } from \"./RefInternal.js\";\nimport type * as RuntimeAndFunctionType from \"./RuntimeAndFunctionType.js\";\n\nexport const TypeId = \"~@confect/core/Callback\";\nexport type TypeId = typeof TypeId;\n\nconst HandleTypeId = \"~@confect/core/Callback/Handle\";\n\n/**\n * A contract's id, `\"<component>/<event>\"`.\n */\nexport type Id = `${string}/${string}`;\n\n/**\n * A function a component calls back into its host, declared by the component:\n * the args it sends and the returns and errors it accepts. A host proves that\n * one of its functions satisfies the contract when it creates a handle.\n */\nexport interface Contract<\n Id_ extends Id,\n FunctionType_ extends FunctionType,\n ArgsFields_ extends FunctionProvenance.ArgsFields,\n Returns_ extends Schema.Codec<any, any>,\n Error_ extends Schema.Codec<any, any> = never,\n> {\n readonly [TypeId]: TypeId;\n readonly id: Id_;\n readonly functionType: FunctionType_;\n readonly functionProvenance: FunctionProvenance.Confect<\n ArgsFields_,\n Returns_,\n Error_,\n FunctionProvenance.Standard\n >;\n}\n\nexport interface Any {\n readonly [TypeId]: TypeId;\n readonly id: Id;\n readonly functionType: FunctionType;\n readonly functionProvenance: FunctionProvenance.AnyConfect;\n}\n\nexport const isContract = (u: unknown): u is Any =>\n Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n\ntype ArgsFields<Contract_ extends Any> =\n Contract_[\"functionProvenance\"] extends {\n readonly \"~ArgsFields\": infer ArgsFields_ extends\n FunctionProvenance.ArgsFields;\n }\n ? ArgsFields_\n : never;\n\ntype ReturnsSchema<Contract_ extends Any> =\n Contract_[\"functionProvenance\"][\"returns\"];\n\ntype ErrorSchema<Contract_ extends Any> =\n Contract_[\"functionProvenance\"] extends {\n readonly error?: infer ErrorSchema_;\n }\n ? Extract<ErrorSchema_, Schema.Codec<any, any>>\n : never;\n\nexport type Args<Contract_ extends Any> = Schema.Struct.Type<\n ArgsFields<Contract_>\n>;\n\nexport type Returns<Contract_ extends Any> = ReturnsSchema<Contract_>[\"Type\"];\n\nexport type Error<Contract_ extends Any> = ErrorSchema<Contract_>[\"Type\"];\n\n/**\n * A host function a component received for a contract. It is a ref, so the\n * runners and the scheduler run it with the contract's codecs, and declared\n * errors arrive by tag.\n */\nexport type Handle<Contract_ extends Any> = Ref.ConfectRef<\n Extract<\n RuntimeAndFunctionType.RuntimeAndFunctionType,\n {\n readonly runtime: \"Convex\";\n readonly functionType: Contract_[\"functionType\"];\n }\n >,\n \"internal\",\n ArgsFields<Contract_>,\n ReturnsSchema<Contract_>,\n ErrorSchema<Contract_>\n> & { readonly [HandleTypeId]: Contract_[\"id\"] };\n\nconst make =\n <FunctionType_ extends FunctionType>(functionType: FunctionType_) =>\n <\n const Id_ extends Id,\n const ArgsFields_ extends FunctionProvenance.ArgsFields = {},\n Returns_ extends Schema.Codec<any, any> = never,\n Error_ extends Schema.Codec<any, any> = never,\n >(\n id: Id_,\n options: {\n readonly args?: () => ArgsFields_;\n readonly returns: () => Returns_;\n readonly error?: () => Error_;\n },\n ): Contract<Id_, FunctionType_, ArgsFields_, Returns_, Error_> => ({\n [TypeId]: TypeId,\n id,\n functionType,\n functionProvenance: FunctionProvenance.Confect(\n options.args ?? (() => ({}) as ArgsFields_),\n options.returns,\n options.error,\n ),\n });\n\nexport const query = make(\"query\");\nexport const mutation = make(\"mutation\");\nexport const action = make(\"action\");\n\nconst isHandleOf =\n <Contract_ extends Any>(contract: Contract_) =>\n (value: unknown): value is Handle<Contract_> =>\n Ref.isRef(value) &&\n Predicate.hasProperty(value, HandleTypeId) &&\n value[HandleTypeId] === contract.id;\n\nconst fromText = <Contract_ extends Any>(\n contract: Contract_,\n text: string,\n): Handle<Contract_> =>\n Object.assign(\n Ref.fromProvenance(\n text,\n contract.functionProvenance,\n [],\n // Convex types a handle as a string that is also a function reference.\n text as unknown as FunctionReference<any, any>,\n contract.functionType,\n ),\n { [HandleTypeId]: contract.id },\n ) as unknown as Handle<Contract_>;\n\n/**\n * The schema of a handle for `contract`: a string on the wire, a runnable ref\n * once decoded. Use it in a component's function args or tables.\n */\nexport const handle = <Contract_ extends Any>(\n contract: Contract_,\n): Schema.Codec<Handle<Contract_>, string> =>\n Schema.String.pipe(\n Schema.decodeTo(\n Schema.declare(isHandleOf(contract), {\n identifier: `Callback.Handle<${contract.id}>`,\n }),\n {\n decode: SchemaGetter.transform((text: string) =>\n fromText(contract, text),\n ),\n encode: SchemaGetter.transform(\n (ref: Handle<Contract_>) => ref.convexFunctionName,\n ),\n },\n ),\n );\n\ntype EncodedArgs<Ref_> = Ref_ extends {\n readonly _tag: \"Confect\";\n readonly args: {\n readonly fields: infer ArgsFields_ extends FunctionProvenance.ArgsFields;\n };\n}\n ? Schema.Struct.Encoded<ArgsFields_>\n : Ref.Args<Ref_>;\n\ntype EncodedReturns<Ref_> = Ref_ extends { readonly _tag: \"Confect\" }\n ? Ref.ReturnsSchema<Ref_>[\"Encoded\"]\n : Ref.Returns<Ref_>;\n\ntype IsAny<A> = 0 extends 1 & A ? true : false;\n\n/**\n * A Confect ref typed from values alone, such as a bound component's ref, has\n * no codec types left to compare, and middleware attachments typed without\n * their specs erase their errors. True when any variant of `Ref_` is erased.\n */\ntype IsErased<Ref_> = true extends (\n Ref_ extends { readonly _tag: \"Confect\" }\n ? IsAny<Ref.ReturnsSchema<Ref_>[\"Encoded\"]> | IsAny<Ref.EncodedError<Ref_>>\n : false\n)\n ? true\n : false;\n\n/**\n * The shape a value has on the wire: a component's ID brands become `string`,\n * since the contract cannot name the host's scope, while the host's own IDs\n * keep their table. Arrays and tuples lose `readonly`, and an optional field is\n * the same whether or not it admits `undefined`, which Convex never transmits.\n * `unknown` stays `unknown`.\n */\ntype WireShape<A> = unknown extends A\n ? A\n : A extends { readonly \"~@confect/core/ScopedId\": unknown }\n ? string\n : A extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n | ArrayBuffer\n ? A\n : { -readonly [Key in keyof A]: WireShape<Exclude<A[Key], undefined>> };\n\ntype Identical<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2\n ? true\n : false;\n\ntype FirstOf<Checks extends ReadonlyArray<unknown>> = Checks extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? [Head] extends [never]\n ? FirstOf<Rest>\n : Head\n : never;\n\n/**\n * Every obligation a host ref owes a contract, in the order they are reported.\n * Each is `never` when it holds.\n */\ntype Obligations<Contract_ extends Any, Ref_ extends Ref.Any> = [\n IsErased<Ref_> extends true\n ? `the ref's codecs are erased, so its encoding cannot be checked against \"${Contract_[\"id\"]}\"; pass the host's generated ref`\n : never,\n [Ref.GetFunctionType<Ref_>] extends [Contract_[\"functionType\"]]\n ? never\n : `\"${Contract_[\"id\"]}\" needs a ${Contract_[\"functionType\"]}, not a ${Ref.GetFunctionType<Ref_>}`,\n Identical<\n WireShape<EncodedArgs<Handle<Contract_>>>,\n WireShape<EncodedArgs<Ref_>>\n > extends true\n ? never\n : `the ref's encoded args differ from the args \"${Contract_[\"id\"]}\" sends`,\n Identical<\n WireShape<EncodedReturns<Handle<Contract_>>>,\n WireShape<EncodedReturns<Ref_>>\n > extends true\n ? never\n : `the ref's returns are encoded differently from the returns of \"${Contract_[\"id\"]}\"`,\n [Ref.Error<Ref_>] extends [Error<Contract_>]\n ? never\n : `the ref fails with errors \"${Contract_[\"id\"]}\" does not declare`,\n [WireShape<Ref.EncodedError<Ref_>>] extends [\n WireShape<Ref.EncodedError<Handle<Contract_>>>,\n ]\n ? never\n : `the ref's errors are encoded differently from the errors of \"${Contract_[\"id\"]}\"`,\n];\n\ntype Mismatch<Contract_ extends Any, Ref_ extends Ref.Any> = FirstOf<\n Obligations<Contract_, Ref_>\n>;\n\n/**\n * `unknown` when host ref `Ref_` satisfies `Contract_` as far as its types\n * show, otherwise an object type naming the first mismatch. The check compares\n * the types that cross the wire, with a component's IDs compared as strings.\n * The host's encoded args and returns must equal the contract's, and its\n * encoded errors (middleware errors included) must be ones the contract's\n * codecs decode. A ref whose codecs are erased cannot be checked and is\n * refused. Types miss what only the validators show, such as field names behind\n * a `Record` type, so `Callback.create` in `@confect/server` also compares the\n * compiled validators before it creates a handle.\n */\nexport type Check<Contract_ extends Any, Ref_ extends Ref.Any> = [\n Mismatch<Contract_, Ref_>,\n] extends [never]\n ? unknown\n : { readonly \"~CallbackMismatch\": Mismatch<Contract_, Ref_> };\n\n/**\n * View a ref as Convex's `FunctionReference_future`, typed with its wire args\n * and returns, for `createFunctionHandle` and clients that accept it.\n */\nexport const toFuture = <Ref_ extends Ref.Any>(\n ref: Ref_,\n): FunctionReference_future<\n Ref.GetFunctionType<Ref_>,\n Ref.GetFunctionVisibility<Ref_>,\n EncodedArgs<Ref_>,\n EncodedReturns<Ref_>\n> => getFunctionReference(ref) as never;\n"],"mappings":";;;;;;;;;;;;;;;;;AAaA,MAAa,SAAS;AAGtB,MAAM,eAAe;AAqCrB,MAAa,cAAc,MACzB,UAAU,YAAY,GAAA,yBAAS,KAAK,EAAA,+BAAA;AA+CtC,MAAM,QACiC,kBAOnC,IACA,aAKiE;EAChE,SAAS;CACV;CACA;CACA,oBAAoBA,QAClB,QAAQ,gBAAgB,CAAC,KACzB,QAAQ,SACR,QAAQ,KACV;AACF;AAEF,MAAa,QAAQ,KAAK,OAAO;AACjC,MAAa,WAAW,KAAK,UAAU;AACvC,MAAa,SAAS,KAAK,QAAQ;AAEnC,MAAM,cACoB,cACvB,UACCC,MAAU,KAAK,KACf,UAAU,YAAY,OAAO,YAAY,KACzC,MAAM,kBAAkB,SAAS;AAErC,MAAM,YACJ,UACA,SAEA,OAAO,OACLC,eACE,MACA,SAAS,oBACT,CAAC,GAED,MACA,SAAS,YACX,GACA,GAAG,eAAe,SAAS,GAAG,CAChC;;;;;AAMF,MAAa,UACX,aAEA,OAAO,OAAO,KACZ,OAAO,SACL,OAAO,QAAQ,WAAW,QAAQ,GAAG,EACnC,YAAY,mBAAmB,SAAS,GAAG,GAC7C,CAAC,GACD;CACE,QAAQ,aAAa,WAAW,SAC9B,SAAS,UAAU,IAAI,CACzB;CACA,QAAQ,aAAa,WAClB,QAA2B,IAAI,kBAClC;AACF,CACF,CACF;;;;;AA4HF,MAAa,YACX,QAMG,qBAAqB,GAAG"}
|
|
1
|
+
{"version":3,"file":"Callback.js","names":["FunctionProvenance.Confect","Ref.isRef","Ref.fromProvenance"],"sources":["../src/Callback.ts"],"sourcesContent":["import type {\n FunctionReference,\n FunctionReference_future,\n FunctionType,\n} from \"convex/server\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as FunctionProvenance from \"./FunctionProvenance.js\";\nimport * as Ref from \"./Ref.js\";\nimport { getFunctionReference } from \"./RefInternal.js\";\nimport { CallbackContract } from \"./internal/annotations.js\";\nimport type * as RuntimeAndFunctionType from \"./RuntimeAndFunctionType.js\";\n\nexport const TypeId = \"~@confect/core/Callback\";\nexport type TypeId = typeof TypeId;\n\nconst HandleTypeId = \"~@confect/core/Callback/Handle\";\n\n/**\n * A contract's id, `\"<component>/<event>\"`.\n */\nexport type Id = `${string}/${string}`;\n\n/**\n * A function a component calls back into its host, declared by the component:\n * the args it sends and the returns and errors it accepts. A host proves that\n * one of its functions satisfies the contract when it creates a handle.\n */\nexport interface Contract<\n Id_ extends Id,\n FunctionType_ extends FunctionType,\n ArgsFields_ extends FunctionProvenance.ArgsFields,\n Returns_ extends Schema.Codec<any, any>,\n Error_ extends Schema.Codec<any, any> = never,\n> {\n readonly [TypeId]: TypeId;\n readonly id: Id_;\n readonly functionType: FunctionType_;\n readonly functionProvenance: FunctionProvenance.Confect<\n ArgsFields_,\n Returns_,\n Error_,\n FunctionProvenance.Standard\n >;\n}\n\nexport interface Any {\n readonly [TypeId]: TypeId;\n readonly id: Id;\n readonly functionType: FunctionType;\n readonly functionProvenance: FunctionProvenance.AnyConfect;\n}\n\nexport const isContract = (u: unknown): u is Any =>\n Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n\ntype ArgsFields<Contract_ extends Any> =\n Contract_[\"functionProvenance\"] extends {\n readonly \"~ArgsFields\": infer ArgsFields_ extends\n FunctionProvenance.ArgsFields;\n }\n ? ArgsFields_\n : never;\n\ntype ReturnsSchema<Contract_ extends Any> =\n Contract_[\"functionProvenance\"][\"returns\"];\n\ntype ErrorSchema<Contract_ extends Any> =\n Contract_[\"functionProvenance\"] extends {\n readonly error?: infer ErrorSchema_;\n }\n ? Extract<ErrorSchema_, Schema.Codec<any, any>>\n : never;\n\nexport type Args<Contract_ extends Any> = Schema.Struct.Type<\n ArgsFields<Contract_>\n>;\n\nexport type Returns<Contract_ extends Any> = ReturnsSchema<Contract_>[\"Type\"];\n\nexport type Error<Contract_ extends Any> = ErrorSchema<Contract_>[\"Type\"];\n\n/**\n * A host function a component received for a contract. It is a ref, so the\n * runners and the scheduler run it with the contract's codecs, and declared\n * errors arrive by tag.\n */\nexport type Handle<Contract_ extends Any> = Ref.ConfectRef<\n Extract<\n RuntimeAndFunctionType.RuntimeAndFunctionType,\n {\n readonly runtime: \"Convex\";\n readonly functionType: Contract_[\"functionType\"];\n }\n >,\n \"internal\",\n ArgsFields<Contract_>,\n ReturnsSchema<Contract_>,\n ErrorSchema<Contract_>\n> & { readonly [HandleTypeId]: Contract_[\"id\"] };\n\nconst make =\n <FunctionType_ extends FunctionType>(functionType: FunctionType_) =>\n <\n const Id_ extends Id,\n const ArgsFields_ extends FunctionProvenance.ArgsFields = {},\n Returns_ extends Schema.Codec<any, any> = never,\n Error_ extends Schema.Codec<any, any> = never,\n >(\n id: Id_,\n options: {\n readonly args?: () => ArgsFields_;\n readonly returns: () => Returns_;\n readonly error?: () => Error_;\n },\n ): Contract<Id_, FunctionType_, ArgsFields_, Returns_, Error_> => ({\n [TypeId]: TypeId,\n id,\n functionType,\n functionProvenance: FunctionProvenance.Confect(\n options.args ?? (() => ({}) as ArgsFields_),\n options.returns,\n options.error,\n ),\n });\n\nexport const query = make(\"query\");\nexport const mutation = make(\"mutation\");\nexport const action = make(\"action\");\n\nconst isHandleOf =\n <Contract_ extends Any>(contract: Contract_) =>\n (value: unknown): value is Handle<Contract_> =>\n Ref.isRef(value) &&\n Predicate.hasProperty(value, HandleTypeId) &&\n value[HandleTypeId] === contract.id;\n\nconst fromText = <Contract_ extends Any>(\n contract: Contract_,\n text: string,\n reservedArgument?: string,\n): Handle<Contract_> =>\n Object.assign(\n Ref.fromProvenance(\n text,\n contract.functionProvenance,\n [],\n // Convex types a handle as a string that is also a function reference.\n text as unknown as FunctionReference<any, any>,\n contract.functionType,\n contract.functionType === \"query\" ? undefined : reservedArgument,\n ),\n { [HandleTypeId]: contract.id },\n ) as unknown as Handle<Contract_>;\n\n/**\n * The schema of a handle for `contract`: a string on the wire, a runnable ref\n * once decoded. Use it in a component's function args or tables. It lowers to\n * Convex's `v.function` with the contract's encoded args and returns.\n * `reservedArgument` opts mutation and action handles into context forwarding.\n * The host target must reserve the same argument name.\n */\nexport const handle = <Contract_ extends Any>(\n contract: Contract_,\n options?: {\n readonly reservedArgument?: Contract_[\"functionType\"] extends \"query\"\n ? never\n : string;\n },\n): Schema.Codec<Handle<Contract_>, string> =>\n Schema.String.annotate({ [CallbackContract]: contract }).pipe(\n Schema.decodeTo(\n Schema.declare(isHandleOf(contract), {\n identifier: `Callback.Handle<${contract.id}>`,\n }),\n {\n decode: SchemaGetter.transform((text: string) =>\n fromText(contract, text, options?.reservedArgument),\n ),\n encode: SchemaGetter.transform(\n (ref: Handle<Contract_>) => ref.convexFunctionName,\n ),\n },\n ),\n );\n\ntype EncodedArgs<Ref_> = Ref_ extends {\n readonly _tag: \"Confect\";\n readonly args: {\n readonly fields: infer ArgsFields_ extends FunctionProvenance.ArgsFields;\n };\n}\n ? Schema.Struct.Encoded<ArgsFields_>\n : Ref.Args<Ref_>;\n\ntype EncodedReturns<Ref_> = Ref_ extends { readonly _tag: \"Confect\" }\n ? Ref.ReturnsSchema<Ref_>[\"Encoded\"]\n : Ref.Returns<Ref_>;\n\ntype IsAny<A> = 0 extends 1 & A ? true : false;\n\n/**\n * A Confect ref typed from values alone, such as a bound component's ref, has\n * no codec types left to compare, and middleware attachments typed without\n * their specs erase their errors. True when any variant of `Ref_` is erased.\n */\ntype IsErased<Ref_> = true extends (\n Ref_ extends { readonly _tag: \"Confect\" }\n ? IsAny<Ref.ReturnsSchema<Ref_>[\"Encoded\"]> | IsAny<Ref.EncodedError<Ref_>>\n : false\n)\n ? true\n : false;\n\n/**\n * The shape a value has on the wire: a component's ID brands become `string`,\n * since the contract cannot name the host's scope, while the host's own IDs\n * keep their table. Arrays and tuples lose `readonly`, and an optional field is\n * the same whether or not it admits `undefined`, which Convex never transmits.\n * `unknown` stays `unknown`.\n */\ntype WireShape<A> = unknown extends A\n ? A\n : A extends { readonly \"~@confect/core/ScopedId\": unknown }\n ? string\n : A extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n | ArrayBuffer\n ? A\n : { -readonly [Key in keyof A]: WireShape<Exclude<A[Key], undefined>> };\n\ntype Identical<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2\n ? true\n : false;\n\ntype FirstOf<Checks extends ReadonlyArray<unknown>> = Checks extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? [Head] extends [never]\n ? FirstOf<Rest>\n : Head\n : never;\n\n/**\n * Every obligation a host ref owes a contract, in the order they are reported.\n * Each is `never` when it holds.\n */\ntype Obligations<Contract_ extends Any, Ref_ extends Ref.Any> = [\n IsErased<Ref_> extends true\n ? `the ref's codecs are erased, so its encoding cannot be checked against \"${Contract_[\"id\"]}\"; pass the host's generated ref`\n : never,\n [Ref.GetFunctionType<Ref_>] extends [Contract_[\"functionType\"]]\n ? never\n : `\"${Contract_[\"id\"]}\" needs a ${Contract_[\"functionType\"]}, not a ${Ref.GetFunctionType<Ref_>}`,\n Identical<\n WireShape<EncodedArgs<Handle<Contract_>>>,\n WireShape<EncodedArgs<Ref_>>\n > extends true\n ? never\n : `the ref's encoded args differ from the args \"${Contract_[\"id\"]}\" sends`,\n Identical<\n WireShape<EncodedReturns<Handle<Contract_>>>,\n WireShape<EncodedReturns<Ref_>>\n > extends true\n ? never\n : `the ref's returns are encoded differently from the returns of \"${Contract_[\"id\"]}\"`,\n [Ref.Error<Ref_>] extends [Error<Contract_>]\n ? never\n : `the ref fails with errors \"${Contract_[\"id\"]}\" does not declare`,\n [WireShape<Ref.EncodedError<Ref_>>] extends [\n WireShape<Ref.EncodedError<Handle<Contract_>>>,\n ]\n ? never\n : `the ref's errors are encoded differently from the errors of \"${Contract_[\"id\"]}\"`,\n];\n\ntype Mismatch<Contract_ extends Any, Ref_ extends Ref.Any> = FirstOf<\n Obligations<Contract_, Ref_>\n>;\n\n/**\n * `unknown` when host ref `Ref_` satisfies `Contract_` as far as its types\n * show, otherwise an object type naming the first mismatch. The check compares\n * the types that cross the wire, with a component's IDs compared as strings.\n * The host's encoded args and returns must equal the contract's, and its\n * encoded errors (middleware errors included) must be ones the contract's\n * codecs decode. A ref whose codecs are erased cannot be checked and is\n * refused. Types miss what only the validators show, such as field names behind\n * a `Record` type, so `Callback.create` in `@confect/server` also compares the\n * compiled validators before it creates a handle.\n */\nexport type Check<Contract_ extends Any, Ref_ extends Ref.Any> = [\n Mismatch<Contract_, Ref_>,\n] extends [never]\n ? unknown\n : { readonly \"~CallbackMismatch\": Mismatch<Contract_, Ref_> };\n\n/**\n * View a ref as Convex's `FunctionReference_future`, typed with its wire args\n * and returns, for `createFunctionHandle` and clients that accept it.\n */\nexport const toFuture = <Ref_ extends Ref.Any>(\n ref: Ref_,\n): FunctionReference_future<\n Ref.GetFunctionType<Ref_>,\n Ref.GetFunctionVisibility<Ref_>,\n EncodedArgs<Ref_>,\n EncodedReturns<Ref_>\n> => getFunctionReference(ref) as never;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAa,SAAS;AAGtB,MAAM,eAAe;AAqCrB,MAAa,cAAc,MACzB,UAAU,YAAY,GAAA,yBAAS,KAAK,EAAA,+BAAA;AA+CtC,MAAM,QACiC,kBAOnC,IACA,aAKiE;EAChE,SAAS;CACV;CACA;CACA,oBAAoBA,QAClB,QAAQ,gBAAgB,CAAC,KACzB,QAAQ,SACR,QAAQ,KACV;AACF;AAEF,MAAa,QAAQ,KAAK,OAAO;AACjC,MAAa,WAAW,KAAK,UAAU;AACvC,MAAa,SAAS,KAAK,QAAQ;AAEnC,MAAM,cACoB,cACvB,UACCC,MAAU,KAAK,KACf,UAAU,YAAY,OAAO,YAAY,KACzC,MAAM,kBAAkB,SAAS;AAErC,MAAM,YACJ,UACA,MACA,qBAEA,OAAO,OACLC,eACE,MACA,SAAS,oBACT,CAAC,GAED,MACA,SAAS,cACT,SAAS,iBAAiB,UAAU,KAAA,IAAY,gBAClD,GACA,GAAG,eAAe,SAAS,GAAG,CAChC;;;;;;;;AASF,MAAa,UACX,UACA,YAMA,OAAO,OAAO,SAAS,GAAG,mBAAmB,SAAS,CAAC,CAAC,CAAC,KACvD,OAAO,SACL,OAAO,QAAQ,WAAW,QAAQ,GAAG,EACnC,YAAY,mBAAmB,SAAS,GAAG,GAC7C,CAAC,GACD;CACE,QAAQ,aAAa,WAAW,SAC9B,SAAS,UAAU,MAAM,SAAS,gBAAgB,CACpD;CACA,QAAQ,aAAa,WAClB,QAA2B,IAAI,kBAClC;AACF,CACF,CACF;;;;;AA4HF,MAAa,YACX,QAMG,qBAAqB,GAAG"}
|
|
@@ -44,7 +44,7 @@ type OptionalValueToValidator<Vl> = [Vl] extends [
|
|
|
44
44
|
] ? ConvertValueToValidator<Val, "optional"> : never;
|
|
45
45
|
export declare const compileSchema: <T, E>(schema: Schema.Codec<T, E>) => ValueToValidator<(typeof schema)["Encoded"]>;
|
|
46
46
|
export declare const isRecursive: (ast: SchemaAST.AST) => boolean;
|
|
47
|
-
export declare const compileAst: (ast: SchemaAST.AST, isOptionalPropertyOfTypeLiteral?: boolean, scope?: IdScope.IdScope) => Effect.Effect<Validator<any, any, any>, UnsupportedSchemaTypeError | UnsupportedPropertySignatureKeyTypeError | IndexSignaturesAreNotSupportedError | MixedIndexAndPropertySignaturesAreNotSupportedError | OptionalTupleElementsAreNotSupportedError | EmptyTupleIsNotSupportedError | EmptyUnionIsNotSupportedError>;
|
|
47
|
+
export declare const compileAst: (ast: SchemaAST.AST, isOptionalPropertyOfTypeLiteral?: boolean, scope?: IdScope.IdScope) => Effect.Effect<Validator<any, any, any>, TopLevelMustBeObjectError | UnsupportedSchemaTypeError | UnsupportedPropertySignatureKeyTypeError | IndexSignaturesAreNotSupportedError | MixedIndexAndPropertySignaturesAreNotSupportedError | OptionalTupleElementsAreNotSupportedError | EmptyTupleIsNotSupportedError | EmptyUnionIsNotSupportedError>;
|
|
48
48
|
declare const TopLevelMustBeObjectError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
49
49
|
readonly _tag: "TopLevelMustBeObjectError";
|
|
50
50
|
} & Readonly<A>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SchemaToValidator.d.ts","sourceRoot":"","sources":["../src/SchemaToValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"SchemaToValidator.d.ts","sourceRoot":"","sources":["../src/SchemaToValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AAGxC,OAAO,KAAK,EACV,SAAS,IAAI,eAAe,EAC5B,kBAAkB,EAClB,SAAS,EACT,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,GAAG,EACH,MAAM,EACN,QAAQ,EACR,KAAK,EACL,OAAO,EACP,OAAO,EACP,OAAO,EACP,MAAM,EACP,MAAM,eAAe,CAAC;AAKvB,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAKxC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,SAAS,MAAM,kBAAkB,CAAC;AAI9C,OAAO,KAAK,EACV,KAAK,EACL,UAAU,EACV,QAAQ,EACR,WAAW,EACX,OAAO,EACP,SAAS,EACT,YAAY,EACb,MAAM,YAAY,CAAC;AAIpB,eAAO,MAAM,iBAAiB,GAAI,YAAY,EAAE,WAAW,cAC7C,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,WAAW,CAAC,UAC5C,OAAO,CAAC,OAAO,qBACH,MAAM,iBACV,MAAM,KACpB,kBAYF,CAAC;;;;AAcF,qBAAa,yBAA0B,SAAQ,+BAE7C;IACA,QAAQ,CAAC,YAAY,EAAE,MAAM,GAA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C;IACA,QAAQ,CAAC,UAAU,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;CAC5C,CAAC;IAEA,IAAa,OAAO,WAEnB;CAEF;;;;AAED,qBAAa,mCAAoC,SAAQ,wCAExD;IAEC,IAAa,OAAO,WAEnB;CAEF;;;;AAED,qBAAa,mDAAoD,SAAQ,wDAExE;IAEC,IAAa,OAAO,WAEnB;CAEF;;;;AAED,qBAAa,yCAA0C,SAAQ,8CAE9D;IAEC,IAAa,OAAO,WAEnB;CAEF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { CallbackContract } from "./internal/annotations.js";
|
|
2
3
|
import { app } from "./IdScope.js";
|
|
3
4
|
import { scope, tableName } from "./GenericId.js";
|
|
4
5
|
import * as Schema from "effect/Schema";
|
|
@@ -34,7 +35,7 @@ var SchemaToValidator_exports = /* @__PURE__ */ __exportAll({
|
|
|
34
35
|
});
|
|
35
36
|
const compileArgsSchema = (argsSchema, scope = app, reservedArgument, functionName) => {
|
|
36
37
|
const ast = Schema.toEncoded(argsSchema).ast;
|
|
37
|
-
const validators =
|
|
38
|
+
const validators = Effect.runSync(compileArgsAst(ast, scope));
|
|
38
39
|
if (reservedArgument === void 0) return validators;
|
|
39
40
|
if (Object.hasOwn(validators, reservedArgument)) throw new ReservedArgumentCollision({
|
|
40
41
|
functionName,
|
|
@@ -45,6 +46,7 @@ const compileArgsSchema = (argsSchema, scope = app, reservedArgument, functionNa
|
|
|
45
46
|
[reservedArgument]: v.optional(v.any())
|
|
46
47
|
};
|
|
47
48
|
};
|
|
49
|
+
const compileArgsAst = (ast, scope) => pipe(ast, Match.value, Match.tag("Objects", (objectsAst) => Array.isReadonlyArrayEmpty(objectsAst.indexSignatures) ? handlePropertySignatures(objectsAst, scope) : Effect.fail(new IndexSignaturesAreNotSupportedError())), Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())));
|
|
48
50
|
var ReservedArgumentCollision = class extends Data.TaggedError("ReservedArgumentCollision") {
|
|
49
51
|
get message() {
|
|
50
52
|
return `${this.functionName} declares the argument "${this.argument}", which its profile reserves. Rename the argument.`;
|
|
@@ -57,13 +59,25 @@ const compileTableSchema = (schema, scope = app) => {
|
|
|
57
59
|
};
|
|
58
60
|
const compileSchema = (schema) => Effect.runSync(compileAst(schema.ast));
|
|
59
61
|
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);
|
|
60
|
-
const compileAst = (ast, isOptionalPropertyOfTypeLiteral = false, scope$1 = app) =>
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
const compileAst = (ast, isOptionalPropertyOfTypeLiteral = false, scope$1 = app) => {
|
|
63
|
+
const contract = SchemaAST.resolveAt(CallbackContract)(ast);
|
|
64
|
+
if (contract !== void 0) return Effect.gen(function* () {
|
|
65
|
+
const args = yield* compileArgsAst(Schema.toEncoded(contract.functionProvenance.args).ast, scope$1);
|
|
66
|
+
const returns = yield* compileAst(Schema.toEncoded(contract.functionProvenance.returns).ast, false, scope$1);
|
|
67
|
+
return v.function({
|
|
68
|
+
fnType: contract.functionType,
|
|
69
|
+
args,
|
|
70
|
+
returns
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
return 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({
|
|
74
|
+
onNone: () => Effect.succeed(v.string()),
|
|
75
|
+
onSome: (tableName) => Effect.succeed(scope(stringAst) === scope$1 ? v.id(tableName) : v.string())
|
|
76
|
+
}))), Match.tag("Number", () => Effect.succeed(v.float64())), Match.tag("BigInt", () => Effect.succeed(v.int64())), Match.tag("Union", (unionAst) => handleUnion(unionAst, isOptionalPropertyOfTypeLiteral, scope$1)), Match.tag("Objects", (objectsAst) => handleObjects(objectsAst, scope$1)), Match.tag("Arrays", (arraysAst) => handleArrays(arraysAst, scope$1)), Match.tag("Unknown", "Any", () => Effect.succeed(v.any())), Match.tag("Declaration", (declaration) => Effect.mapBoth(declaration.run(declaration.typeParameters)(/* @__PURE__ */ new ArrayBuffer(0), declaration, {}), {
|
|
77
|
+
onSuccess: () => v.bytes(),
|
|
78
|
+
onFailure: () => new UnsupportedSchemaTypeError({ schemaType: declaration._tag })
|
|
79
|
+
})), 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);
|
|
80
|
+
};
|
|
67
81
|
const handleUnion = ({ types }, isOptionalPropertyOfTypeLiteral, scope) => handleUnionTypes(types, isOptionalPropertyOfTypeLiteral, scope);
|
|
68
82
|
const handleUnionTypes = Effect.fnUntraced(function* (types, isOptionalPropertyOfTypeLiteral, scope) {
|
|
69
83
|
const members = isOptionalPropertyOfTypeLiteral ? Array.filter(types, Predicate.not(SchemaAST.isUndefined)) : types;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SchemaToValidator.js","names":["IdScope.app","GenericId.tableName","GenericId.scope","scope"],"sources":["../src/SchemaToValidator.ts"],"sourcesContent":["import * as IdScope from \"./IdScope.js\";\nimport type {\n GenericId as ConvexGenericId,\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 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.js\";\nimport type {\n IsAny,\n IsOptional,\n IsRecord,\n IsRecursive,\n IsUnion,\n TypeError,\n UnionToTuple,\n} from \"./Types.js\";\n\n// Args\n\nexport const compileArgsSchema = <ConfectValue, ConvexValue>(\n argsSchema: Schema.Codec<ConfectValue, ConvexValue>,\n scope: IdScope.IdScope = IdScope.app,\n reservedArgument?: string,\n functionName?: string,\n): PropertyValidators => {\n const ast = Schema.toEncoded(argsSchema).ast;\n\n const validators = pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", (objectsAst) =>\n Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)\n ? handlePropertySignatures(objectsAst, scope)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),\n Effect.runSync,\n );\n if (reservedArgument === undefined) return validators;\n if (Object.hasOwn(validators, reservedArgument)) {\n throw new ReservedArgumentCollision({\n functionName,\n argument: reservedArgument,\n });\n }\n return { ...validators, [reservedArgument]: v.optional(v.any()) };\n};\n\nexport class ReservedArgumentCollision extends Data.TaggedError(\n \"ReservedArgumentCollision\",\n)<{\n readonly functionName: string | undefined;\n readonly argument: string;\n}> {\n override get message() {\n return `${this.functionName} declares the argument \"${this.argument}\", which its profile reserves. Rename the argument.`;\n }\n}\n\n// Returns\n\nexport const compileReturnsSchema = <ConfectValue, ConvexValue>(\n schema: Schema.Codec<ConfectValue, ConvexValue>,\n scope: IdScope.IdScope = IdScope.app,\n): Validator<any, any, any> =>\n Effect.runSync(compileAst(Schema.toEncoded(schema).ast, false, scope));\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 scope: IdScope.IdScope = IdScope.app,\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, false, scope) as Effect.Effect<any>)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.tag(\"Union\", (unionAst) => compileAst(unionAst, false, scope)),\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 [string | number | bigint | boolean | null | ArrayBuffer]\n ? ConvertValueToValidator<Vl>\n : IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? ConvertValueToValidator<Vl>\n : TypeError<\"Provided value is not a valid Convex value\", Vl>;\n\ntype OptionalValue<Vl, Optionality> = Optionality extends \"optional\"\n ? Vl | undefined\n : Vl;\n\ntype ConvertValueToValidator<\n Vl,\n Optionality extends \"required\" | \"optional\" = \"required\",\n> = [Vl] extends [never]\n ? never\n : IsAny<Vl> extends true\n ? VAny<any, Optionality>\n : [Vl] extends [null]\n ? VNull<OptionalValue<null, Optionality>, Optionality>\n : [Vl] extends [boolean]\n ? [boolean] extends [Vl]\n ? VBoolean<OptionalValue<boolean, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>\n : IsUnion<Vl> extends true\n ? UnionValueToValidator<Vl, Optionality>\n : [Vl] extends [number]\n ? [number] extends [Vl]\n ? VFloat64<OptionalValue<number, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>\n : [Vl] extends [bigint]\n ? [bigint] extends [Vl]\n ? VInt64<OptionalValue<bigint, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>\n : [Vl] extends [string]\n ? StringValueToValidator<Vl, Optionality>\n : [Vl] extends [ArrayBuffer]\n ? VBytes<OptionalValue<ArrayBuffer, Optionality>, Optionality>\n : IsRecursive<Vl> extends true\n ? VAny<any, Optionality>\n : Vl extends ReadonlyArray<infer El>\n ? VArray<\n OptionalValue<MutableValue<El[]>, Optionality>,\n ConvertValueToValidator<El>,\n Optionality\n >\n : Vl extends object\n ? ObjectValueToValidator<Vl, Optionality>\n : never;\n\ntype StringValueToValidator<Vl, Optionality extends \"required\" | \"optional\"> =\n Vl extends ConvexGenericId<string>\n ? VId<OptionalValue<Vl, Optionality>, Optionality>\n : [string] extends [Vl]\n ? VString<OptionalValue<string, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>;\n\ntype ObjectValueToValidator<Vl, Optionality extends \"required\" | \"optional\"> =\n IsRecord<MutableValue<Vl>> extends true\n ? ValueToValidator<Vl[keyof Vl]> extends infer VdValue extends Validator<\n any,\n \"required\",\n any\n >\n ? VRecord<\n OptionalValue<MutableValue<Vl>, Optionality>,\n VString,\n VdValue,\n Optionality\n >\n : never\n : ObjectFieldsToValidators<Vl> extends infer VdFields extends Record<\n string,\n any\n >\n ? VObject<\n OptionalValue<MutableValue<Vl>, Optionality>,\n VdFields,\n Optionality\n >\n : never;\n\ntype ObjectFieldsToValidators<Vl> = {\n -readonly [K in keyof Vl]-?: IsAny<Vl[K]> extends true\n ? IsOptional<Vl, K> extends true\n ? VAny<any, \"optional\">\n : VAny\n : undefined extends Vl[K]\n ? OptionalValueToValidator<Vl[K]>\n : [Vl[K]] extends [ReadonlyValue]\n ? ConvertValueToValidator<Vl[K]>\n : never;\n};\n\nexport type UndefinedOrValueToValidator<Vl extends ReadonlyValue | undefined> =\n undefined extends Vl\n ? OptionalValueToValidator<Vl>\n : [Vl] extends [ReadonlyValue]\n ? ValueToValidator<Vl>\n : never;\n\ntype UnionValueToValidator<Vl, Optionality extends \"required\" | \"optional\"> =\n IsRecursive<Vl> extends true\n ? VAny<any, Optionality>\n : VUnion<\n OptionalValue<MutableValue<Vl>, Optionality>,\n ValueTupleToValidatorTuple<UnionToTuple<Vl>>,\n Optionality\n >;\n\ntype ValueTupleToValidatorTuple<\n VlTuple extends readonly unknown[],\n Acc extends Validator<any, \"required\", any>[] = [],\n> = VlTuple extends\n | [true, false, ...infer VlRest]\n | [false, true, ...infer VlRest]\n ? ValueTupleToValidatorTuple<VlRest, [...Acc, VBoolean]>\n : VlTuple extends [infer Vl, ...infer VlRest]\n ? ValueTupleToValidatorTuple<VlRest, [...Acc, ConvertValueToValidator<Vl>]>\n : Acc;\n\ntype OptionalValueToValidator<Vl> = [Vl] extends [\n (infer Val extends ReadonlyValue) | undefined,\n]\n ? ConvertValueToValidator<Val, \"optional\">\n : never;\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 scope: IdScope.IdScope = IdScope.app,\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) =>\n Effect.succeed(\n GenericId.scope(stringAst) === scope\n ? v.id(tableName)\n : v.string(),\n ),\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, scope),\n ),\n Match.tag(\"Objects\", (objectsAst) => handleObjects(objectsAst, scope)),\n Match.tag(\"Arrays\", (arraysAst) => handleArrays(arraysAst, scope)),\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 scope: IdScope.IdScope,\n) => handleUnionTypes(types, isOptionalPropertyOfTypeLiteral, scope);\n\nconst handleUnionTypes = Effect.fnUntraced(function* (\n types: SchemaAST.Union[\"types\"],\n isOptionalPropertyOfTypeLiteral: boolean,\n scope: IdScope.IdScope,\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(\n Array.map(members, (type) => compileAst(type, false, scope)),\n );\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, scope: IdScope.IdScope) =>\n pipe(\n objectsAst.indexSignatures,\n Array.head,\n Option.match({\n onNone: () =>\n Effect.map(handlePropertySignatures(objectsAst, scope), 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, false, scope),\n type_: compileAst(type, false, scope),\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 = (\n { elements, rest }: SchemaAST.Arrays,\n scope: IdScope.IdScope,\n) => handleArrayElements(elements, rest, scope);\n\nconst handleArrayElements = Effect.fnUntraced(function* (\n elements: SchemaAST.Arrays[\"elements\"],\n rest: SchemaAST.Arrays[\"rest\"],\n scope: IdScope.IdScope,\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, false, scope);\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, false, scope),\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 = (\n objectsAst: SchemaAST.Objects,\n scope: IdScope.IdScope,\n) =>\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, scope);\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":";;;;;;;;;;;;;;;;;;;;;;;;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Aa,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"}
|
|
1
|
+
{"version":3,"file":"SchemaToValidator.js","names":["IdScope.app","scope","GenericId.tableName","GenericId.scope"],"sources":["../src/SchemaToValidator.ts"],"sourcesContent":["import * as IdScope from \"./IdScope.js\";\nimport type * as Callback from \"./Callback.js\";\nimport { CallbackContract } from \"./internal/annotations.js\";\nimport type {\n GenericId as ConvexGenericId,\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 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.js\";\nimport type {\n IsAny,\n IsOptional,\n IsRecord,\n IsRecursive,\n IsUnion,\n TypeError,\n UnionToTuple,\n} from \"./Types.js\";\n\n// Args\n\nexport const compileArgsSchema = <ConfectValue, ConvexValue>(\n argsSchema: Schema.Codec<ConfectValue, ConvexValue>,\n scope: IdScope.IdScope = IdScope.app,\n reservedArgument?: string,\n functionName?: string,\n): PropertyValidators => {\n const ast = Schema.toEncoded(argsSchema).ast;\n\n const validators = Effect.runSync(compileArgsAst(ast, scope));\n if (reservedArgument === undefined) return validators;\n if (Object.hasOwn(validators, reservedArgument)) {\n throw new ReservedArgumentCollision({\n functionName,\n argument: reservedArgument,\n });\n }\n return { ...validators, [reservedArgument]: v.optional(v.any()) };\n};\n\nconst compileArgsAst = (ast: SchemaAST.AST, scope: IdScope.IdScope) =>\n pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", (objectsAst) =>\n Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)\n ? handlePropertySignatures(objectsAst, scope)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),\n );\n\nexport class ReservedArgumentCollision extends Data.TaggedError(\n \"ReservedArgumentCollision\",\n)<{\n readonly functionName: string | undefined;\n readonly argument: string;\n}> {\n override get message() {\n return `${this.functionName} declares the argument \"${this.argument}\", which its profile reserves. Rename the argument.`;\n }\n}\n\n// Returns\n\nexport const compileReturnsSchema = <ConfectValue, ConvexValue>(\n schema: Schema.Codec<ConfectValue, ConvexValue>,\n scope: IdScope.IdScope = IdScope.app,\n): Validator<any, any, any> =>\n Effect.runSync(compileAst(Schema.toEncoded(schema).ast, false, scope));\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 scope: IdScope.IdScope = IdScope.app,\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, false, scope) as Effect.Effect<any>)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.tag(\"Union\", (unionAst) => compileAst(unionAst, false, scope)),\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 [string | number | bigint | boolean | null | ArrayBuffer]\n ? ConvertValueToValidator<Vl>\n : IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? ConvertValueToValidator<Vl>\n : TypeError<\"Provided value is not a valid Convex value\", Vl>;\n\ntype OptionalValue<Vl, Optionality> = Optionality extends \"optional\"\n ? Vl | undefined\n : Vl;\n\ntype ConvertValueToValidator<\n Vl,\n Optionality extends \"required\" | \"optional\" = \"required\",\n> = [Vl] extends [never]\n ? never\n : IsAny<Vl> extends true\n ? VAny<any, Optionality>\n : [Vl] extends [null]\n ? VNull<OptionalValue<null, Optionality>, Optionality>\n : [Vl] extends [boolean]\n ? [boolean] extends [Vl]\n ? VBoolean<OptionalValue<boolean, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>\n : IsUnion<Vl> extends true\n ? UnionValueToValidator<Vl, Optionality>\n : [Vl] extends [number]\n ? [number] extends [Vl]\n ? VFloat64<OptionalValue<number, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>\n : [Vl] extends [bigint]\n ? [bigint] extends [Vl]\n ? VInt64<OptionalValue<bigint, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>\n : [Vl] extends [string]\n ? StringValueToValidator<Vl, Optionality>\n : [Vl] extends [ArrayBuffer]\n ? VBytes<OptionalValue<ArrayBuffer, Optionality>, Optionality>\n : IsRecursive<Vl> extends true\n ? VAny<any, Optionality>\n : Vl extends ReadonlyArray<infer El>\n ? VArray<\n OptionalValue<MutableValue<El[]>, Optionality>,\n ConvertValueToValidator<El>,\n Optionality\n >\n : Vl extends object\n ? ObjectValueToValidator<Vl, Optionality>\n : never;\n\ntype StringValueToValidator<Vl, Optionality extends \"required\" | \"optional\"> =\n Vl extends ConvexGenericId<string>\n ? VId<OptionalValue<Vl, Optionality>, Optionality>\n : [string] extends [Vl]\n ? VString<OptionalValue<string, Optionality>, Optionality>\n : VLiteral<OptionalValue<Vl, Optionality>, Optionality>;\n\ntype ObjectValueToValidator<Vl, Optionality extends \"required\" | \"optional\"> =\n IsRecord<MutableValue<Vl>> extends true\n ? ValueToValidator<Vl[keyof Vl]> extends infer VdValue extends Validator<\n any,\n \"required\",\n any\n >\n ? VRecord<\n OptionalValue<MutableValue<Vl>, Optionality>,\n VString,\n VdValue,\n Optionality\n >\n : never\n : ObjectFieldsToValidators<Vl> extends infer VdFields extends Record<\n string,\n any\n >\n ? VObject<\n OptionalValue<MutableValue<Vl>, Optionality>,\n VdFields,\n Optionality\n >\n : never;\n\ntype ObjectFieldsToValidators<Vl> = {\n -readonly [K in keyof Vl]-?: IsAny<Vl[K]> extends true\n ? IsOptional<Vl, K> extends true\n ? VAny<any, \"optional\">\n : VAny\n : undefined extends Vl[K]\n ? OptionalValueToValidator<Vl[K]>\n : [Vl[K]] extends [ReadonlyValue]\n ? ConvertValueToValidator<Vl[K]>\n : never;\n};\n\nexport type UndefinedOrValueToValidator<Vl extends ReadonlyValue | undefined> =\n undefined extends Vl\n ? OptionalValueToValidator<Vl>\n : [Vl] extends [ReadonlyValue]\n ? ValueToValidator<Vl>\n : never;\n\ntype UnionValueToValidator<Vl, Optionality extends \"required\" | \"optional\"> =\n IsRecursive<Vl> extends true\n ? VAny<any, Optionality>\n : VUnion<\n OptionalValue<MutableValue<Vl>, Optionality>,\n ValueTupleToValidatorTuple<UnionToTuple<Vl>>,\n Optionality\n >;\n\ntype ValueTupleToValidatorTuple<\n VlTuple extends readonly unknown[],\n Acc extends Validator<any, \"required\", any>[] = [],\n> = VlTuple extends\n | [true, false, ...infer VlRest]\n | [false, true, ...infer VlRest]\n ? ValueTupleToValidatorTuple<VlRest, [...Acc, VBoolean]>\n : VlTuple extends [infer Vl, ...infer VlRest]\n ? ValueTupleToValidatorTuple<VlRest, [...Acc, ConvertValueToValidator<Vl>]>\n : Acc;\n\ntype OptionalValueToValidator<Vl> = [Vl] extends [\n (infer Val extends ReadonlyValue) | undefined,\n]\n ? ConvertValueToValidator<Val, \"optional\">\n : never;\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 scope: IdScope.IdScope = IdScope.app,\n): Effect.Effect<\n Validator<any, any, any>,\n | TopLevelMustBeObjectError\n | UnsupportedSchemaTypeError\n | UnsupportedPropertySignatureKeyTypeError\n | IndexSignaturesAreNotSupportedError\n | MixedIndexAndPropertySignaturesAreNotSupportedError\n | OptionalTupleElementsAreNotSupportedError\n | EmptyTupleIsNotSupportedError\n | EmptyUnionIsNotSupportedError\n> => {\n const contract = SchemaAST.resolveAt<Callback.Any>(CallbackContract)(ast);\n if (contract !== undefined) {\n return Effect.gen(function* () {\n const args = yield* compileArgsAst(\n Schema.toEncoded(contract.functionProvenance.args).ast,\n scope,\n );\n const returns = yield* compileAst(\n Schema.toEncoded(contract.functionProvenance.returns).ast,\n false,\n scope,\n );\n return v.function({ fnType: contract.functionType, args, returns });\n });\n }\n return 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) =>\n Effect.succeed(\n GenericId.scope(stringAst) === scope\n ? v.id(tableName)\n : v.string(),\n ),\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, scope),\n ),\n Match.tag(\"Objects\", (objectsAst) => handleObjects(objectsAst, scope)),\n Match.tag(\"Arrays\", (arraysAst) => handleArrays(arraysAst, scope)),\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};\n\nconst handleUnion = (\n { types }: SchemaAST.Union,\n isOptionalPropertyOfTypeLiteral: boolean,\n scope: IdScope.IdScope,\n) => handleUnionTypes(types, isOptionalPropertyOfTypeLiteral, scope);\n\nconst handleUnionTypes = Effect.fnUntraced(function* (\n types: SchemaAST.Union[\"types\"],\n isOptionalPropertyOfTypeLiteral: boolean,\n scope: IdScope.IdScope,\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(\n Array.map(members, (type) => compileAst(type, false, scope)),\n );\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, scope: IdScope.IdScope) =>\n pipe(\n objectsAst.indexSignatures,\n Array.head,\n Option.match({\n onNone: () =>\n Effect.map(handlePropertySignatures(objectsAst, scope), 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, false, scope),\n type_: compileAst(type, false, scope),\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 = (\n { elements, rest }: SchemaAST.Arrays,\n scope: IdScope.IdScope,\n) => handleArrayElements(elements, rest, scope);\n\nconst handleArrayElements = Effect.fnUntraced(function* (\n elements: SchemaAST.Arrays[\"elements\"],\n rest: SchemaAST.Arrays[\"rest\"],\n scope: IdScope.IdScope,\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, false, scope);\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, false, scope),\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 = (\n objectsAst: SchemaAST.Objects,\n scope: IdScope.IdScope,\n) =>\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, scope);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,qBACX,YACA,QAAyBA,KACzB,kBACA,iBACuB;CACvB,MAAM,MAAM,OAAO,UAAU,UAAU,CAAC,CAAC;CAEzC,MAAM,aAAa,OAAO,QAAQ,eAAe,KAAK,KAAK,CAAC;CAC5D,IAAI,qBAAqB,KAAA,GAAW,OAAO;CAC3C,IAAI,OAAO,OAAO,YAAY,gBAAgB,GAC5C,MAAM,IAAI,0BAA0B;EAClC;EACA,UAAU;CACZ,CAAC;CAEH,OAAO;EAAE,GAAG;GAAa,mBAAmB,EAAE,SAAS,EAAE,IAAI,CAAC;CAAE;AAClE;AAEA,MAAM,k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AEA,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"annotations.d.ts","sourceRoot":"","sources":["../../src/internal/annotations.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,qCAAqC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"annotations.js","names":[],"sources":["../../src/internal/annotations.ts"],"sourcesContent":["export const CallbackContract = \"~@confect/core/Callback/Contract\";\n"],"mappings":";AAAA,MAAa,mBAAmB"}
|
package/package.json
CHANGED
package/src/Callback.ts
CHANGED
|
@@ -9,6 +9,7 @@ import * as SchemaGetter from "effect/SchemaGetter";
|
|
|
9
9
|
import * as FunctionProvenance from "./FunctionProvenance.js";
|
|
10
10
|
import * as Ref from "./Ref.js";
|
|
11
11
|
import { getFunctionReference } from "./RefInternal.js";
|
|
12
|
+
import { CallbackContract } from "./internal/annotations.js";
|
|
12
13
|
import type * as RuntimeAndFunctionType from "./RuntimeAndFunctionType.js";
|
|
13
14
|
|
|
14
15
|
export const TypeId = "~@confect/core/Callback";
|
|
@@ -138,6 +139,7 @@ const isHandleOf =
|
|
|
138
139
|
const fromText = <Contract_ extends Any>(
|
|
139
140
|
contract: Contract_,
|
|
140
141
|
text: string,
|
|
142
|
+
reservedArgument?: string,
|
|
141
143
|
): Handle<Contract_> =>
|
|
142
144
|
Object.assign(
|
|
143
145
|
Ref.fromProvenance(
|
|
@@ -147,25 +149,34 @@ const fromText = <Contract_ extends Any>(
|
|
|
147
149
|
// Convex types a handle as a string that is also a function reference.
|
|
148
150
|
text as unknown as FunctionReference<any, any>,
|
|
149
151
|
contract.functionType,
|
|
152
|
+
contract.functionType === "query" ? undefined : reservedArgument,
|
|
150
153
|
),
|
|
151
154
|
{ [HandleTypeId]: contract.id },
|
|
152
155
|
) as unknown as Handle<Contract_>;
|
|
153
156
|
|
|
154
157
|
/**
|
|
155
158
|
* The schema of a handle for `contract`: a string on the wire, a runnable ref
|
|
156
|
-
* once decoded. Use it in a component's function args or tables.
|
|
159
|
+
* once decoded. Use it in a component's function args or tables. It lowers to
|
|
160
|
+
* Convex's `v.function` with the contract's encoded args and returns.
|
|
161
|
+
* `reservedArgument` opts mutation and action handles into context forwarding.
|
|
162
|
+
* The host target must reserve the same argument name.
|
|
157
163
|
*/
|
|
158
164
|
export const handle = <Contract_ extends Any>(
|
|
159
165
|
contract: Contract_,
|
|
166
|
+
options?: {
|
|
167
|
+
readonly reservedArgument?: Contract_["functionType"] extends "query"
|
|
168
|
+
? never
|
|
169
|
+
: string;
|
|
170
|
+
},
|
|
160
171
|
): Schema.Codec<Handle<Contract_>, string> =>
|
|
161
|
-
Schema.String.pipe(
|
|
172
|
+
Schema.String.annotate({ [CallbackContract]: contract }).pipe(
|
|
162
173
|
Schema.decodeTo(
|
|
163
174
|
Schema.declare(isHandleOf(contract), {
|
|
164
175
|
identifier: `Callback.Handle<${contract.id}>`,
|
|
165
176
|
}),
|
|
166
177
|
{
|
|
167
178
|
decode: SchemaGetter.transform((text: string) =>
|
|
168
|
-
fromText(contract, text),
|
|
179
|
+
fromText(contract, text, options?.reservedArgument),
|
|
169
180
|
),
|
|
170
181
|
encode: SchemaGetter.transform(
|
|
171
182
|
(ref: Handle<Contract_>) => ref.convexFunctionName,
|
package/src/SchemaToValidator.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import * as IdScope from "./IdScope.js";
|
|
2
|
+
import type * as Callback from "./Callback.js";
|
|
3
|
+
import { CallbackContract } from "./internal/annotations.js";
|
|
2
4
|
import type {
|
|
3
5
|
GenericId as ConvexGenericId,
|
|
4
6
|
PropertyValidators,
|
|
@@ -51,17 +53,7 @@ export const compileArgsSchema = <ConfectValue, ConvexValue>(
|
|
|
51
53
|
): PropertyValidators => {
|
|
52
54
|
const ast = Schema.toEncoded(argsSchema).ast;
|
|
53
55
|
|
|
54
|
-
const validators =
|
|
55
|
-
ast,
|
|
56
|
-
Match.value,
|
|
57
|
-
Match.tag("Objects", (objectsAst) =>
|
|
58
|
-
Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)
|
|
59
|
-
? handlePropertySignatures(objectsAst, scope)
|
|
60
|
-
: Effect.fail(new IndexSignaturesAreNotSupportedError()),
|
|
61
|
-
),
|
|
62
|
-
Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),
|
|
63
|
-
Effect.runSync,
|
|
64
|
-
);
|
|
56
|
+
const validators = Effect.runSync(compileArgsAst(ast, scope));
|
|
65
57
|
if (reservedArgument === undefined) return validators;
|
|
66
58
|
if (Object.hasOwn(validators, reservedArgument)) {
|
|
67
59
|
throw new ReservedArgumentCollision({
|
|
@@ -72,6 +64,18 @@ export const compileArgsSchema = <ConfectValue, ConvexValue>(
|
|
|
72
64
|
return { ...validators, [reservedArgument]: v.optional(v.any()) };
|
|
73
65
|
};
|
|
74
66
|
|
|
67
|
+
const compileArgsAst = (ast: SchemaAST.AST, scope: IdScope.IdScope) =>
|
|
68
|
+
pipe(
|
|
69
|
+
ast,
|
|
70
|
+
Match.value,
|
|
71
|
+
Match.tag("Objects", (objectsAst) =>
|
|
72
|
+
Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)
|
|
73
|
+
? handlePropertySignatures(objectsAst, scope)
|
|
74
|
+
: Effect.fail(new IndexSignaturesAreNotSupportedError()),
|
|
75
|
+
),
|
|
76
|
+
Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),
|
|
77
|
+
);
|
|
78
|
+
|
|
75
79
|
export class ReservedArgumentCollision extends Data.TaggedError(
|
|
76
80
|
"ReservedArgumentCollision",
|
|
77
81
|
)<{
|
|
@@ -334,6 +338,7 @@ export const compileAst = (
|
|
|
334
338
|
scope: IdScope.IdScope = IdScope.app,
|
|
335
339
|
): Effect.Effect<
|
|
336
340
|
Validator<any, any, any>,
|
|
341
|
+
| TopLevelMustBeObjectError
|
|
337
342
|
| UnsupportedSchemaTypeError
|
|
338
343
|
| UnsupportedPropertySignatureKeyTypeError
|
|
339
344
|
| IndexSignaturesAreNotSupportedError
|
|
@@ -341,8 +346,23 @@ export const compileAst = (
|
|
|
341
346
|
| OptionalTupleElementsAreNotSupportedError
|
|
342
347
|
| EmptyTupleIsNotSupportedError
|
|
343
348
|
| EmptyUnionIsNotSupportedError
|
|
344
|
-
> =>
|
|
345
|
-
|
|
349
|
+
> => {
|
|
350
|
+
const contract = SchemaAST.resolveAt<Callback.Any>(CallbackContract)(ast);
|
|
351
|
+
if (contract !== undefined) {
|
|
352
|
+
return Effect.gen(function* () {
|
|
353
|
+
const args = yield* compileArgsAst(
|
|
354
|
+
Schema.toEncoded(contract.functionProvenance.args).ast,
|
|
355
|
+
scope,
|
|
356
|
+
);
|
|
357
|
+
const returns = yield* compileAst(
|
|
358
|
+
Schema.toEncoded(contract.functionProvenance.returns).ast,
|
|
359
|
+
false,
|
|
360
|
+
scope,
|
|
361
|
+
);
|
|
362
|
+
return v.function({ fnType: contract.functionType, args, returns });
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return isRecursive(ast)
|
|
346
366
|
? Effect.succeed(v.any())
|
|
347
367
|
: pipe(
|
|
348
368
|
ast,
|
|
@@ -421,6 +441,7 @@ export const compileAst = (
|
|
|
421
441
|
),
|
|
422
442
|
Match.exhaustive,
|
|
423
443
|
);
|
|
444
|
+
};
|
|
424
445
|
|
|
425
446
|
const handleUnion = (
|
|
426
447
|
{ types }: SchemaAST.Union,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const CallbackContract = "~@confect/core/Callback/Contract";
|