UNPKG

react-box-tools

Version:

Box tools react components, utils and hooks

622 lines (621 loc) 17.5 kB
var L = Object.defineProperty; var W = (s, r, e) => r in s ? L(s, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[r] = e; var c = (s, r, e) => W(s, typeof r != "symbol" ? r + "" : r, e); var y; ((s) => { function r(e) { throw new Error(); } s.assertNever = r, s.arrayToEnum = (e) => { const t = {}; for (const a of e) t[a] = a; return t; }, s.objectValues = (e) => (0, s.objectKeys)(e).map(function(t) { return e[t]; }), s.objectKeys = typeof Object.keys == "function" ? (e) => Object.keys(e) : (e) => { const t = []; for (const a in e) Object.prototype.hasOwnProperty.call(e, a) && t.push(a); return t; }; })(y || (y = {})); const g = y.arrayToEnum([ "string", "array", "object", "unknown" ]), C = (s) => { switch (typeof s) { case "string": return g.string; case "object": return Array.isArray(s) ? g.array : g.object; default: return g.unknown; } }, d = y.arrayToEnum([ "invalid_type", "custom", "invalid_string", "too_small", "too_big", "required" ]), w = class w extends Error { constructor(e) { super(); c(this, "errors", []); c(this, "addError", (e) => { this.errors = [...this.errors, e]; }); c(this, "addErrors", (e = []) => { this.errors = [...this.errors, ...e]; }); const t = new.target.prototype; Object.setPrototypeOf ? Object.setPrototypeOf(this, t) : this.__proto__ = t, this.name = "Validation", this.errors = e; } getFieldErrors(e = (t) => t.message) { const t = {}; for (const a of this.errors) a.path.length > 0 && (t[a.path[0]] = t[a.path[0]] || [], t[a.path[0]].push(e(a))); return t; } getFieldError(e) { let t = this.errors; e && e.length > 0 && (t = this.errors.filter((n) => e.includes(n.path[0]))); const a = {}; for (const n of t) n.path.length > 0 && (a[n.path[0]] || (a[n.path[0]] = n.message)); return a; } }; c(w, "create", (e) => new w(e)); let I = w; const N = (s, r) => { let e; switch (s.code) { case d.invalid_type: e = `Expected ${s.expected}, received ${s.received}`; break; case d.invalid_string: typeof s.validation == "object" ? "startWith" in s.validation ? e = `Must start with "${s.validation.startWith}"` : "endWith" in s.validation ? e = `Must end with "${s.validation.endWith}"` : y.assertNever(s.validation) : s.validation !== "regex" ? e = `Invalid ${s.validation}` : e = "Invalid"; break; case d.too_small: s.type === "array" ? e = `Must contain ${s.inclusive ? "at least" : "more than"} ${s.minimum} element(s)` : s.type === "string" ? e = `Must contain ${s.inclusive ? "at least" : "over"} ${s.minimum} character(s)` : e = "Invalid"; break; case d.too_big: s.type === "array" ? e = `Must contain ${s.inclusive ? "at most" : "less than"} ${s.maximum} element(s)` : s.type === "string" ? e = `Must contain ${s.inclusive ? "at most" : "under"} ${s.maximum} character(s)` : e = "Invalid"; break; case d.custom: e = "Invalid"; break; case d.required: e = "Required"; break; default: e = r.defaultError, y.assertNever(s); } return { message: e }; }, V = (s) => { const { data: r, path: e, errorMaps: t, errorData: a } = s, n = [...e, ...a.path || []], i = { ...a, path: n }; let o = ""; const f = t.filter((l) => !!l).slice().reverse(); for (const l of f) o = l(i, { data: r, defaultError: o }).message; return { ...a, path: n, message: a.message || o }; }; function h(s, r) { const e = V({ errorData: r, data: s.data, path: s.path, errorMaps: [ s.common.errorMap, // contextual error map is first priority s.schemaErrorMap, // then schema-bound map if available N // then global default map ].filter((t) => !!t) }); s.common.issues.push(e); } class v { constructor() { c(this, "value", "valid"); } dirty() { this.value === "valid" && (this.value = "dirty"); } abort() { this.value !== "aborted" && (this.value = "aborted"); } static mergeArray(r, e) { const t = []; for (const a of e) { if (a.status === "aborted") return b; a.status === "dirty" && r.dirty(), t.push(a.value); } return { status: r.value, value: t }; } static async mergeObjectAsync(r, e) { const t = []; for (const a of e) t.push({ key: await a.key, value: await a.value }); return v.mergeObjectSync(r, t); } static mergeObjectSync(r, e) { const t = {}; for (const a of e) { const { key: n, value: i } = a; if (n.status === "aborted" || i.status === "aborted") return b; n.status === "dirty" && r.dirty(), i.status === "dirty" && r.dirty(), (typeof i.value < "u" || a.alwaysSet) && (t[n.value] = i.value); } return { status: r.value, value: t }; } } const b = Object.freeze({ status: "aborted" }), U = (s) => ({ status: "dirty", value: s }), z = (s) => ({ status: "valid", value: s }), Y = (s) => s.status === "aborted", B = (s) => s.status === "dirty", A = (s) => s.status === "valid", T = (s) => typeof Promise !== void 0 && s instanceof Promise; class M { constructor(r, e, t, a) { c(this, "parent"); c(this, "data"); c(this, "_path"); c(this, "_key"); this.parent = r, this.data = e, this._path = t, this._key = a; } get path() { return this._path.concat(this._key); } } const q = (s, r) => { if (A(r)) return { ok: !0, data: r.value }; if (!s.common.issues.length) throw new Error("Validation failed"); return { ok: !1, validation: new I(s.common.issues) }; }; class j { constructor(r) { c(this, "_output"); c(this, "_input"); c(this, "_def"); this._def = r, this.validate = this.validate.bind(this), this.add = this.add.bind(this), this.array = this.array.bind(this), this.convert = this.convert.bind(this); } _getOrReturnCtx(r, e) { return e || { common: r.parent.common, data: r.data, type: C(r.data), schemaErrorMap: this._def.errorMap, path: r.path, parent: r.parent }; } _processInputParams(r) { return { status: new v(), ctx: { common: r.parent.common, data: r.data, type: C(r.data), schemaErrorMap: this._def.errorMap, path: r.path, parent: r.parent } }; } _validationSync(r) { const e = this._validation(r); if (T(e)) throw new Error("Synchronous validation in promise."); return e; } _validationAsync(r) { const e = this._validation(r); return Promise.resolve(e); } async validate(r, e) { const t = { common: { issues: [], errorMap: e == null ? void 0 : e.errorMap, async: !0 }, path: (e == null ? void 0 : e.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: r, type: C(r) }, a = this._validation({ data: r, path: [], parent: t }), n = await (T(a) ? a : Promise.resolve(a)); return q(t, n); } add(r, e) { const t = (a) => typeof e == "string" || typeof e > "u" ? { message: e } : typeof e == "function" ? e(a) : e; return this._refinement((a, n) => { const i = r(a), o = () => n.addIssue({ code: d.custom, ...t(a) }); return typeof Promise < "u" && i instanceof Promise ? i.then((f) => f ? !0 : (o(), !1)) : i ? !0 : (o(), !1); }); } refinement(r, e) { return this._refinement((t, a) => r(t) ? !0 : (a.addIssue( typeof e == "function" ? e(t, a) : e ), !1)); } _refinement(r) { return new x({ schema: this, type: "Effect", effect: { type: "refinement", refinement: r } }); } array() { return $.create(this); } convert(r) { return new x({ schema: this, type: "Effect", effect: { type: "convert", convert: r } }); } } const O = class O extends j { innerType() { return this._def.schema; } _validation(r) { const { status: e, ctx: t } = this._processInputParams(r), a = this._def.effect || null, n = { addIssue: (i) => { h(t, i), i.fatal ? e.abort() : e.dirty(); }, get path() { return t.path; } }; if (n.addIssue = n.addIssue.bind(n), a.type === "refinement") { const i = (o) => { const f = a.refinement(o, n); if (t.common.async) return Promise.resolve(f); if (f instanceof Promise) throw new Error( "Async operation." ); return o; }; if (t.common.async === !1) { const o = this._def.schema._validationSync({ data: t.data, path: t.path, parent: t }); return o.status === "aborted" ? b : (o.status === "dirty" && e.dirty(), i(o.value), { status: e.value, value: o.value }); } else return this._def.schema._validationAsync({ data: t.data, path: t.path, parent: t }).then((o) => o.status === "aborted" ? b : (o.status === "dirty" && e.dirty(), i(o.value).then(() => ({ status: e.value, value: o.value })))); } if (a.type === "convert") if (t.common.async === !1) { const i = this._def.schema._validationSync({ data: t.data, path: t.path, parent: t }); if (!A(i)) return i; const o = a.convert(i.value, n); if (o instanceof Promise) throw new Error( "Async operation" ); return { status: e.value, value: o }; } else return this._def.schema._validationAsync({ data: t.data, path: t.path, parent: t }).then((i) => A(i) ? Promise.resolve(a.convert(i.value, n)).then( (o) => ({ status: e.value, value: o }) ) : i); y.assertNever(a); } }; c(O, "create", (r, e) => new O({ schema: r, type: "Effect", effect: e })); let x = O; var E = /* @__PURE__ */ ((s) => (s.String = "String", s.Array = "Array", s.Object = "Object", s.Effect = "Effect", s))(E || {}), u; ((s) => { s.errToObj = (r) => typeof r == "string" ? { message: r } : r || {}, s.toString = (r) => typeof r == "string" ? r : r == null ? void 0 : r.message; })(u || (u = {})); var m; let $ = (m = class extends j { _validation(r) { const { ctx: e, status: t } = this._processInputParams(r), a = this._def; if (e.type !== g.array) return h(e, { code: d.invalid_type, expected: g.array, received: e.type }), b; if (a.minLength !== null && e.data.length < a.minLength.value && (h(e, { code: d.too_small, minimum: a.minLength.value, type: "array", inclusive: !0, message: a.minLength.message }), t.dirty()), a.maxLength !== null && e.data.length > a.maxLength.value && (h(e, { code: d.too_big, maximum: a.maxLength.value, type: "array", inclusive: !0, message: a.maxLength.message }), t.dirty()), e.common.async) return Promise.all( e.data.map((i, o) => a.type._validationAsync( new M(e, i, e.path, o) )) ).then((i) => v.mergeArray(t, i)); const n = e.data.map((i, o) => a.type._validationSync( new M(e, i, e.path, o) )); return v.mergeArray(t, n); } min(r, e) { return new m({ ...this._def, minLength: { value: r, message: u.toString(e) } }); } max(r, e) { return new m({ ...this._def, maxLength: { value: r, message: u.toString(e) } }); } length(r, e) { return this.min(r, e).max(r, e); } nonempty(r) { return this.min(1, r); } }, c(m, "create", (r) => new m({ type: r, minLength: null, maxLength: null, typeName: E.Array })), m); const G = $.create; var S; ((s) => { s.mergeShapes = (r, e) => ({ ...r, ...e // second overwrites first }); })(S || (S = {})); var p; let D = (p = class extends j { constructor() { super(...arguments); c(this, "_cached", null); } _getCached() { if (this._cached !== null) return this._cached; const e = this._def.shape(), t = y.objectKeys(e); return this._cached = { shape: e, keys: t }; } _validation(e) { var t = e.data; (t === void 0 || t == null) && (e.data = {}); const { status: a, ctx: n } = this._processInputParams(e), { shape: i, keys: o } = this._getCached(), f = []; for (const l of o) { const k = i[l], P = n.data[l]; f.push({ key: { status: "valid", value: l }, value: k._validation( new M(n, P, n.path, l) ), alwaysSet: l in n.data }); } return n.common.async ? Promise.resolve().then(async () => { const l = []; for (const k of f) { const P = await k.key; l.push({ key: P, value: await k.value, alwaysSet: k.alwaysSet }); } return l; }).then((l) => v.mergeObjectSync(a, l)) : v.mergeObjectSync(a, f); } }, c(p, "create", (e) => new p({ shape: () => e, typeName: E.Object })), p); const H = D.create, F = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i, _ = class _ extends j { constructor() { super(...arguments); c(this, "_regex", (e, t, a) => this.refinement((n) => e.test(n), { validation: t, code: d.invalid_string, ...u.errToObj(a) })); c(this, "trim", () => new _({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] })); } _validation(e) { (e.data === void 0 || e.data == null) && (e.data = ""); const t = new v(); let a; for (const n of this._def.checks) switch (n.kind) { case "min": e.data.length < n.value && (a = this._getOrReturnCtx(e, a), h(a, { code: d.too_small, minimum: n.value, type: "string", inclusive: !0, message: n.message }), t.dirty()); break; case "max": e.data.length > n.value && (a = this._getOrReturnCtx(e, a), h(a, { code: d.too_big, maximum: n.value, type: "string", inclusive: !0, message: n.message }), t.dirty()); break; case "required": e.data.length == 0 && (a = this._getOrReturnCtx(e, a), h(a, { code: d.required, message: n.message }), t.dirty()); break; case "email": F.test(e.data) || (a = this._getOrReturnCtx(e, a), h(a, { validation: "email", code: d.invalid_string, message: n.message }), t.dirty()); break; case "url": try { new URL(e.data); } catch { a = this._getOrReturnCtx(e, a), h(a, { validation: "url", code: d.invalid_string, message: n.message }), t.dirty(); } break; case "regex": n.regex.lastIndex = 0, n.regex.test(e.data) || (a = this._getOrReturnCtx(e, a), h(a, { validation: "regex", code: d.invalid_string, message: n.message }), t.dirty()); break; case "trim": e.data = e.data.trim(); break; case "startWith": e.data.startsWith(n.value) || (a = this._getOrReturnCtx(e, a), h(a, { code: d.invalid_string, validation: { startWith: n.value }, message: n.message }), t.dirty()); break; case "endWith": e.data.endsWith(n.value) || (a = this._getOrReturnCtx(e, a), h(a, { code: d.invalid_string, validation: { endWith: n.value }, message: n.message }), t.dirty()); break; default: y.assertNever(n); break; } return { status: t.value, value: e.data }; } _addCheck(e) { return new _({ ...this._def, checks: [...this._def.checks, e] }); } required(e) { return this._addCheck({ kind: "required", ...u.errToObj(e) }); } email(e) { return this._addCheck({ kind: "email", ...u.errToObj(e) }); } url(e) { return this._addCheck({ kind: "url", ...u.errToObj(e) }); } regex(e, t) { return this._addCheck({ kind: "regex", regex: e, ...u.errToObj(t) }); } startWith(e, t) { return this._addCheck({ kind: "startWith", value: e, ...u.errToObj(t) }); } endWith(e, t) { return this._addCheck({ kind: "endWith", value: e, ...u.errToObj(t) }); } min(e, t) { return this._addCheck({ kind: "min", value: e, ...u.errToObj(t) }); } max(e, t) { return this._addCheck({ kind: "max", value: e, ...u.errToObj(t) }); } length(e, t) { return this.min(e, t).max(e, t); } }; c(_, "create", () => new _({ checks: [], type: E.String })); let R = _; const J = R.create; export { U as DIRTY, x as Effect, d as ErrorCode, b as INVALID, z as OK, E as SchemaKind, j as SchemaOf, M as ValidateInputPath, I as Validation, v as ValidationStatus, h as addError, G as array, Y as isAborted, T as isAsync, B as isDirty, A as isValid, V as makeIssue, H as object, J as string };