UNPKG

rescript-schema

Version:

🧬 The fastest parser in the entire JavaScript ecosystem with a focus on small bundle size and top-notch DX

1,928 lines (1,745 loc) • 112 kB
function some(x) { if (x === undefined) { return { BS_PRIVATE_NESTED_SOME_NONE: 0 }; } else if (x !== null && x.BS_PRIVATE_NESTED_SOME_NONE !== undefined) { return { BS_PRIVATE_NESTED_SOME_NONE: x.BS_PRIVATE_NESTED_SOME_NONE + 1 | 0 }; } else { return x; } } function valFromOption(x) { if (x === null || x.BS_PRIVATE_NESTED_SOME_NONE === undefined) { return x; } let depth = x.BS_PRIVATE_NESTED_SOME_NONE; if (depth === 0) { return; } else { return { BS_PRIVATE_NESTED_SOME_NONE: depth - 1 | 0 }; } } /* No side effect */ function get$2(dict, k) { if ((k in dict)) { return some(dict[k]); } } let unsafeDeleteKey = (function (dict,key){ delete dict[key]; }); /* No side effect */ function length(xs) { let _x = xs; let _acc = 0; while (true) { let acc = _acc; let x = _x; if (x === 0) { return acc; } _acc = acc + 1 | 0; _x = x.tl; continue; }} function fillAux(arr, _i, _x) { while (true) { let x = _x; let i = _i; if (x === 0) { return; } arr[i] = x.hd; _x = x.tl; _i = i + 1 | 0; continue; }} function fromArray$1(a) { let _i = a.length - 1 | 0; let _res = /* [] */0; while (true) { let res = _res; let i = _i; if (i < 0) { return res; } _res = { hd: a[i], tl: res }; _i = i - 1 | 0; continue; }} function toArray$1(x) { let len = length(x); let arr = new Array(len); fillAux(arr, 0, x); return arr; } /* No side effect */ let idMap = {}; function create(str) { let v = idMap[str]; if (v !== undefined) { let id = v + 1 | 0; idMap[str] = id; return str + ("/" + id); } idMap[str] = 1; return str; } /* No side effect */ // Generated by ReScript, PLEASE EDIT WITH CARE let immutableEmpty = {}; function fromString(string) { let _idx = 0; while (true) { let idx = _idx; let match = string[idx]; if (match === undefined) { return "\"" + string + "\""; } if (match === "\"") { return JSON.stringify(string); } _idx = idx + 1 | 0; continue; }} function toArray(path) { if (path === "") { return []; } else { return JSON.parse(path.split("\"][\"").join("\",\"")); } } function fromLocation(location) { return "[" + fromString(location) + "]"; } function fromArray(array) { let len = array.length; if (len !== 1) { if (len !== 0) { return "[" + array.map(fromString).join("][") + "]"; } else { return ""; } } else { return "[" + fromString(array[0]) + "]"; } } function concat(path, concatedPath) { return path + concatedPath; } let symbol = Symbol("rescript-schema"); let itemSymbol = Symbol("item"); let Raised = /* @__PURE__ */create("S_Core-RescriptSchema.Raised"); let globalConfig = { r: 0, u: "Strip", n: false }; class RescriptSchemaError extends Error { constructor(code, flag, path) { super(); this.flag = flag; this.code = code; this.path = path; this.s = symbol; this.RE_EXN_ID = Raised; this._1 = this; this.Error = this; this.name = "RescriptSchemaError"; } get message() { return message(this); } get reason() { return reason(this); } } function getOrRethrow(exn) { if ((exn&&exn.s===symbol)) { return exn; } throw exn; } function has(acc, flag) { return (acc & flag) !== 0; } function embed(b, value) { let e = b.g.e; let l = e.length; e[l] = value; return "e[" + l + "]"; } function secondAllocate(v) { let b = this; b.l = b.l + "," + v; } function initialAllocate(v) { let b = this; b.l = v; b.a = secondAllocate; } function rootScope(flag) { let global = { c: "", l: "", a: initialAllocate, v: -1, o: flag, e: [] }; global.g = global; return global; } function allocateScope(b) { ((delete b.a)); let varsAllocation = b.l; if (varsAllocation === "") { return b.c; } else { return "let " + varsAllocation + ";" + b.c; } } function varWithoutAllocation(global) { let newCounter = global.v + 1; global.v = newCounter; return "v" + newCounter; } function _var(_b) { return this.i; } function _notVar(b) { let val = this; let v = varWithoutAllocation(b.g); let i = val.i; if (i === "") { val.b.a(v); } else if (val.b.a !== (void 0)) { val.b.a(v + "=" + i); } else { b.c = b.c + (v + "=" + i + ";"); b.g.a(v); } val.v = _var; val.i = v; return v; } function allocateVal(b) { let v = varWithoutAllocation(b.g); b.a(v); return { b: b, v: _var, i: v, a: false }; } function objectJoin(inlinedLocation, value) { return inlinedLocation + ":" + value + ","; } function arrayJoin(_inlinedLocation, value) { return value + ","; } function make(b, isArray) { return { b: b, v: _notVar, i: "", a: false, j: isArray ? arrayJoin : objectJoin, c: 0, p: "" }; } function add(objectVal, inlinedLocation, val) { objectVal[inlinedLocation] = val; if (val.a) { objectVal.p = objectVal.p + val.i + ","; objectVal.i = objectVal.i + objectVal.j(inlinedLocation, "a[" + (objectVal.c++) + "]"); } else { objectVal.i = objectVal.i + objectVal.j(inlinedLocation, val.i); } } function merge(target, subObjectVal) { let inlinedLocations = Object.keys(subObjectVal); for (let idx = 7, idx_finish = inlinedLocations.length; idx < idx_finish; ++idx) { let inlinedLocation = inlinedLocations[idx]; add(target, inlinedLocation, subObjectVal[inlinedLocation]); } } function complete(objectVal, isArray) { objectVal.i = isArray ? "[" + objectVal.i + "]" : "{" + objectVal.i + "}"; if (objectVal.c) { objectVal.a = true; objectVal.i = "Promise.all([" + objectVal.p + "]).then(a=>(" + objectVal.i + "))"; } return objectVal; } function addKey(b, input, key, val) { return input.v(b) + "[" + key + "]=" + val.i; } function set(b, input, val) { if (input === val) { return ""; } let inputVar = input.v(b); let match = input.a; if (match) { let match$1 = val.a; if (!match$1) { return inputVar + "=Promise.resolve(" + val.i + ")"; } } else { let match$2 = val.a; if (match$2) { input.a = true; return inputVar + "=" + val.i; } } return inputVar + "=" + val.i; } function get(b, targetVal, inlinedLocation) { let val = targetVal[inlinedLocation]; if (val !== undefined) { return val; } else { return { b: b, v: _notVar, i: targetVal.v(b) + ("[" + inlinedLocation + "]"), a: false }; } } function setInlined(b, input, inlined) { return input.v(b) + "=" + inlined; } function map(inlinedFn, input) { return { b: input.b, v: _notVar, i: inlinedFn + "(" + input.i + ")", a: false }; } function transform(b, input, operation) { if (!input.a) { return operation(b, input); } let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let operationInput = { b: b, v: _var, i: varWithoutAllocation(bb.g), a: false }; let operationOutputVal = operation(bb, operationInput); let operationCode = allocateScope(bb); return { b: input.b, v: _notVar, i: input.i + ".then(" + operationInput.v(b) + "=>{" + operationCode + "return " + operationOutputVal.i + "})", a: true }; } function raise(b, code, path) { throw new RescriptSchemaError(code, b.g.o, path); } function embedSyncOperation(b, input, fn) { if (input.a) { return { b: input.b, v: _notVar, i: input.i + ".then(" + embed(b, fn) + ")", a: true }; } else { return map(embed(b, fn), input); } } function embedAsyncOperation(b, input, fn) { if (!(b.g.o & 2)) { raise(b, "UnexpectedAsync", ""); } let val = embedSyncOperation(b, input, fn); val.a = true; return val; } function failWithArg(b, path, fn, arg) { return embed(b, arg => raise(b, fn(arg), path)) + "(" + arg + ")"; } function fail(b, message, path) { return embed(b, () => raise(b, { TAG: "OperationFailed", _0: message }, path)) + "()"; } function effectCtx(b, selfSchema, path) { return { schema: selfSchema, fail: (message, customPathOpt) => { let customPath = customPathOpt !== undefined ? customPathOpt : ""; return raise(b, { TAG: "OperationFailed", _0: message }, path + customPath); } }; } function registerInvalidJson(b, selfSchema, path) { if (b.g.o & 8) { return raise(b, { TAG: "InvalidJsonSchema", _0: selfSchema }, path); } } function invalidOperation(b, path, description) { return raise(b, { TAG: "InvalidOperation", description: description }, path); } function withCatch(b, input, $$catch, appendSafe, fn) { let prevCode = b.c; b.c = ""; let errorVar = varWithoutAllocation(b.g); let maybeResolveVal = $$catch(b, errorVar); let catchCode = "if(" + (errorVar + "&&" + errorVar + ".s===s") + "){" + b.c; b.c = ""; let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let fnOutput = fn(bb); b.c = b.c + allocateScope(bb); let isNoop = fnOutput.i === input.i && b.c === ""; if (appendSafe !== undefined) { appendSafe(b, fnOutput); } if (isNoop) { return fnOutput; } let isAsync = fnOutput.a; let output = input === fnOutput ? input : ( appendSafe !== undefined ? fnOutput : ({ b: b, v: _notVar, i: "", a: isAsync }) ); let catchCode$1 = maybeResolveVal !== undefined ? catchLocation => catchCode + ( catchLocation === 1 ? "return " + maybeResolveVal.i : set(b, output, maybeResolveVal) ) + ("}else{throw " + errorVar + "}") : param => catchCode + "}throw " + errorVar; b.c = prevCode + ("try{" + b.c + ( isAsync ? setInlined(b, output, fnOutput.i + ".catch(" + errorVar + "=>{" + catchCode$1(1) + "})") : set(b, output, fnOutput) ) + "}catch(" + errorVar + "){" + catchCode$1(0) + "}"); return output; } function withPathPrepend(b, input, path, maybeDynamicLocationVar, appendSafe, fn) { if (path === "" && maybeDynamicLocationVar === undefined) { return fn(b, input, path); } try { return withCatch(b, input, (b, errorVar) => { b.c = errorVar + ".path=" + fromString(path) + "+" + ( maybeDynamicLocationVar !== undefined ? "'[\"'+" + maybeDynamicLocationVar + "+'\"]'+" : "" ) + errorVar + ".path"; }, appendSafe, b => fn(b, input, "")); } catch (exn) { let error = getOrRethrow(exn); throw new RescriptSchemaError(error.code, error.flag, path + "[]" + error.path); } } function typeFilterCode(b, schema, input, path) { let inputVar = input.v(b); return "if(" + schema.f(b, inputVar) + "){" + failWithArg(b, path, input => ({ TAG: "InvalidType", expected: schema, received: input }), inputVar) + "}"; } function parseWithTypeValidation(b, schema, input, path) { if (schema.f !== undefined && (b.g.o & 1 || schema.t.TAG === "literal")) { b.c = b.c + typeFilterCode(b, schema, input, path); } return schema.b(b, input, schema, path); } function noop(_b, input, param, param$1) { return input; } function invalidJson(b, input, selfSchema, path) { registerInvalidJson(b, selfSchema, path); return input; } function noopOperation(i) { return i; } function compile(builder, schema, flag) { if (flag & 8 && schema["~r"]().t.TAG === "option") { throw new RescriptSchemaError({ TAG: "InvalidJsonSchema", _0: schema }, flag, ""); } let b = rootScope(flag); let input = { b: b, v: _var, i: "i", a: false }; let output = builder(b, input, schema, ""); schema.i = output.a; if (b.l !== "") { b.c = "let " + b.l + ";" + b.c; } if (schema.f !== undefined && (flag & 1 || schema.t.TAG === "literal")) { b.c = typeFilterCode(b, schema, input, "") + b.c; } if (b.c === "" && output === input && !(flag & 22)) { return noopOperation; } let inlinedOutput = flag & 4 ? "void 0" : output.i; if (flag & 16) { inlinedOutput = "JSON.stringify(" + inlinedOutput + ")"; } if (flag & 2 && !output.a) { inlinedOutput = "Promise.resolve(" + inlinedOutput + ")"; } let inlinedFunction = "i=>{" + b.c + "return " + inlinedOutput + "}"; let ctxVarValue1 = b.g.e; return new Function("e", "s", "return " + inlinedFunction)(ctxVarValue1, symbol); } function operationFn(s, o) { if ((o in s)) { return (s[o]); } let ss = o & 32 ? s["~r"]() : s; let f = compile(ss.b, ss, o); ((s[o] = f)); return f; } function compile$1(schema, input, output, mode, typeValidationOpt) { let typeValidation = typeValidationOpt !== undefined ? typeValidationOpt : true; let flag = 0; let exit = 0; switch (output) { case "Output" : case "Input" : exit = 1; break; case "Assert" : flag = flag | 4; break; case "Json" : flag = flag | 8; break; case "JsonString" : flag = flag | 24; break; } if (exit === 1 && output === input) { throw new Error("[rescript-schema] Can't compile operation to converting value to self"); } if (mode !== "Sync") { flag = flag | 2; } if (typeValidation) { flag = flag | 1; } if (input === "Output") { flag = flag | 32; } let fn = operationFn(schema, flag); if (input !== "JsonString") { return fn; } let flag$1 = flag; return jsonString => { try { return fn(JSON.parse(jsonString)); } catch (exn) { throw new RescriptSchemaError({ TAG: "OperationFailed", _0: exn.message }, flag$1, ""); } }; } function toSelf() { return this; } function onlyChild(factory, schema) { return function () { let reversed = schema["~r"](); if (reversed === schema) { return this; } else { return factory(reversed); } }; } function value(literal) { return literal.value; } function isJsonable(literal) { return literal.j; } function toString(literal) { return literal.s; } function arrayFilterBuilder(b, inputVar, literal) { let items = literal.i; return inputVar + "!==" + embed(b, literal.value) + "&&(!Array.isArray(" + inputVar + ")||" + inputVar + ".length!==" + items.length + ( items.length > 0 ? "||" + items.map((literal, idx) => literal.f(b, inputVar + "[" + idx + "]", literal)).join("||") : "" ) + ")"; } function dictFilterBuilder(b, inputVar, literal) { let items = literal.i; let fields = Object.keys(items); let numberOfFields = fields.length; return inputVar + "!==" + embed(b, value) + "&&(typeof " + inputVar + "!==\"object\"||!" + inputVar + "||Object.keys(" + inputVar + ").length!==" + numberOfFields + ( numberOfFields > 0 ? "||" + fields.map(field => { let literal = items[field]; return literal.f(b, inputVar + "[" + fromString(field) + "]", literal); }).join("||") : "" ) + ")"; } function inlinedStrictEqualFilterBuilder(param, inputVar, literal) { return inputVar + "!==" + literal.s; } function strictEqualFilterBuilder(b, inputVar, literal) { return inputVar + "!==" + embed(b, literal.value); } let undefined_value = undefined; let $$undefined = { kind: "Undefined", value: undefined_value, s: "undefined", f: inlinedStrictEqualFilterBuilder, j: false }; let null_value = null; let $$null = { kind: "Null", value: null_value, s: "null", f: inlinedStrictEqualFilterBuilder, j: true }; let nan_value = NaN; function nan_f(param, inputVar, param$1) { return "!Number.isNaN(" + inputVar + ")"; } let nan = { kind: "NaN", value: nan_value, s: "NaN", f: nan_f, j: false }; function parseInternal(value) { let typeOfValue = typeof value; if (typeOfValue === "symbol") { return { kind: "Symbol", value: value, s: value.toString(), f: strictEqualFilterBuilder, j: false }; } else if (typeOfValue === "boolean") { return { kind: "Boolean", value: value, s: value ? "true" : "false", f: inlinedStrictEqualFilterBuilder, j: true }; } else if (typeOfValue === "string") { return { kind: "String", value: value, s: fromString(value), f: inlinedStrictEqualFilterBuilder, j: true }; } else if (typeOfValue === "function") { return { kind: "Function", value: value, s: value.toString(), f: strictEqualFilterBuilder, j: false }; } else if (typeOfValue === "object") { if (value === null) { return $$null; } else if (Array.isArray(value)) { let items = []; let isJsonable = true; let string = "["; for (let idx = 0, idx_finish = value.length; idx < idx_finish; ++idx) { let itemValue = value[idx]; let itemLiteral = parseInternal(itemValue); if (isJsonable && !itemLiteral.j) { isJsonable = false; } if (idx !== 0) { string = string + ", "; } string = string + itemLiteral.s; items.push(itemLiteral); } return { kind: "Array", value: value, s: string + "]", f: arrayFilterBuilder, j: isJsonable, i: some(items) }; } else if (value.constructor === Object) { let items$1 = {}; let string$1 = "{ "; let isJsonable$1 = true; let fields = Object.keys(value); let numberOfFields = fields.length; for (let idx$1 = 0; idx$1 < numberOfFields; ++idx$1) { let field = fields[idx$1]; let itemValue$1 = value[field]; let itemLiteral$1 = parseInternal(itemValue$1); if (isJsonable$1 && !itemLiteral$1.j) { isJsonable$1 = false; } if (idx$1 !== 0) { string$1 = string$1 + ", "; } string$1 = string$1 + (fromString(field) + ": " + itemLiteral$1.s); items$1[field] = itemLiteral$1; } return { kind: "Dict", value: value, s: string$1 + " }", f: dictFilterBuilder, j: isJsonable$1, i: some(items$1) }; } else { return { kind: "Object", value: value, s: Object.prototype.toString.call(value), f: strictEqualFilterBuilder, j: false }; } } else if (typeOfValue === "undefined") { return $$undefined; } else if (typeOfValue === "number") { if (Number.isNaN(value)) { return nan; } else { return { kind: "Number", value: value, s: value.toString(), f: inlinedStrictEqualFilterBuilder, j: true }; } } else { return { kind: "BigInt", value: value, s: value.toString() + "n", f: inlinedStrictEqualFilterBuilder, j: false }; } } let parse = parseInternal; function isAsync(schema) { let v = schema.i; if (v !== 0) { return v; } try { let b = rootScope(2); let input = { b: b, v: _var, i: "i", a: false }; let output = schema.b(b, input, schema, ""); schema.i = output.a; return schema.i; } catch (exn) { getOrRethrow(exn); return false; } } function reverse(schema) { return schema["~r"](); } function parseOrThrow(any, schema) { return operationFn(schema, 1)(any); } function parseJsonStringOrThrow(jsonString, schema) { let tmp; try { tmp = JSON.parse(jsonString); } catch (exn) { throw new RescriptSchemaError({ TAG: "OperationFailed", _0: exn.message }, 1, ""); } return parseOrThrow(tmp, schema); } function parseAsyncOrThrow(any, schema) { return operationFn(schema, 3)(any); } function convertOrThrow(input, schema) { return operationFn(schema, 0)(input); } function convertToJsonOrThrow(any, schema) { return operationFn(schema, 8)(any); } function convertToJsonStringOrThrow(input, schema) { return operationFn(schema, 24)(input); } function convertAsyncOrThrow(any, schema) { return operationFn(schema, 2)(any); } function reverseConvertOrThrow(value, schema) { return operationFn(schema, 32)(value); } function reverseConvertToJsonOrThrow(value, schema) { return operationFn(schema, 40)(value); } function reverseConvertToJsonStringOrThrow(value, schema, spaceOpt) { let space = spaceOpt !== undefined ? spaceOpt : 0; return JSON.stringify(reverseConvertToJsonOrThrow(value, schema), null, space); } function assertOrThrow(any, schema) { return operationFn(schema, 5)(any); } function wrapExnToFailure(exn) { if ((exn&&exn.s===symbol)) { return { success: false, error: exn }; } throw exn; } function js_safe(fn) { try { return { success: true, value: fn() }; } catch (exn) { return wrapExnToFailure(exn); } } function js_safeAsync(fn) { try { return fn().then(value => ({ success: true, value: value }), wrapExnToFailure); } catch (exn) { return Promise.resolve(wrapExnToFailure(exn)); } } function makeReverseSchema(name, tagged, metadataMap, builder, maybeTypeFilter) { return { t: tagged, n: name, "~r": toSelf, b: builder, f: maybeTypeFilter, i: 0, m: metadataMap }; } function makeSchema(name, tagged, metadataMap, builder, maybeTypeFilter, reverse) { return { t: tagged, n: name, "~r": function () { let original = this; let reversed = reverse.call(original); let reversed$1 = original !== reversed && typeof reversed.t === "string" ? makeReverseSchema(reversed.n, reversed.t, reversed.m, reversed.b, reversed.f) : reversed; original["~r"] = () => reversed$1; reversed$1["~r"] = () => original; return reversed$1; }, b: builder, f: maybeTypeFilter, i: 0, m: metadataMap }; } function make$1(namespace, name) { return namespace + ":" + name; } let Id = { make: make$1 }; let empty = {}; function set$1(map, id, metadata) { if (map === empty) { return ({[id]:metadata}); } let copy = Object.assign({}, map); copy[id] = metadata; return copy; } function get$1(schema, id) { return schema.m[id]; } function set$2(schema, id, metadata) { let metadataMap = set$1(schema.m, id, metadata); return makeSchema(schema.n, schema.t, metadataMap, schema.b, schema.f, () => { let schema$1 = schema["~r"](); return makeReverseSchema(schema$1.n, schema$1.t, metadataMap, schema$1.b, schema$1.f); }); } function primitiveName() { return this.t; } function makePrimitiveSchema(tagged, builder, maybeTypeFilter) { return makeSchema(primitiveName, tagged, empty, builder, maybeTypeFilter, toSelf); } function recursive(fn) { let r = "r" + globalConfig.r; globalConfig.r = globalConfig.r + 1 | 0; let placeholder = { m: empty, t: "unknown", n: () => "<recursive>", b: (b, input, param, param$1) => transform(b, input, (_b, input) => map(r, input)), "~r": () => makeReverseSchema(primitiveName, "unknown", empty, (_b, input, param, param$1) => map(r, input), undefined) }; let schema = fn(placeholder); placeholder.f = schema.f; placeholder.t = schema.t; let initialParseOperationBuilder = schema.b; schema.b = (b, input, selfSchema, path) => { let inputVar = input.v(b); let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let opOutput = initialParseOperationBuilder(bb, input, selfSchema, ""); let opBodyCode = allocateScope(bb) + ("return " + opOutput.i); b.c = b.c + ("let " + r + "=" + inputVar + "=>{" + opBodyCode + "};"); return withPathPrepend(b, input, path, undefined, undefined, (b, input, param) => transform(b, input, (_b, input) => { let output = map(r, input); if (opOutput.a) { output.a = true; placeholder.b = (b, input, param, param$1) => transform(b, input, (_b, input) => { let output = map(r, input); output.a = true; return output; }); } return output; })); }; let initialReverse = schema["~r"].bind(schema); schema["~r"] = () => { let initialReversed = initialReverse(); let reversed = makeReverseSchema(initialReversed.n, initialReversed.t, initialReversed.m, (b, input, selfSchema, path) => { let inputVar = input.v(b); let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let initialInput = { b: bb, v: input.v, i: input.i, a: input.a }; let opOutput = initialReversed.b(bb, initialInput, selfSchema, ""); let opBodyCode = allocateScope(bb) + ("return " + opOutput.i); b.c = b.c + ("let " + r + "=" + inputVar + "=>{" + opBodyCode + "};"); return withPathPrepend(b, input, path, undefined, undefined, (_b, input, param) => map(r, input)); }, initialReversed.f); reversed["~r"] = () => schema; schema["~r"] = () => reversed; return reversed; }; return schema; } function setName(schema, name) { return makeSchema(() => name, schema.t, schema.m, schema.b, schema.f, () => schema["~r"]()); } function removeTypeValidation(schema) { return makeSchema(schema.n, schema.t, schema.m, schema.b, undefined, () => schema["~r"]()); } function internalRefine(schema, refiner) { return makeSchema(schema.n, schema.t, schema.m, (b, input, selfSchema, path) => transform(b, schema.b(b, input, schema, path), (b, input) => { let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let rCode = refiner(bb, input.v(bb), selfSchema, path); b.c = b.c + allocateScope(bb) + rCode; return input; }), schema.f, () => { let schema$1 = schema["~r"](); return makeReverseSchema(schema$1.n, schema$1.t, schema$1.m, (b, input, selfSchema, path) => { let input$1 = transform(b, input, (b, input) => { b.c = b.c + refiner(b, input.v(b), selfSchema, path); return input; }); return schema$1.b(b, input$1, schema$1, path); }, schema$1.f); }); } function refine(schema, refiner) { return internalRefine(schema, (b, inputVar, selfSchema, path) => embed(b, refiner(effectCtx(b, selfSchema, path))) + "(" + inputVar + ");"); } function addRefinement(schema, metadataId, refinement, refiner) { let refinements = schema.m[metadataId]; return internalRefine(set$2(schema, metadataId, refinements !== undefined ? refinements.concat(refinement) : [refinement]), refiner); } function transform$1(schema, transformer) { return makeSchema(schema.n, schema.t, schema.m, (b, input, selfSchema, path) => { let input$1 = schema.b(b, input, schema, path); let match = transformer(effectCtx(b, selfSchema, path)); let parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { return invalidOperation(b, path, "The S.transform doesn't allow parser and asyncParser at the same time. Remove parser in favor of asyncParser"); } else { return embedSyncOperation(b, input$1, parser); } } let asyncParser = match.a; if (asyncParser !== undefined) { return embedAsyncOperation(b, input$1, asyncParser); } else if (match.s !== undefined) { return invalidOperation(b, path, "The S.transform parser is missing"); } else { return input$1; } }, schema.f, () => { let schema$1 = schema["~r"](); return makeReverseSchema(primitiveName, "unknown", empty, (b, input, selfSchema, path) => { let match = transformer(effectCtx(b, selfSchema, path)); let serializer = match.s; if (serializer === undefined) { if (match.a !== undefined || match.p !== undefined) { return invalidOperation(b, path, "The S.transform serializer is missing"); } else { return schema$1.b(b, input, schema$1, path); } } let input$1 = embedSyncOperation(b, input, serializer); return schema$1.b(b, input$1, schema$1, path); }, undefined); }); } function custom(name, definer) { return makeSchema(() => name, "unknown", empty, (b, input, selfSchema, path) => { registerInvalidJson(b, selfSchema, path); let match = definer(effectCtx(b, selfSchema, path)); let parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { return invalidOperation(b, path, "The S.custom doesn't allow parser and asyncParser at the same time. Remove parser in favor of asyncParser"); } else { return embedSyncOperation(b, input, parser); } } let asyncParser = match.a; if (asyncParser !== undefined) { return embedAsyncOperation(b, input, asyncParser); } else if (match.s !== undefined) { return invalidOperation(b, path, "The S.custom parser is missing"); } else { return input; } }, undefined, () => makeReverseSchema(() => name, "unknown", empty, (b, input, selfSchema, path) => { registerInvalidJson(b, selfSchema, path); let match = definer(effectCtx(b, selfSchema, path)); let serializer = match.s; if (serializer !== undefined) { return embedSyncOperation(b, input, serializer); } else if (match.a !== undefined || match.p !== undefined) { return invalidOperation(b, path, "The S.custom serializer is missing"); } else { return input; } }, undefined)); } function literal(value) { let literal$1 = parseInternal(value); return makeSchema(() => literal$1.s, { TAG: "literal", _0: literal$1 }, empty, literal$1.j ? noop : invalidJson, (b, inputVar) => literal$1.f(b, inputVar, literal$1), toSelf); } let unit = literal((void 0)); let defaultMetadataId = "rescript-schema:Option.default"; function name() { return this.t._0.n() + " | undefined"; } function $$default(schema) { return schema.m[defaultMetadataId]; } function makeBuilder(isNullInput, isNullOutput) { return (b, input, selfSchema, path) => { let childSchema = selfSchema.t._0; let childSchemaTag = childSchema.t.TAG; let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let itemInput = !(b.g.o & 1) && (childSchema.t === "unknown" || childSchemaTag === "option" || childSchemaTag === "literal" && childSchema.t._0.value === (void 0)) ? ({ b: bb, v: _notVar, i: embed(bb, valFromOption) + "(" + input.v(b) + ")", a: false }) : input; let itemOutput = childSchema.b(bb, itemInput, childSchema, path); let itemCode = allocateScope(bb); let inputLiteral = isNullInput ? "null" : "void 0"; let ouputLiteral = isNullOutput ? "null" : "void 0"; let isTransformed = inputLiteral !== ouputLiteral || itemOutput !== input; let output = isTransformed ? ({ b: b, v: _notVar, i: "", a: itemOutput.a }) : input; if (itemCode !== "" || isTransformed) { b.c = b.c + ("if(" + input.v(b) + "!==" + inputLiteral + "){" + itemCode + set(b, output, itemOutput) + "}" + ( inputLiteral !== ouputLiteral || output.a ? "else{" + set(b, output, { b: b, v: _notVar, i: ouputLiteral, a: false }) + "}" : "" )); } return output; }; } function maybeTypeFilter(schema, inlinedNoneValue) { if (schema.f !== undefined) { return (b, inputVar) => inputVar + "!==" + inlinedNoneValue + "&&(" + schema.f(b, inputVar) + ")"; } } function factory(schema) { return makeSchema(name, { TAG: "option", _0: schema }, empty, makeBuilder(false, false), maybeTypeFilter(schema, "void 0"), onlyChild(factory, schema)); } function getWithDefault(schema, $$default) { return makeSchema(schema.n, schema.t, set$1(schema.m, defaultMetadataId, $$default), (b, input, param, path) => transform(b, schema.b(b, input, schema, path), (b, input) => { let inputVar = input.v(b); let tmp; tmp = $$default.TAG === "Value" ? embed(b, $$default._0) : embed(b, $$default._0) + "()"; return { b: b, v: _notVar, i: inputVar + "===void 0?" + tmp + ":" + inputVar, a: false }; }), schema.f, () => { let reversed = schema["~r"](); if (reversed.t.TAG === "option") { return reversed.t._0; } else { return reversed; } }); } function getOr(schema, defalutValue) { return getWithDefault(schema, { TAG: "Value", _0: defalutValue }); } function getOrWith(schema, defalutCb) { return getWithDefault(schema, { TAG: "Callback", _0: defalutCb }); } function factory$1(schema) { return makeSchema(() => schema.n() + " | null", { TAG: "null", _0: schema }, empty, makeBuilder(true, false), maybeTypeFilter(schema, "null"), () => { let child = schema["~r"](); return makeReverseSchema(name, { TAG: "option", _0: child }, empty, makeBuilder(false, true), maybeTypeFilter(schema, "void 0")); }); } function nullable(schema) { return factory(factory$1(schema)); } function builder(b, input, selfSchema, path) { b.c = b.c + failWithArg(b, path, input => ({ TAG: "InvalidType", expected: selfSchema, received: input }), input.i) + ";"; return input; } let schema = makeSchema(primitiveName, "never", empty, builder, undefined, toSelf); let metadataId = "rescript-schema:Array.refinements"; function refinements(schema) { let m = schema.m[metadataId]; if (m !== undefined) { return m; } else { return []; } } function typeFilter(_b, inputVar) { return "!Array.isArray(" + inputVar + ")"; } function name$1() { return "array<" + this.t._0.n() + ">"; } function factory$2(schema) { return makeSchema(name$1, { TAG: "array", _0: schema }, empty, (b, input, param, path) => { let inputVar = input.v(b); let iteratorVar = varWithoutAllocation(b.g); let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let itemInput = { b: bb, v: _notVar, i: inputVar + "[" + iteratorVar + "]", a: false }; let itemOutput = withPathPrepend(bb, itemInput, path, iteratorVar, undefined, (b, input, path) => parseWithTypeValidation(b, schema, input, path)); let itemCode = allocateScope(bb); let isTransformed = itemInput !== itemOutput; let output = isTransformed ? ({ b: b, v: _notVar, i: "new Array(" + inputVar + ".length)", a: false }) : input; if (isTransformed || itemCode !== "") { b.c = b.c + ("for(let " + iteratorVar + "=0;" + iteratorVar + "<" + inputVar + ".length;++" + iteratorVar + "){" + itemCode + ( isTransformed ? addKey(b, output, iteratorVar, itemOutput) : "" ) + "}"); } if (itemOutput.a) { return { b: output.b, v: _notVar, i: "Promise.all(" + output.i + ")", a: true }; } else { return output; } }, typeFilter, onlyChild(factory$2, schema)); } function typeFilter$1(b, inputVar) { let tagged = this.t; let code = "typeof " + inputVar + "!==\"object\"||!" + inputVar + ( tagged.unknownKeys === "Strict" ? "||Array.isArray(" + inputVar + ")" : "" ); let items = tagged.items; for (let idx = 0, idx_finish = items.length; idx < idx_finish; ++idx) { let match = items[idx]; let schema = match.schema; if (schema.t.TAG === "literal") { code = code + "||" + schema.f(b, inputVar + ("[" + match.inlinedLocation + "]")); } } return code; } function name$2() { let tagged = this.t; if (tagged.items.length === 0) { return "{}"; } else { return "{ " + tagged.items.map(item => item.location + ": " + item.schema.n() + ";").join(" ") + " }"; } } function setUnknownKeys(schema, unknownKeys, deep) { let match = schema.t; if (typeof match !== "object") { return schema; } if (match.TAG !== "object") { return schema; } if (match.unknownKeys === unknownKeys) { return schema; } let advanced = match.advanced; let items = match.items; let tagged; if (deep) { let newItems = []; let newFields = {}; for (let idx = 0, idx_finish = items.length; idx < idx_finish; ++idx) { let item = items[idx]; let newSchema = setUnknownKeys(item.schema, unknownKeys, deep); let newItem = newSchema === item.schema ? item : ({ schema: newSchema, location: item.location, inlinedLocation: item.inlinedLocation }); newFields[item.location] = newItem; newItems.push(newItem); } tagged = { TAG: "object", items: newItems, fields: newFields, unknownKeys: unknownKeys, advanced: advanced }; } else { tagged = { TAG: "object", items: items, fields: match.fields, unknownKeys: unknownKeys, advanced: advanced }; } return { t: tagged, n: schema.n, "~r": schema["~r"], b: schema.b, f: schema.f, i: schema.i, m: schema.m }; } function strip(schema) { return setUnknownKeys(schema, "Strip", false); } function deepStrip(schema) { return setUnknownKeys(schema, "Strip", true); } function strict(schema) { return setUnknownKeys(schema, "Strict", false); } function deepStrict(schema) { return setUnknownKeys(schema, "Strict", true); } function name$3() { return "[" + this.t.items.map(item => item.schema.n()).join(", ") + "]"; } function typeFilter$2(b, inputVar) { let items = this.t.items; let length = items.length; let code = typeFilter(b, inputVar) + ("||" + inputVar + ".length!==" + length); for (let idx = 0; idx < length; ++idx) { let match = items[idx]; let schema = match.schema; if (schema.t.TAG === "literal") { code = code + "||" + schema.f(b, inputVar + ("[" + match.inlinedLocation + "]")); } } return code; } function typeFilter$3(_b, inputVar) { return "typeof " + inputVar + "!==\"object\"||!" + inputVar; } function factory$3(schema) { return makeSchema(() => "dict<" + schema.n() + ">", { TAG: "dict", _0: schema }, empty, (b, input, param, path) => { let inputVar = input.v(b); let keyVar = varWithoutAllocation(b.g); let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let itemInput = { b: bb, v: _notVar, i: inputVar + "[" + keyVar + "]", a: false }; let itemOutput = withPathPrepend(bb, itemInput, path, keyVar, undefined, (b, input, path) => parseWithTypeValidation(b, schema, input, path)); let itemCode = allocateScope(bb); let isTransformed = itemInput !== itemOutput; let output = isTransformed ? ({ b: b, v: _notVar, i: "{}", a: false }) : input; if (isTransformed || itemCode !== "") { b.c = b.c + ("for(let " + keyVar + " in " + inputVar + "){" + itemCode + ( isTransformed ? addKey(b, output, keyVar, itemOutput) : "" ) + "}"); } if (!itemOutput.a) { return output; } let resolveVar = varWithoutAllocation(b.g); let rejectVar = varWithoutAllocation(b.g); let asyncParseResultVar = varWithoutAllocation(b.g); let counterVar = varWithoutAllocation(b.g); let outputVar = output.v(b); return { b: b, v: _notVar, i: "new Promise((" + resolveVar + "," + rejectVar + ")=>{let " + counterVar + "=Object.keys(" + outputVar + ").length;for(let " + keyVar + " in " + outputVar + "){" + outputVar + "[" + keyVar + "].then(" + asyncParseResultVar + "=>{" + outputVar + "[" + keyVar + "]=" + asyncParseResultVar + ";if(" + counterVar + "--===1){" + resolveVar + "(" + outputVar + ")}}," + rejectVar + ")}})", a: true }; }, typeFilter$3, onlyChild(factory$3, schema)); } let schema$1 = makeSchema(primitiveName, "unknown", empty, invalidJson, undefined, toSelf); let metadataId$1 = "rescript-schema:String.refinements"; function refinements$1(schema) { let m = schema.m[metadataId$1]; if (m !== undefined) { return m; } else { return []; } } let cuidRegex = /^c[^\s-]{8,}$/i; let uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; let emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; let datetimeRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/; function typeFilter$4(_b, inputVar) { return "typeof " + inputVar + "!==\"string\""; } let schema$2 = makePrimitiveSchema("string", noop, typeFilter$4); function factory$4(schema, spaceOpt) { let space = spaceOpt !== undefined ? spaceOpt : 0; return makeSchema(primitiveName, "string", empty, (b, input, param, path) => { let jsonVal = allocateVal(b); b.c = b.c + ("try{" + jsonVal.i + "=JSON.parse(" + input.i + ")}catch(t){" + failWithArg(b, path, message => ({ TAG: "OperationFailed", _0: message }), "t.message") + "}"); return parseWithTypeValidation(b, schema, jsonVal, path); }, typeFilter$4, () => { let reversed = schema["~r"](); return makeReverseSchema(reversed.n, reversed.t, reversed.m, (b, input, param, path) => { let prevFlag = b.g.o; b.g.o = prevFlag | 8; if (reversed.t.TAG === "option") { raise(b, { TAG: "InvalidJsonSchema", _0: reversed }, ""); } let output = { b: b, v: _notVar, i: "JSON.stringify(" + reversed.b(b, input, reversed, path).i + ( space > 0 ? ",null," + space : "" ) + ")", a: false }; b.g.o = prevFlag; return output; }, reversed.f); }); } function typeFilter$5(_b, inputVar) { return "typeof " + inputVar + "!==\"boolean\""; } let schema$3 = makePrimitiveSchema("boolean", noop, typeFilter$5); let metadataId$2 = "rescript-schema:Int.refinements"; function refinements$2(schema) { let m = schema.m[metadataId$2]; if (m !== undefined) { return m; } else { return []; } } function refinement(inputVar) { return inputVar + ">2147483647||" + inputVar + "<-2147483648||" + inputVar + "%1!==0"; } function typeFilter$6(_b, inputVar) { return "typeof " + inputVar + "!==\"number\"||" + refinement(inputVar); } let schema$4 = makePrimitiveSchema("int32", noop, typeFilter$6); let metadataId$3 = "rescript-schema:Float.refinements"; function refinements$3(schema) { let m = schema.m[metadataId$3]; if (m !== undefined) { return m; } else { return []; } } function typeFilter$7(_b, inputVar) { return "typeof " + inputVar + "!==\"number\"" + ( globalConfig.n ? "" : "||Number.isNaN(" + inputVar + ")" ); } let schema$5 = makePrimitiveSchema("number", noop, typeFilter$7); function typeFilter$8(_b, inputVar) { return "typeof " + inputVar + "!==\"bigint\""; } let schema$6 = makePrimitiveSchema("bigint", invalidJson, typeFilter$8); function parse$1(b, schemas, path, input, output) { let isMultiple = schemas.length > 1; let loop = (idx, errorCodes) => { if (idx === schemas.length) { return failWithArg(b, path, internalErrors => ({ TAG: "InvalidUnion", _0: internalErrors }), "[" + errorCodes + "]"); } let schema = schemas[idx]; let parserCode; try { let bb = { c: "", l: "", a: initialAllocate, g: b.g }; let itemOutput = schema.b(bb, input, schema, ""); if (itemOutput !== input) { bb.c = bb.c + set(bb, output, itemOutput); } parserCode = allocateScope(bb); } catch (exn) { parserCode = "throw " + embed(b, getOrRethrow(exn)); } if (!isMultiple) { return parserCode; } let errorVar = "e" + idx; return "try{" + parserCode + "}catch(" + errorVar + "){" + loop(idx + 1 | 0, errorCodes + errorVar + ",") + "}"; }; return loop(0, ""); } function factory$5(schemas) { let len = schemas.length; if (len === 1) { return schemas[0]; } if (len !== 0) { return makeSchema(() => schemas.map(s => s.n()).join(" | "), { TAG: "union", _0: schemas }, empty, (b, input, selfSchema, path) => { let schemas = selfSchema.t._0; let inputVar = input.v(b); let output = { b: b, v: _notVar, i: inputVar, a: false }; let byTypeFilter = {}; let typeFilters = []; for (let idx = 0, idx_finish = schemas.length; idx < idx_finish; ++idx) { let schema = schemas[idx]; let typeFilterCode = schema.f !== undefined ? schema.f(b, inputVar) : ""; let schemas$1 = get$2(byTypeFilter, typeFilterCode); if (schemas$1 !== undefined) { schemas$1.push(schema); } else { typeFilters.push(typeFilterCode); byTypeFilter[typeFilterCode] = [schema]; } } let loopTypeFilters = (_idx, _maybeUnknownParser) => { while (true) { let maybeUnknownParser = _maybeUnknownParser; let idx = _idx; if (idx === typeFilters.length) { if (maybeUnknownParser !== undefined) { return maybeUnknownParser; } else { return failWithArg(b, path, received => ({ TAG: "InvalidType", expected: selfSchema, received: received }), inputVar); } } let typeFilterCode = typeFilters[idx]; let schemas = byTypeFilter[typeFilterCode]; let parserCode = parse$1(b, schemas, path, input, output); if (typeFilterCode === "") { _maybeUnknownParser = parserCode; _idx = idx + 1 | 0; continue; } let tmp = parserCode === "" ? "" : "}else{" + parserCode; return "if(" + typeFilterCode + "){" + loopTypeFilters(idx + 1 | 0, maybeUnknownParser) + tmp + "}"; } }; b.c = b.c + loopTypeFilters(0, undefined); if (output.a) { return { b: b, v: _notVar, i: "Promise.resolve(" + output.i + ")", a: true }; } else { return output; } }, undefined, function () { let original = this; let schemas = original.t._0; return factory$5(schemas.map(s => s["~r"]())); }); } throw new Error("[rescript-schema] S.union requires at least one item"); } function $$enum(values) { return factory$5(values.map(literal)); } function preprocess(schema, transformer) { let unionSchemas = schema.t; if (typeof unionSchemas === "object" && unionSchemas.TAG === "union") { return makeSchema(schema.n, { TAG: "union", _0: unionSchemas._0.map(unionSchema => preprocess(unionSchema, transformer)) }, schema.m, schema.b, schema.f, schema["~r"]); } return makeSchema(schema.n, schema.t, schema.m, (b, input, selfSchema, path) => { let match = transformer(effectCtx(b, selfSchema, path)); let parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { return invalidOperation(b, path, "The S.preprocess doesn't allow parser and asyncParser at the same time. Remove parser in favor of asyncParser"); } else { return parseWithTypeValidation(b, schema, embedSyncOperation(b, input, parser), path); } } let asyncParser = match.a; if (asyncParser !== undefined) { return transform(b, embedAsyncOperation(b, input, asyncParser), (b, input) => parseWithTypeValidation(b, schema, input, path)); } else { return parseWithTypeValidation(b, schema, input, path); } }, undefined, () => { let reversed = schema["~r"](); return makeReverseSchema(primitiveName, reversed.t, empty, (b, input, param, path) => { let input$1 = reversed.b(b, input, reversed, path); let match = transformer(effectCtx(b, schema, path)); let serializer = match.s; if (serializer !== undefined) { return embedSyncOperation(b, input$1, serializer); } else { return input$1; } }, undefined); }); } function list(schema) { return transform$1(factory$2(schema), param => ({ p: fromArray$1, s: toArray$1 })); } function json(validate) { return makeSchema(() => "JSON", { TAG: "JSON", validated: validate }, empty, validate ? (b, input, selfSchema, path) => { let parse = (input, pathOpt) => { let path$1 = pathOpt !== undefined ? pathOpt : path; let match = typeof input; if (match === "string" || match === "boolean") { return input; } if (match !== "object") { if (match === "number" && !Number.isNaN(input)) { return input; } else { return raise(b, { TAG: "InvalidType", expected: selfSchema, received: input }, path$1); } } if (input === null) { return input; } if (Array.isArray(input)) { let output = []; for (let idx = 0, idx_finish = input.length; idx < idx_finish; ++idx) { let inputItem = input[idx]; let location = idx.toString(); output.push(parse(inputItem, path$1 + ("[" + fromString(location) + "]"))); } return output; } let keys = Object.keys(input); let output$1 = {}; for (let idx$1 = 0, idx_finish$1 = keys.length; idx$1 < idx_finish$1; ++idx$1) { let key = keys[idx$1]; let field = input[key]; output$1[key] = parse(field, path$1 + ("[" + fromString(key) + "]")); } return output$1; }; return map(embed(b, parse), input); } : noop, undefined, function () { if (validate) { return json(false); } else { return this; } }); } let Catch = {}; function passingTypeFilt